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 { researchRuntimeSchema } from '@stock-bot/stock-config/diagnostics'; 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 & { getStatus(runId?: string): ReturnType; getDiagnostics?(): z.infer; }; type Reservation = { runner: BacktestRunner; execution: ReturnType; }; 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(); private closing = false; private shutdownWork: Promise | undefined; constructor( private readonly dependencies: { runners: readonly BacktestRunner[]; logger: Pick; } ) { 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 { 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 { 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); } getDiagnostics() { return { accepting: !this.closing, capacity: this.runners.length, slots: this.runners.map(runner => runner.getAttemptDiagnostics()), }; } getStatus(input?: string): ReturnType { 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 { 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; } }