fix(api): reject retired backtest creation before writes (CL23)

This commit is contained in:
Boki 2026-10-28 13:48:41 -04:00
parent 3fc0a272d8
commit cd1aa61481
10 changed files with 297 additions and 48 deletions

View file

@ -1,7 +1,6 @@
import { randomUUID as uuidv4 } from 'node:crypto';
import type { PoolClient } from 'pg';
import { at } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import {
backtestRequestFromDefinition,
backtestSettingsFromDefinition,
@ -23,19 +22,12 @@ import {
type Backtest,
type BacktestContainer,
type BacktestRequest,
type Run,
type RunRequest,
} from './contracts';
import { mapBacktest } from './mapping';
const logger = getLogger('backtest-v2-service');
/** Focused templates operations; transaction order is preserved. */
export class BacktestTemplates {
constructor(
private readonly container: BacktestContainer,
private readonly startRun: (request: RunRequest) => Promise<Run>
) {}
constructor(private readonly container: BacktestContainer) {}
async createBacktest(
request: BacktestRequest,
options: { autoStart?: boolean } = {}
@ -46,6 +38,9 @@ export class BacktestTemplates {
}
if (!catalog) {
rejectCatalogVersionReferences(request);
if (options.autoStart !== false) {
throw new HistoricalDataRequestError('Backtest drafts require explicit autoStart:false');
}
}
const backtestId = uuidv4();
const result = await this.container.postgres.transaction(async client => {
@ -76,24 +71,7 @@ export class BacktestTemplates {
);
});
const backtest = mapBacktest(at(result.rows, 0));
// Automatically create and start a run for the new backtest
if (options.autoStart !== false) {
try {
await this.startRun({
backtestId: backtest.id,
speedMultiplier: null, // Max speed (instant)
});
} catch (error) {
logger.error('Failed to auto-create run for new backtest', {
backtestId: backtest.id,
error,
});
// Don't fail the backtest creation if run creation fails
}
}
return backtest;
return mapBacktest(at(result.rows, 0));
}
async getBacktest(id: string): Promise<Backtest | null> {