feat(backtests): separate saving from retry-safe run submission
This commit is contained in:
parent
5eb0985057
commit
9b9403e36b
18 changed files with 1200 additions and 226 deletions
|
|
@ -53,7 +53,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '10-durable-backtest-dispatch.sql' ||
|
||||
f === '11-simulation-execution-ledger.sql' ||
|
||||
f === '12-historical-datasets.sql' ||
|
||||
f === '13-strategy-recovery.sql')
|
||||
f === '13-strategy-recovery.sql' ||
|
||||
f === '14-backtest-submission.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { Hono } from 'hono';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import { BacktestServiceV2, RunSubmissionConflictError } from '../services/backtest-v2.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
|
|
@ -40,7 +41,11 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
app.post('/api/v2/backtests', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.createBacktest(body);
|
||||
if (body.autoStart !== undefined && typeof body.autoStart !== 'boolean') {
|
||||
return c.json({ error: 'autoStart must be a boolean' }, 400);
|
||||
}
|
||||
// Omitted autoStart preserves legacy clients. New web clients explicitly save only.
|
||||
const backtest = await backtestService.createBacktest(body, { autoStart: body.autoStart });
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
|
|
@ -91,15 +96,29 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
|
||||
app.post('/api/v2/backtests/:backtestId/runs', async c => {
|
||||
try {
|
||||
const key = c.req.header('Idempotency-Key');
|
||||
const principal = getVerifiedHttpPrincipal(c.req.raw);
|
||||
if (key !== undefined && !principal) {
|
||||
return c.json({ error: 'Verified submission principal required' }, 401);
|
||||
}
|
||||
if (key !== undefined && !/^[\x21-\x7e]{1,200}$/.test(key)) {
|
||||
return c.json(
|
||||
{ error: 'Idempotency-Key must contain 1–200 visible ASCII characters' },
|
||||
400
|
||||
);
|
||||
}
|
||||
const body = await c.req.json();
|
||||
const run = await backtestService.createRun({
|
||||
backtestId: c.req.param('backtestId'),
|
||||
speedMultiplier: body.speedMultiplier,
|
||||
});
|
||||
const run = await backtestService.createRun(
|
||||
{ backtestId: c.req.param('backtestId'), speedMultiplier: body.speedMultiplier },
|
||||
key !== undefined && principal ? { principal, key } : undefined
|
||||
);
|
||||
c.header('Location', `/api/v2/runs/${run.id}`);
|
||||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof RunSubmissionConflictError) {
|
||||
return c.json({ error: error.message }, 409);
|
||||
}
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ export function createRoutes(
|
|||
cors({
|
||||
origin: security.allowedOrigins,
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowHeaders: ['Content-Type', 'Authorization'],
|
||||
allowHeaders: ['Content-Type', 'Authorization', 'Idempotency-Key'],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue