more stuff

This commit is contained in:
Boki 2026-10-20 20:11:40 -04:00
parent c3cb36c8d6
commit 7dec0be3b4
26 changed files with 1394 additions and 275 deletions

View file

@ -41,7 +41,11 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
const files = readdirSync(migrationsDir)
.filter(
f => f.endsWith('.sql') && (f.startsWith('001_') || f === '09-backtest-run-contract.sql')
f =>
f.endsWith('.sql') &&
(f.startsWith('001_') ||
f === '09-backtest-run-contract.sql' ||
f === '10-durable-backtest-dispatch.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -2,7 +2,6 @@ import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { BacktestServiceV2 } from '../services/backtest-v2.service';
import { getWebSocketHandler } from '../websocket/run-updates';
const logger = getLogger('backtests-v2-routes');
@ -90,7 +89,8 @@ export function createBacktestV2Routes(container: IServiceContainer) {
backtestId: c.req.param('backtestId'),
speedMultiplier: body.speedMultiplier,
});
return c.json(run, 201);
c.header('Location', `/api/v2/runs/${run.id}`);
return c.json(run, 202);
} catch (error) {
logger.error('Failed to create run', error);
return c.json({ error: 'Failed to create run' }, 500);
@ -146,7 +146,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
app.post('/api/v2/runs/:id/cancel', async c => {
try {
await backtestService.cancelRun(c.req.param('id'));
return c.json({ message: 'Run cancelled' });
return c.json({ message: 'Cancellation requested' }, 202);
} catch (error) {
logger.error('Failed to cancel run', error);
return c.json({ error: 'Failed to cancel run' }, 500);
@ -169,20 +169,18 @@ export function createBacktestV2Routes(container: IServiceContainer) {
try {
const runId = c.req.param('id');
const body = await c.req.json();
const { progress, currentDate } = body;
const { progress, currentDate, attemptId } = body;
if (typeof attemptId !== 'string') {
return c.json({ error: 'Execution attempt ID required' }, 400);
}
// Update run progress in database
await backtestService.updateRunProgress(runId, {
progress,
currentDate,
attemptId,
});
// Broadcast via WebSocket if handler is available
const wsHandler = getWebSocketHandler();
if (wsHandler) {
wsHandler.sendProgressUpdate(runId, progress, currentDate);
}
return c.json({ message: 'Progress updated' });
} catch (error) {
logger.error('Failed to update run progress', error);

View file

@ -4,6 +4,7 @@ import { getLogger } from '@stock-bot/logger';
import { initializeStockConfig } from '@stock-bot/stock-config';
import { createRoutes } from './routes/create-routes';
import { createWebSocketRoute, handleWebSocketConnection } from './routes/websocket.routes';
import { BacktestDispatcher } from './services/BacktestDispatcher';
import { getWebSocketHandler, type RunSocketData } from './websocket/run-updates';
// Initialize configuration with service-specific overrides
@ -65,6 +66,15 @@ export async function startServerWithWebSocket() {
const diContainer = await createContainer(config);
container = diContainer.resolve('serviceContainer');
if (!container.postgres || !container.queueManager) {
throw new Error('Durable backtest dispatch requires PostgreSQL and Redis queues');
}
const dispatcher = new BacktestDispatcher(
container.postgres,
container.queueManager.getQueue('{orchestrator_orchestrator}', { workers: 0 }),
logger
);
// Create HTTP routes
const routes = createRoutes(container, security);
@ -125,15 +135,29 @@ export async function startServerWithWebSocket() {
}
logger.info(`Web API service with WebSocket support started on port ${server.port}`);
dispatcher.start();
logger.info(`WebSocket endpoint available at ws://localhost:${server.port}/ws`);
// Handle shutdown
process.on('SIGINT', async () => {
let shuttingDown = false;
const shutdown = async () => {
if (shuttingDown) {
return;
}
shuttingDown = true;
logger.info('Shutting down server...');
const deadline = setTimeout(() => process.exit(1), 10_000);
deadline.unref();
await dispatcher.shutdown();
getWebSocketHandler()?.cleanup();
await server.stop(true);
await container?.queueManager?.shutdown();
await diContainer.dispose();
clearTimeout(deadline);
process.exit(0);
});
};
process.on('SIGINT', () => void shutdown());
process.on('SIGTERM', () => void shutdown());
} catch (error) {
logger.fatal('Failed to start web API service', { error });
process.exit(1);

View file

@ -0,0 +1,105 @@
import type { Logger, PostgresClient, Queue } from '@stock-bot/services';
/** PostgreSQL is the source of truth; Redis jobs are repeatable delivery notifications. */
export class BacktestDispatcher {
private timer?: ReturnType<typeof setInterval>;
private inFlight?: Promise<void>;
private closing = false;
constructor(
private readonly postgres: Pick<PostgresClient, 'transaction'>,
private readonly queue: Pick<Queue, 'add'>,
private readonly logger: Pick<Logger, 'error'>,
private readonly options = { intervalMs: 5_000, republishMs: 30_000, maxAttempts: 3 }
) {}
start() {
this.timer ??= setInterval(
() =>
void this.tick().catch(error => {
this.logger.error('Backtest dispatch/recovery failed; will retry', { error });
}),
this.options.intervalMs
);
this.timer.unref();
void this.tick().catch(error =>
this.logger.error('Initial backtest dispatch failed; will retry', { error })
);
}
tick(): Promise<void> {
if (this.closing) {
return Promise.resolve();
}
return (this.inFlight ??= this.dispatch().finally(() => {
this.inFlight = undefined;
}));
}
async shutdown() {
this.closing = true;
if (this.timer) {
clearInterval(this.timer);
}
await this.inFlight;
}
private async dispatch() {
// Recovery is independent of Redis availability. Every terminal write fences the old owner.
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET
status = CASE WHEN cancel_requested THEN 'cancelled'::run_status
WHEN attempt_number >= $1 THEN 'failed'::run_status ELSE 'pending'::run_status END,
error = CASE WHEN cancel_requested THEN NULL
WHEN attempt_number >= $1 THEN 'Execution lease expired; retry limit reached' ELSE NULL END,
completed_at = CASE WHEN cancel_requested OR attempt_number >= $1 THEN NOW() ELSE NULL END,
attempt_id = NULL, lease_expires_at = NULL, updated_at = NOW()
WHERE status IN ('running', 'paused') AND lease_expires_at <= clock_timestamp()`,
[this.options.maxAttempts]
);
});
// Reserve a small batch in SQL, then publish outside the transaction. A crash between these
// steps only delays redelivery; it cannot lose the intent or hold DB locks during a Redis outage.
const rows = await this.postgres.transaction(async client => {
const due = await client.query<{ run_id: string }>(`SELECT d.run_id
FROM backtest_dispatch d JOIN runs r ON r.id = d.run_id
WHERE r.status = 'pending' AND NOT r.cancel_requested AND d.next_publish_at <= NOW()
ORDER BY d.next_publish_at LIMIT 20 FOR UPDATE OF d SKIP LOCKED`);
for (const row of due.rows) {
await client.query(
`UPDATE backtest_dispatch
SET next_publish_at = NOW() + $2::interval
WHERE run_id = $1`,
[row.run_id, `${this.options.republishMs} milliseconds`]
);
}
return due.rows;
});
for (const row of rows) {
await this.queue.add(
'run-backtest',
{
handler: 'orchestrator',
operation: 'run-backtest',
payload: { runId: row.run_id },
},
{
jobId: `backtest-${row.run_id}`,
attempts: 3,
backoff: { type: 'fixed', delay: 1_000 },
removeOnComplete: true,
removeOnFail: true,
}
);
await this.postgres.transaction(async client => {
await client.query(
`UPDATE backtest_dispatch
SET last_published_at = NOW(), publish_count = publish_count + 1 WHERE run_id = $1`,
[row.run_id]
);
});
}
}
}

View file

@ -49,6 +49,8 @@ export interface Run {
completedAt?: Date;
pausedAt?: Date;
progress: number;
cancelRequested: boolean;
attemptNumber: number;
currentDate?: Date;
createdAt: Date;
updatedAt: Date;
@ -200,29 +202,69 @@ export class BacktestServiceV2 {
async createRun(request: RunRequest): Promise<Run> {
const runId = uuidv4();
const row = await this.container.postgres.transaction(async client => {
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
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 definition = this.mapBacktest(at(parent.rows, 0));
const multiplier = request.speedMultiplier ?? null;
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
throw new Error('Speed multiplier must be positive or null');
}
const snapshot = {
runId,
backtestId: definition.id,
name: definition.name,
mode: 'backtest',
strategy: definition.strategy,
symbols: definition.symbols,
startDate: definition.startDate.toISOString(),
endDate: definition.endDate.toISOString(),
initialCapital: definition.initialCapital,
config: definition.config,
dataFrequency: definition.config.dataFrequency ?? '1d',
commission: definition.config.commission ?? 0.001,
slippage: definition.config.slippage ?? 0.0001,
speed:
multiplier === null
? 'max'
: multiplier >= 10
? '10x'
: multiplier >= 5
? '5x'
: multiplier >= 2
? '2x'
: 'realtime',
};
if (
!snapshot.strategy ||
!Array.isArray(snapshot.symbols) ||
!snapshot.symbols.length ||
snapshot.symbols.some(symbol => typeof symbol !== 'string' || !symbol.length) ||
!Number.isFinite(snapshot.initialCapital) ||
snapshot.initialCapital <= 0 ||
Date.parse(snapshot.endDate) <= Date.parse(snapshot.startDate) ||
!['1m', '5m', '15m', '1h', '1d'].includes(String(snapshot.dataFrequency)) ||
typeof snapshot.commission !== 'number' ||
!Number.isFinite(snapshot.commission) ||
typeof snapshot.slippage !== 'number' ||
!Number.isFinite(snapshot.slippage)
) {
throw new Error('Invalid backtest execution configuration');
}
const result = await client.query(
`INSERT INTO runs
(id, backtest_id, run_number, speed_multiplier, status)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
(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,
request.speedMultiplier === undefined ? null : request.speedMultiplier,
]
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
);
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
return at(result.rows, 0);
});
const run = this.mapRun(row);
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
void this.startRun(run);
return run;
return this.mapRun(row);
}
async getRun(id: string): Promise<Run | null> {
@ -248,14 +290,17 @@ export class BacktestServiceV2 {
async updateRunProgress(
id: string,
updates: { progress?: number; currentDate?: Date }
updates: { progress?: number; currentDate?: Date; attemptId: string }
): Promise<void> {
const result = await this.container.postgres.query(
`UPDATE runs
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
[id, updates.progress ?? null, updates.currentDate ?? null]
);
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, {
@ -273,7 +318,21 @@ export class BacktestServiceV2 {
await this.sendControl(id, 'resume');
}
async cancelRun(id: string): Promise<void> {
await this.sendControl(id, 'stop');
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<void> {
await this.sendControl(id, 'speed', { speed: speedMultiplier });
@ -394,94 +453,6 @@ export class BacktestServiceV2 {
}
// Private methods
private async startRun(run: Run): Promise<void> {
try {
const backtest = await this.getBacktest(run.backtestId);
if (!backtest) {
throw new Error('Backtest not found');
}
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
runId: run.id,
backtestId: backtest.id,
name: backtest.name,
mode: 'backtest',
startDate: backtest.startDate.toISOString(),
endDate: backtest.endDate.toISOString(),
symbols: backtest.symbols,
strategy: backtest.strategy,
initialCapital: backtest.initialCapital,
config: backtest.config,
dataFrequency: backtest.config.dataFrequency ?? '1d',
commission: backtest.config.commission ?? 0.001,
slippage: backtest.config.slippage ?? 0.0001,
speed:
run.speedMultiplier === null
? 'max'
: run.speedMultiplier >= 10
? '10x'
: run.speedMultiplier >= 5
? '5x'
: run.speedMultiplier >= 2
? '2x'
: 'realtime',
}),
});
if (!response.ok) {
if (response.status === 409) {
const outcome: unknown = await response
.clone()
.json()
.catch(() => null);
if (
outcome &&
typeof outcome === 'object' &&
'status' in outcome &&
outcome.status === 'cancelled' &&
(await this.getRun(run.id))?.status === 'cancelled'
) {
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
type: 'run_update',
data: { status: 'cancelled', timestamp: new Date().toISOString() },
});
return;
}
}
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
}
const result: BacktestRunResult = await response.json();
if (
result.runId !== run.id ||
result.backtestId !== backtest.id ||
!['completed', 'cancelled'].includes(result.status)
) {
throw new Error('Invalid orchestrator run response');
}
// Results and terminal state are already committed by the orchestrator.
this.getWebSocketHandler()?.sendCompletion(run.id, result);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logger.error('Backtest dispatch failed', { runId: run.id, error });
// A broken HTTP connection must not overwrite a claimed or completed execution.
try {
await this.container.postgres.query(
`UPDATE runs SET status = 'failed', error = $2,
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
[run.id, message]
);
} catch (persistenceError) {
logger.error('Could not record backtest dispatch failure', {
runId: run.id,
persistenceError,
});
}
this.getWebSocketHandler()?.sendError(run.id, message);
}
}
private mapBacktest(row: QueryResultRow): Backtest {
return {
id: row.id,
@ -515,6 +486,8 @@ export class BacktestServiceV2 {
completedAt: row.completed_at,
pausedAt: row.paused_at,
progress: parseFloat(row.progress),
cancelRequested: row.cancel_requested === true,
attemptNumber: Number(row.attempt_number ?? 0),
currentDate: row.current_simulation_date,
createdAt: row.created_at,
updatedAt: row.updated_at,

View file

@ -13,15 +13,29 @@ export interface RunUpdateMessage {
data: unknown;
}
export function createWebSocketHandler(_container: IServiceContainer) {
export function createWebSocketHandler(container: IServiceContainer) {
const connections = new Map<string, Set<RunSocket>>();
const completionTimers = new Map<string, ReturnType<typeof setTimeout>>();
const snapshots = new Map<string, string>();
let pollTimer: ReturnType<typeof setInterval> | undefined;
let polling: Promise<void> | undefined;
let stopped = false;
return {
handleConnection(ws: RunSocket, runId: string) {
const clients = connections.get(runId) ?? new Set<RunSocket>();
clients.add(ws);
connections.set(runId, clients);
ws.send(JSON.stringify({ type: 'connected', runId, timestamp: new Date().toISOString() }));
if (container.postgres && !pollTimer) {
pollTimer = setInterval(
() =>
void this.refreshRunUpdates().catch(error => {
logger.warn('Could not refresh persisted run updates', { error });
}),
1000
);
pollTimer.unref();
}
},
handleMessage(ws: RunSocket, payload: string | Buffer) {
try {
@ -44,8 +58,61 @@ export function createWebSocketHandler(_container: IServiceContainer) {
clients?.delete(ws);
if (clients?.size === 0) {
connections.delete(runId);
snapshots.delete(runId);
if (!connections.size && pollTimer) {
clearInterval(pollTimer);
pollTimer = undefined;
}
}
},
/** Notifications are a projection of committed SQL state, independent of the executor process. */
refreshRunUpdates(): Promise<void> {
if (stopped || !container.postgres || !connections.size) {
return Promise.resolve();
}
const postgres = container.postgres;
return (polling ??= (async () => {
const result = await postgres.query(
`SELECT id, status, progress, current_simulation_date,
error, cancel_requested, attempt_number, updated_at FROM runs WHERE id::text = ANY($1::text[])`,
[[...connections.keys()]]
);
if (stopped) {
return;
}
for (const row of result.rows) {
const fingerprint = JSON.stringify(row);
if (snapshots.get(row.id) === fingerprint) {
continue;
}
snapshots.set(row.id, fingerprint);
this.broadcastRunUpdate(row.id, {
data: {
status: row.status,
progress: Number(row.progress),
currentDate: row.current_simulation_date,
cancelRequested: row.cancel_requested,
attemptNumber: row.attempt_number,
timestamp: new Date().toISOString(),
},
});
// Terminal rows do not change after commit, so these events are emitted once per subscription.
if (row.status === 'completed') {
this.sendCompletion(row.id);
} else if (row.status === 'failed') {
this.sendError(row.id, String(row.error ?? 'Backtest failed'));
} else if (row.status === 'running' || row.status === 'paused') {
this.sendProgressUpdate(
row.id,
Number(row.progress),
row.current_simulation_date?.toISOString()
);
}
}
})().finally(() => {
polling = undefined;
}));
},
broadcastRunUpdate(runId: string, update: Partial<RunUpdateMessage>) {
const message: RunUpdateMessage = {
type: 'run_update',
@ -94,6 +161,12 @@ export function createWebSocketHandler(_container: IServiceContainer) {
return connections.get(runId)?.size ?? 0;
},
cleanup() {
stopped = true;
if (pollTimer) {
clearInterval(pollTimer);
}
pollTimer = undefined;
snapshots.clear();
for (const timer of completionTimers.values()) {
clearTimeout(timer);
}