feat(research): run durable backtests in a bounded worker pool

This commit is contained in:
Boki 2026-10-24 17:41:00 -04:00
parent bbf0dd4453
commit 26b97265c6
15 changed files with 1730 additions and 129 deletions

View file

@ -7,9 +7,11 @@ import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from '../../backtest
import { BacktestConflictError } from '../../backtest/run-repository';
import type { OrchestratorServices as IServiceContainer } from '../../types';
const _BacktestIdSchema = z.object({
backtestId: z.string(),
});
const runIdSchema = z
.string()
.uuid()
.transform(value => value.toLowerCase());
const controlSchema = z.object({ runId: runIdSchema.optional() }).strict();
export function createBacktestRoutes(container: IServiceContainer): Hono {
const app = new Hono();
@ -60,103 +62,60 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
app.post('/', runBacktest);
app.post('/run', runBacktest);
// Stop running backtest
app.post('/stop', async c => {
try {
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.stopBacktest(runId);
return c.json({
message: 'Backtest stop requested',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error stopping backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to stop backtest',
},
500
);
}
const controlError = (error: unknown) => ({
body: { error: error instanceof Error ? error.message : 'Backtest control failed' },
status:
error instanceof BacktestConflictError
? (409 as const)
: error instanceof z.ZodError || error instanceof SyntaxError
? (400 as const)
: (500 as const),
});
// Pause running backtest
app.post('/pause', async c => {
try {
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.pauseBacktest(runId);
return c.json({
message: 'Backtest paused',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error pausing backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to pause backtest',
},
500
);
}
});
// Resume paused backtest
app.post('/resume', async c => {
try {
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.resumeBacktest(runId);
return c.json({
message: 'Backtest resumed',
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error resuming backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to resume backtest',
},
500
);
}
});
// Set backtest speed
// Empty legacy bodies still target the sole active run. Invalid JSON never becomes an untargeted control.
for (const [path, operation, message] of [
['/stop', 'stopBacktest', 'Backtest stop requested'],
['/pause', 'pauseBacktest', 'Backtest paused'],
['/resume', 'resumeBacktest', 'Backtest resumed'],
] as const) {
app.post(path, async c => {
try {
const text = await c.req.text();
const { runId } = controlSchema.parse(text.trim() ? JSON.parse(text) : {});
await backtestEngine[operation](runId);
return c.json({ message, timestamp: new Date().toISOString() });
} catch (error) {
const failure = controlError(error);
return c.json(failure.body, failure.status);
}
});
}
app.post('/speed', async c => {
try {
const body = await c.req.json();
const { speed, runId } = z
.object({
speed: z.number().finite().positive().nullable().default(1),
runId: z.string().uuid().optional(),
runId: runIdSchema.optional(),
})
.parse(body);
.strict()
.parse(await c.req.json());
await backtestEngine.setSpeedMultiplier(speed, runId);
return c.json({
message: 'Backtest speed updated',
speed: speed === null ? 'unlimited' : speed,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error setting backtest speed:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to set speed',
},
500
);
const failure = controlError(error);
return c.json(failure.body, failure.status);
}
});
// Get backtest progress
app.get('/progress', async c => {
app.get('/progress', c => {
try {
const status = backtestEngine.getStatus();
const runId = runIdSchema.optional().parse(c.req.query('runId'));
const status = backtestEngine.getStatus(runId);
if (runId !== undefined && status.runId !== runId) {
throw new BacktestConflictError('No matching active backtest');
}
return c.json({
status: status.isPaused ? 'paused' : status.isRunning ? 'running' : 'idle',
progress: status.progress,
@ -166,18 +125,25 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
runId: status.runId,
});
} catch (error) {
container.logger.error('Error getting backtest progress:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get progress',
},
500
);
const failure = controlError(error);
return c.json(failure.body, failure.status);
}
});
// Stream backtest events (Server-Sent Events)
app.get('/stream', async c => {
app.get('/stream', c => {
let runId: string;
try {
const requested = runIdSchema.optional().parse(c.req.query('runId'));
const target = requested ?? backtestEngine.getStatus().runId;
if (!target) {
throw new BacktestConflictError('An exact runId is required when no backtest is active');
}
runId = target;
} catch (error) {
const failure = controlError(error);
return c.json(failure.body, failure.status);
}
c.header('Content-Type', 'text/event-stream');
c.header('Cache-Control', 'no-cache');
c.header('Connection', 'keep-alive');
@ -194,25 +160,40 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
dispose();
controller.close();
};
const onProgress = (data: unknown) => {
const matches = (data: unknown) =>
data !== null && typeof data === 'object' && 'runId' in data && data.runId === runId;
const send = (data: unknown) => {
if (!closed) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
}
};
const onComplete = (data: unknown) => {
onProgress({ event: 'complete', data });
finish();
const onProgress = (data: unknown) => {
if (matches(data)) {
send(data);
}
};
const onError = (error: unknown) => {
onProgress({
event: 'error',
error: error instanceof Error ? error.message : String(error),
});
finish();
const onComplete = (data: unknown) => {
if (matches(data)) {
send({ event: 'complete', runId, data });
finish();
}
};
const onError = (data: unknown) => {
if (matches(data)) {
const error = (data as { error: unknown }).error;
send({
event: 'error',
runId,
error: error instanceof Error ? error.message : String(error),
});
finish();
}
};
const onCancelled = (data: unknown) => {
onProgress({ event: 'cancelled', data });
finish();
if (matches(data)) {
send({ event: 'cancelled', runId, data });
finish();
}
};
dispose = () => {
closed = true;

View file

@ -0,0 +1,197 @@
import { EventEmitter } from 'node:events';
import { z } from 'zod';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestRunner } from './BacktestRunner';
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from './execution-engine';
import { BacktestConflictError } from './run-repository';
export type ResearchConcurrency = 1 | 2 | 4;
export function assertResearchConcurrency(value: unknown): asserts value is ResearchConcurrency {
if (value !== 1 && value !== 2 && value !== 4) {
throw new Error('Research concurrency must be 1, 2, or 4');
}
}
/** The existing runner surface, shared by production pool and single-runner fixtures. */
export type ResearchBacktestRuntime = Pick<
BacktestRunner,
| 'runQueued'
| 'runBacktest'
| 'stopBacktest'
| 'pauseBacktest'
| 'resumeBacktest'
| 'setSpeedMultiplier'
| 'shutdown'
> &
Pick<EventEmitter, 'on' | 'off'> & {
getStatus(runId?: string): ReturnType<BacktestRunner['getStatus']>;
};
type Reservation = {
runner: BacktestRunner;
execution: ReturnType<BacktestRunner['runQueued']>;
};
const runIdSchema = z
.string()
.uuid()
.transform(value => value.toLowerCase());
/** Independent portfolios only. BullMQ remains the sole waiting queue; SQL owns attempts. */
export class ResearchBacktestPool extends EventEmitter implements ResearchBacktestRuntime {
private readonly runners: readonly BacktestRunner[];
private readonly reservations = new Map<string, Reservation>();
private closing = false;
private shutdownWork: Promise<void> | undefined;
constructor(
private readonly dependencies: {
runners: readonly BacktestRunner[];
logger: Pick<Logger, 'error'>;
}
) {
super();
assertResearchConcurrency(dependencies.runners.length);
if (new Set(dependencies.runners).size !== dependencies.runners.length) {
throw new Error('Research slots require distinct runner instances');
}
this.runners = [...dependencies.runners];
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
parseBacktestRequest(input);
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
// Intentionally not async: reserve before any load/claim and return the exact shared promise.
runQueued(input: string): ReturnType<BacktestRunner['runQueued']> {
const runId = runIdSchema.parse(input);
if (this.closing) {
return Promise.reject(new BacktestConflictError('Backtest pool is shutting down'));
}
const existing = this.reservations.get(runId);
if (existing) {
return existing.execution;
}
const occupied = new Set([...this.reservations.values()].map(value => value.runner));
const runner = this.runners.find(candidate => !occupied.has(candidate));
if (!runner) {
return Promise.reject(new BacktestConflictError('All research slots are occupied'));
}
const forward = (event: string) => (data: unknown) => {
if (data && typeof data === 'object') {
this.publish(event, { ...data, runId });
}
};
const progress = forward('progress');
const complete = forward('complete');
const cancelled = forward('cancelled');
runner.on('progress', progress);
runner.on('complete', complete);
runner.on('cancelled', cancelled);
const execution = Promise.resolve()
.then(() => runner.runQueued(runId))
.catch((error: unknown) => {
if (!(error instanceof BacktestCancelledError)) {
this.publish('error', { runId, error });
}
throw error;
})
.finally(() => {
runner.off('progress', progress);
runner.off('complete', complete);
runner.off('cancelled', cancelled);
this.reservations.delete(runId);
});
this.reservations.set(runId, { runner, execution });
return execution;
}
private publish(event: string, value: unknown) {
if (event === 'error' && !this.listenerCount('error')) {
return;
}
try {
this.emit(event, value);
} catch (error) {
this.dependencies.logger.error('Research pool observer failed', { event, error });
}
}
private resolve(input?: string): [string, Reservation] {
if (input !== undefined) {
const runId = runIdSchema.parse(input);
const reservation = this.reservations.get(runId);
if (!reservation) {
throw new BacktestConflictError('No matching active backtest');
}
return [runId, reservation];
}
if (this.reservations.size > 1) {
throw new BacktestConflictError('Multiple backtests are active; an exact runId is required');
}
const only = this.reservations.entries().next().value;
if (!only) {
throw new BacktestConflictError('No matching active backtest');
}
return only;
}
async stopBacktest(input?: string) {
const [runId, { runner }] = this.resolve(input);
// A reservation is not a SQL claim. The runner retains its pending/committing refusal rules.
await runner.stopBacktest(runId);
}
async pauseBacktest(input?: string) {
const [runId, { runner }] = this.resolve(input);
await runner.pauseBacktest(runId);
}
async resumeBacktest(input?: string) {
const [runId, { runner }] = this.resolve(input);
await runner.resumeBacktest(runId);
}
async setSpeedMultiplier(speed: number | null, input?: string) {
const [runId, { runner }] = this.resolve(input);
await runner.setSpeedMultiplier(speed, runId);
}
getStatus(input?: string): ReturnType<BacktestRunner['getStatus']> {
if (input === undefined && this.reservations.size === 0) {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId: undefined };
}
const [runId, { runner }] = this.resolve(input);
const status = runner.getStatus();
if (status.runId !== runId) {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId };
}
return { ...status, runId };
}
shutdown(): Promise<void> {
if (!this.shutdownWork) {
this.closing = true;
const executions = [...this.reservations.values()].map(value => value.execution);
this.shutdownWork = (async () => {
const [results] = await Promise.all([
Promise.allSettled(
this.runners.map(runner => Promise.resolve().then(() => runner.shutdown()))
),
// Each job already reports its outcome to its caller/queue. An unclaimed
// load deferred by closure is not a failure to drain the worker itself.
Promise.allSettled(executions),
]);
const errors = new Set(
results.flatMap(result =>
result.status === 'rejected' && !(result.reason instanceof BacktestCancelledError)
? [result.reason as unknown]
: []
)
);
if (errors.size) {
throw new AggregateError([...errors], 'Could not cleanly drain the research pool');
}
})();
}
return this.shutdownWork;
}
}

View file

@ -1,8 +1,8 @@
import { asValue, type AwilixContainer } from 'awilix';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestRunner } from './backtest/BacktestRunner';
import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { assertResearchConcurrency, ResearchBacktestPool } from './backtest/ResearchBacktestPool';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
@ -41,12 +41,15 @@ export async function registerOrchestratorServices(
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
maxConcurrent?: number;
canonicalPaper?: PaperConfigurationInput;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'research-only' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
const maxConcurrent = options.maxConcurrent === undefined ? 1 : options.maxConcurrent;
assertResearchConcurrency(maxConcurrent);
if (options.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
@ -100,16 +103,22 @@ export async function registerOrchestratorServices(
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
})
: undefined;
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
const runner = new ResearchBacktestPool({
runners: Array.from(
{ length: maxConcurrent },
() =>
new BacktestRunner({
engine: new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
),
engineName: 'native',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
})
),
logger: services.logger,
});
const analytics = new AnalyticsService(services);
@ -118,7 +127,6 @@ export async function registerOrchestratorServices(
Object.assign(custom, {
StorageService: storageService,
AnalyticsService: analytics,
BacktestEngine: engine,
BacktestRunner: runner,
...(paper ? { CanonicalPaperRuntime: paper } : {}),
});
@ -127,15 +135,13 @@ export async function registerOrchestratorServices(
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
BacktestRunner: ResearchBacktestPool;
orchestratorServices: IServiceContainer;
}
>;
canonicalContainer.register({
StorageService: asValue(storageService),
AnalyticsService: asValue(analytics),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
@ -147,8 +153,9 @@ export async function registerOrchestratorServices(
if (paper && canonicalPaper && options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: maxConcurrent });
} catch (error) {
await runner.shutdown().catch(() => {});
await paper?.shutdown().catch(() => {});
throw error;
}

View file

@ -1,13 +1,13 @@
import { z } from 'zod';
import { BaseHandler, Handler, Operation } from '@stock-bot/handlers';
import { defined } from '@stock-bot/invariants';
import type { BacktestRunner } from '../../backtest/BacktestRunner';
import { LEGACY_EXECUTION_RETIRED } from '../../backtest/execution-engine';
import type { ResearchBacktestRuntime } from '../../backtest/ResearchBacktestPool';
import type { OrchestratorServices } from '../../types';
@Handler('orchestrator')
export class BacktestHandler extends BaseHandler<OrchestratorServices> {
private readonly runner: BacktestRunner;
private readonly runner: ResearchBacktestRuntime;
constructor(services: OrchestratorServices) {
super(services);
this.runner = defined(services.custom?.BacktestRunner, 'Backtest runner is unavailable');

View file

@ -1,5 +1,6 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { assertResearchConcurrency } from './backtest/ResearchBacktestPool';
import { paperConfigurationSchema } from './contracts/paper-runtime';
import { validatePaperConfiguration } from './paper/feed';
import {
@ -28,6 +29,9 @@ export async function createContainer(
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
// Fail before opening connections as well as before registering runtime services.
assertSupportedComposition(role, useRustEngine);
const maxConcurrent =
settings?.backtesting?.maxConcurrent === undefined ? 1 : settings.backtesting.maxConcurrent;
assertResearchConcurrency(maxConcurrent);
if (settings?.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
@ -58,6 +62,7 @@ export async function createContainer(
await registerOrchestratorServices(container, {
role,
useRustEngine,
maxConcurrent,
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,

View file

@ -47,13 +47,12 @@ export const ModeConfigSchema = z.discriminatedUnion('mode', [
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
custom?: Partial<{
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
BacktestRunner: import('./backtest/ResearchBacktestPool').ResearchBacktestRuntime;
StorageService: import('./services/StorageService').StorageService;
MarketDataService: import('./services/MarketDataService').MarketDataService;
ExecutionService: import('./services/ExecutionService').ExecutionService;
AnalyticsService: import('./services/AnalyticsService').AnalyticsService;
StrategyManager: import('./strategies/StrategyManager').StrategyManager;
BacktestEngine: import('./backtest/execution-engine').BacktestExecutionEngine;
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
ModeManager: import('./core/ModeManager').ModeManager;
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;