import { createHash, randomUUID as uuidv4 } from 'node:crypto'; import { at } from '@stock-bot/invariants'; import { type CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research'; import { HistoricalDataRequestError } from '@stock-bot/types'; import { getWebSocketHandler } from '../../websocket/run-updates'; import type { WebSocketHandler } from '../../websocket/run-updates'; import { admitCanonicalRequest } from '../canonical-research.service'; import { BacktestRetentionError, CatalogExecutionUnavailableError, RunSubmissionConflictError, type BacktestContainer, type BacktestTransport, type Run, type RunRequest, type RunSubmission, } from './contracts'; import { mapBacktest, mapRun } from './mapping'; const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004'; /** Focused runs operations; transaction order is preserved. */ export class BacktestRuns { private wsHandler: WebSocketHandler | null = null; constructor( private readonly container: BacktestContainer, private readonly request: BacktestTransport ) {} async createRun(request: RunRequest, submission?: RunSubmission): Promise { const runId = uuidv4(); const multiplier = request.speedMultiplier ?? null; if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) { throw new HistoricalDataRequestError('Speed multiplier must be positive or null'); } // Hash submission intent, not the mutable definition or newly generated run ID. // A retry after an edit must still return the original run and its frozen snapshot. const submissionHash = submission ? createHash('sha256') .update( JSON.stringify({ version: 1, backtestId: request.backtestId, speedMultiplier: multiplier, }) ) .digest('hex') : null; const row = await this.container.postgres.transaction(async client => { const replay = async () => { if (!submission) { return undefined; } const existing = await client.query( 'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2', [submission.principal, submission.key] ); const saved = existing.rows[0]; if (saved && saved.submission_hash !== submissionHash) { throw new RunSubmissionConflictError(); } return saved; }; const previous = await replay(); if (previous) { return previous; } const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [ request.backtestId, ]); if (!parent.rows.length) { throw new Error('Backtest not found'); } const concurrent = await replay(); if (concurrent) { return concurrent; } if (at(parent.rows, 0).archived_at) { throw new BacktestRetentionError('backtest_archived'); } const definition = mapBacktest(at(parent.rows, 0)); const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog'; if (!catalog) { throw new CatalogExecutionUnavailableError( 'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.' ); } if (multiplier !== null) { throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed'); } const snapshot = await admitCanonicalRequest( client, this.container, definition, definition.id, runId ).catch((error: unknown) => { throw new CatalogExecutionUnavailableError( error instanceof Error ? error.message : 'Canonical execution unavailable' ); }); const result = await client.query( `INSERT INTO runs (id, backtest_id, run_number, speed_multiplier, status, request_snapshot, dataset_hash, submission_principal, submission_key, submission_hash) SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $8, $5, $6, $7 FROM runs WHERE backtest_id = $2 ${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''} RETURNING *`, [ runId, request.backtestId, multiplier, JSON.stringify(snapshot), submission?.principal ?? null, submission?.key ?? null, submissionHash, snapshot.datasetHash, ] ); // Different parent locks can race for one principal/key. The unique index waits for // the winner's transaction; this next READ COMMITTED query sees its committed row. if (!result.rows.length) { const winner = await replay(); if (!winner) { throw new Error('Concurrent submission disappeared; retry with the same key'); } return winner; } await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]); return at(result.rows, 0); }); return mapRun(row); } async getRun(id: string): Promise { const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]); if (result.rows.length === 0) { return null; } return mapRun(at(result.rows, 0)); } async listRuns(backtestId: string, agentId?: string): Promise { const result = agentId !== undefined ? await this.container.postgres.query( `SELECT * FROM runs WHERE backtest_id = $1 AND research_agent_id = $2 ORDER BY run_number DESC`, [backtestId, agentId] ) : await this.container.postgres.query( `SELECT * FROM runs WHERE backtest_id = $1 ORDER BY run_number DESC`, [backtestId] ); return result.rows.map(row => mapRun(row)); } async updateRunProgress( id: string, updates: { progress?: number; currentDate?: Date; attemptId: string } ): Promise { const result = await this.container.postgres.transaction(async client => { await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]); return client.query( `UPDATE runs SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW() WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`, [id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId] ); }); const row = result.rows[0]; if (row) { this.getWebSocketHandler()?.broadcastRunUpdate(id, { type: 'run_update', runId: id, data: { status: row.status, ...updates, timestamp: new Date().toISOString() }, }); } } async pauseRun(id: string): Promise { await this.sendControl(id, 'pause'); } async resumeRun(id: string): Promise { await this.sendControl(id, 'resume'); } async cancelRun(id: string): Promise { const result = await this.container.postgres.query( `UPDATE runs SET cancel_requested = TRUE, status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END, completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW() WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`, [id] ); const row = result.rows[0]; if (!row) { throw new Error('No cancellable run found'); } this.getWebSocketHandler()?.broadcastRunUpdate(id, { type: 'run_update', data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() }, }); } async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { await this.sendControl(id, 'speed', { speed: speedMultiplier }); } private async sendControl(runId: string, command: string, payload: object = {}): Promise { const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...payload, runId }), }); if (!response.ok) { throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`); } // The runner, not the API client, commits acknowledged state changes. } async canonicalCapability(id: string): Promise { try { const execution = await this.container.postgres.transaction(async client => { const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id])) .rows[0]; if (!row || row.archived_at !== null) { throw new Error('Backtest is missing or archived'); } const request = await admitCanonicalRequest(client, this.container, mapBacktest(row), id); return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined; }); return { available: true, reason: null, ...(execution ? { execution } : {}) }; } catch (error) { return { available: false, reason: error instanceof Error ? error.message : 'Canonical execution unavailable', }; } } private getWebSocketHandler(): WebSocketHandler | null { // Try to get from global if not already set this.wsHandler ??= getWebSocketHandler(); return this.wsHandler; } }