feat(backtests): separate saving from retry-safe run submission

This commit is contained in:
Boki 2026-10-22 17:01:46 -04:00
parent 5eb0985057
commit 9b9403e36b
18 changed files with 1200 additions and 226 deletions

View file

@ -1,4 +1,4 @@
import { randomUUID as uuidv4 } from 'node:crypto';
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import { authenticatedServiceFetch } from '@stock-bot/di';
import { at } from '@stock-bot/invariants';
@ -6,6 +6,7 @@ import { getLogger } from '@stock-bot/logger';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
import type { BacktestRunResult } from '@stock-bot/types';
import { HistoricalDataRequestError } from '@stock-bot/types';
import { getWebSocketHandler } from '../websocket/run-updates';
import type { WebSocketHandler } from '../websocket/run-updates';
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
@ -63,6 +64,18 @@ export interface RunRequest {
speedMultiplier?: number | null;
}
export interface RunSubmission {
principal: 'operator' | 'service';
key: string;
}
export class RunSubmissionConflictError extends Error {
constructor() {
super('This submission key was already used for a different run request');
this.name = 'RunSubmissionConflictError';
}
}
export class BacktestServiceV2 {
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
private wsHandler: WebSocketHandler | null = null;
@ -208,17 +221,55 @@ export class BacktestServiceV2 {
}
// Run operations
async createRun(request: RunRequest): Promise<Run> {
async createRun(request: RunRequest, submission?: RunSubmission): Promise<Run> {
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;
}
const definition = this.mapBacktest(at(parent.rows, 0));
const multiplier = request.speedMultiplier ?? null;
const snapshot = backtestRequestFromDefinition(definition, {
runId,
backtestId: definition.id,
@ -226,11 +277,31 @@ export class BacktestServiceV2 {
});
const result = await client.query(
`INSERT INTO runs
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb
FROM runs WHERE backtest_id = $2 RETURNING *`,
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot,
submission_principal, submission_key, submission_hash)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $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,
]
);
// 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);
});