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

@ -7,8 +7,9 @@ import { BacktestCancelledError, type BacktestExecutionEngine } from './executio
import { normalizeBacktestResult } from './result';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type RunIdentity,
type RunClaim,
} from './run-repository';
export function parseBacktestRequest(input: unknown): BacktestConfig {
@ -24,7 +25,8 @@ export function parseBacktestRequest(input: unknown): BacktestConfig {
/** One application workflow for HTTP, jobs, and both execution backends. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunIdentity | undefined;
private active: RunClaim | undefined;
private leaseFailure: BacktestLeaseLostError | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
@ -37,6 +39,8 @@ export class BacktestRunner extends EventEmitter {
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
@ -53,14 +57,78 @@ export class BacktestRunner extends EventEmitter {
}
this.busy = true;
this.cancelled = false;
this.leaseFailure = undefined;
this.phase = 'preparing';
this.execution = this.execute(config);
return this.execution;
}
/** Queue redelivery is an acknowledgement for terminal runs, never a second execution. */
async runQueued(runId: string) {
const run = await this.dependencies.repository.load(runId);
if (!run) {
return { runId, status: 'missing' };
}
if (['completed', 'cancelled', 'failed'].includes(run.status)) {
return { runId, status: run.status };
}
let snapshot: BacktestConfig;
try {
snapshot = parseBacktestRequest(run.config);
} catch (error) {
await this.dependencies.repository.rejectPending(
runId,
'Invalid persisted execution configuration'
);
throw error;
}
const result = await this.runBacktest({ ...snapshot, runId });
return { runId, status: result.status };
}
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
const heartbeat = async () => {
const active = this.active;
if (!active) {
return;
}
let deadline: ReturnType<typeof setTimeout> | undefined;
try {
const state = await Promise.race([
this.dependencies.repository.heartbeat(active.runId, active.attemptId),
new Promise<never>((_resolve, reject) => {
deadline = setTimeout(
() => reject(new Error('Execution heartbeat timed out')),
this.dependencies.heartbeatTimeoutMs ?? 5_000
);
}),
]);
if (!state.cancelRequested) {
return;
}
this.cancelled = true;
} catch (error) {
this.leaseFailure = new BacktestLeaseLostError(
'Could not renew execution lease; abandoning attempt',
{ cause: error }
);
} finally {
if (deadline) {
clearTimeout(deadline);
}
}
if (this.phase === 'executing') {
try {
await this.dependencies.engine.stopBacktest();
} catch (error) {
this.dependencies.logger.error('Could not stop abandoned/cancelled execution', { error });
}
}
};
const onProgress = (data: unknown) => {
const active = this.active;
if (
@ -81,7 +149,14 @@ export class BacktestRunner extends EventEmitter {
? data.currentDate
: undefined;
this.progressWrites = this.progressWrites
.then(() => this.dependencies.repository.updateProgress(active.runId, progress, date))
.then(() =>
this.dependencies.repository.updateProgress(
active.runId,
progress,
date,
active.attemptId
)
)
.catch(error => {
this.dependencies.logger.error('Could not persist backtest progress', { error });
});
@ -90,13 +165,38 @@ export class BacktestRunner extends EventEmitter {
this.dependencies.engine.on('progress', onProgress);
try {
this.active = await this.dependencies.repository.start(config);
const executionConfig = { ...config, ...this.active };
const executionConfig = parseBacktestRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
});
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
heartbeatWork = undefined;
});
}
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
await this.dependencies.prepare?.(executionConfig);
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
this.phase = 'executing';
const raw = await this.dependencies.engine.runBacktest(executionConfig);
if (this.leaseFailure) {
throw this.leaseFailure;
}
this.phase = 'persisting';
let result: BacktestRunResult;
try {
@ -112,21 +212,25 @@ export class BacktestRunner extends EventEmitter {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
await this.progressWrites;
await this.dependencies.repository.complete(result);
if (this.leaseFailure) {
throw this.leaseFailure;
}
await this.dependencies.repository.complete(result, this.active.attemptId);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = error;
if (this.active) {
let failure = this.leaseFailure ?? error;
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (error instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId);
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error)
error instanceof Error ? error.message : String(error),
this.active.attemptId
);
}
} catch (persistenceError) {
@ -138,12 +242,20 @@ export class BacktestRunner extends EventEmitter {
}
}
if (failure instanceof BacktestCancelledError) {
this.publish('cancelled', { ...this.active, status: 'cancelled' });
this.publish('cancelled', {
runId: this.active?.runId,
backtestId: this.active?.backtestId,
status: 'cancelled',
});
} else if (this.listenerCount('error')) {
this.publish('error', failure);
}
throw failure;
} finally {
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}
await heartbeatWork;
this.dependencies.engine.off('progress', onProgress);
this.active = undefined;
this.busy = false;
@ -211,12 +323,20 @@ export class BacktestRunner extends EventEmitter {
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'paused' });
await this.dependencies.repository.updateControl(
active.runId,
{ status: 'paused' },
active.attemptId
);
}
async resumeBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.resumeBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'running' });
await this.dependencies.repository.updateControl(
active.runId,
{ status: 'running' },
active.attemptId
);
}
async setSpeedMultiplier(speed: number | null, runId?: string) {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
@ -224,7 +344,11 @@ export class BacktestRunner extends EventEmitter {
}
const active = this.requireActive(runId);
this.dependencies.engine.setSpeedMultiplier(speed);
await this.dependencies.repository.updateControl(active.runId, { speedMultiplier: speed });
await this.dependencies.repository.updateControl(
active.runId,
{ speedMultiplier: speed },
active.attemptId
);
}
getStatus() {
return {

View file

@ -1,33 +1,64 @@
import { randomUUID } from 'node:crypto';
import type { TransactionCallback } from '@stock-bot/postgres';
import type { PostgresClient } from '@stock-bot/services';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import { BacktestConfigSchema, type BacktestConfig } from '../types';
import { BacktestCancelledError } from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type RunIdentity,
type RunClaim,
} from './run-repository';
/** Uses the existing backtests/runs schema; never commits completion without the result. */
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
export class PostgresBacktestRunRepository implements BacktestRunRepository {
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
constructor(
private readonly postgres: Pick<PostgresClient, 'transaction'>,
private readonly leaseMs = 30_000
) {
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
throw new Error('Invalid execution lease duration');
}
}
async start(config: BacktestConfig): Promise<RunIdentity> {
async load(runId: string) {
return this.postgres.transaction(async client => {
const result = await client.query('SELECT status, request_snapshot FROM runs WHERE id = $1', [
runId,
]);
const row = result.rows[0];
return row ? { status: String(row.status), config: row.request_snapshot as unknown } : null;
});
}
async start(config: BacktestConfig): Promise<RunClaim> {
const attemptId = randomUUID();
return this.postgres.transaction(async client => {
if (config.runId) {
const claimed = await client.query<{ id: string; backtest_id: string }>(
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [config.runId]);
const claimed = await client.query(
`UPDATE runs SET status = 'running', progress = 0, error = NULL,
started_at = NOW(), completed_at = NULL, updated_at = NOW()
WHERE id = $1 AND status IN ('pending', 'failed')
started_at = NOW(), completed_at = NULL, paused_at = NULL, updated_at = NOW(),
attempt_id = $3, attempt_number = attempt_number + 1,
lease_expires_at = clock_timestamp() + $4::interval
WHERE id = $1 AND status = 'pending' AND NOT cancel_requested
AND request_snapshot IS NOT NULL
AND ($2::uuid IS NULL OR backtest_id = $2::uuid)
RETURNING id, backtest_id`,
[config.runId, config.backtestId ?? null]
RETURNING id, backtest_id, request_snapshot`,
[config.runId, config.backtestId ?? null, attemptId, `${this.leaseMs} milliseconds`]
);
const run = claimed.rows[0];
if (!run) {
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
}
return { runId: run.id, backtestId: run.backtest_id };
const snapshot = BacktestConfigSchema.parse(run.request_snapshot);
return {
runId: String(run.id),
backtestId: String(run.backtest_id),
attemptId,
config: snapshot,
};
}
const backtestId = config.backtestId ?? randomUUID();
@ -53,7 +84,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
]
);
}
// Serialize run numbering on the parent rather than racing MAX(run_number).
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
backtestId,
]);
@ -61,9 +91,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
throw new Error('Backtest definition not found');
}
const runId = randomUUID();
const snapshot = { ...config, runId, backtestId };
await client.query(
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier,
request_snapshot, attempt_id, attempt_number, lease_expires_at)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3,
$4::jsonb, $5::uuid, 1, clock_timestamp() + $6::interval
FROM runs WHERE backtest_id = $2`,
[
runId,
@ -73,22 +106,70 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
: config.speed === 'realtime'
? 1
: Number.parseFloat(config.speed),
JSON.stringify(snapshot),
attemptId,
`${this.leaseMs} milliseconds`,
]
);
return { runId, backtestId };
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
return { runId, backtestId, attemptId, config: snapshot };
});
}
async complete(result: BacktestRunResult): Promise<void> {
async rejectPending(runId: string, error: string) {
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET status = 'failed', error = $2,
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
[runId, error]
);
});
}
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
return this.postgres.transaction(async client => {
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]);
return work(client);
});
}
async heartbeat(runId: string, attemptId: string) {
return this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET lease_expires_at = clock_timestamp() + $3::interval, updated_at = NOW()
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') RETURNING cancel_requested`,
[runId, attemptId, `${this.leaseMs} milliseconds`]
);
if (!result.rows[0]) {
throw new BacktestLeaseLostError('Execution lease lost');
}
return { cancelRequested: result.rows[0].cancel_requested === true };
});
}
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
await this.ownedTransaction(result.runId, async client => {
const updated = await client.query(
`UPDATE runs SET status = $2, progress = CASE WHEN $2 = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused') RETURNING id`,
[result.runId, result.status, result.completedAt, result.backtestId]
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`,
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
);
if (!updated.rows.length) {
throw new BacktestConflictError('Run no longer belongs to this execution');
const cancellation = await client.query(
`SELECT id FROM runs
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND cancel_requested`,
[result.runId, attemptId]
);
if (cancellation.rows.length) {
throw new BacktestCancelledError();
}
throw new BacktestLeaseLostError('Execution lease lost');
}
await client.query(
`INSERT INTO backtest_results
@ -111,59 +192,73 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
async updateProgress(runId: string, progress: number, currentDate?: string): Promise<void> {
await this.postgres.transaction(async client => {
await client.query(
async updateProgress(
runId: string,
progress: number,
currentDate: string | undefined,
attemptId: string
) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET progress = GREATEST(progress, $2),
current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused')`,
[runId, progress, currentDate ?? null]
WHERE id = $1 AND attempt_id = $4 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') RETURNING id`,
[runId, progress, currentDate ?? null, attemptId]
);
if (!result.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost');
}
});
}
async updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
): Promise<void> {
await this.postgres.transaction(async client => {
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
attemptId: string
) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET status = COALESCE($2::run_status, status),
paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END,
speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
WHERE id = $1 AND attempt_id = $5 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
[
runId,
update.status ?? null,
update.speedMultiplier !== undefined,
update.speedMultiplier ?? null,
attemptId,
]
);
if (!result.rows.length) {
throw new BacktestConflictError('No matching active run');
throw new BacktestLeaseLostError('No matching owned active run');
}
});
}
async fail(runId: string, error: string): Promise<void> {
await this.postgres.transaction(async client => {
async fail(runId: string, error: string, attemptId: string) {
await this.ownedTransaction(runId, async client => {
await client.query(
`UPDATE runs SET status = 'failed', error = $2, completed_at = NOW(), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused')`,
[runId, error]
`UPDATE runs SET status = CASE WHEN cancel_requested THEN 'cancelled'::run_status ELSE 'failed'::run_status END,
error = CASE WHEN cancel_requested THEN NULL ELSE $2 END,
completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
WHERE id = $1 AND attempt_id = $3 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused')`,
[runId, error, attemptId]
);
});
}
async cancel(runId: string): Promise<void> {
await this.postgres.transaction(async client => {
async cancel(runId: string, attemptId: string) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
[runId]
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') RETURNING id`,
[runId, attemptId]
);
if (!result.rows.length) {
throw new BacktestConflictError('No matching active run to cancel');
throw new BacktestLeaseLostError('No matching owned active run to cancel');
}
});
}

View file

@ -5,39 +5,65 @@ export interface RunIdentity {
runId: string;
backtestId: string;
}
export interface RunClaim extends RunIdentity {
attemptId: string;
config: BacktestConfig;
}
/** The runner owns this lifecycle. Results and terminal status must commit atomically. */
/** Every execution write must prove ownership of an unexpired attempt. */
export interface BacktestRunRepository {
start(config: BacktestConfig): Promise<RunIdentity>;
complete(result: BacktestRunResult): Promise<void>;
updateProgress(runId: string, progress: number, currentDate?: string): Promise<void>;
fail(runId: string, error: string): Promise<void>;
cancel(runId: string): Promise<void>;
start(config: BacktestConfig): Promise<RunClaim>;
load(runId: string): Promise<{ status: string; config: unknown } | null>;
rejectPending(runId: string, error: string): Promise<void>;
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
updateProgress(
runId: string,
progress: number,
currentDate: string | undefined,
attemptId: string
): Promise<void>;
fail(runId: string, error: string, attemptId: string): Promise<void>;
cancel(runId: string, attemptId: string): Promise<void>;
updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
attemptId: string
): Promise<void>;
}
export class BacktestConflictError extends Error {}
export class BacktestLeaseLostError extends BacktestConflictError {}
/** No database is never a license to execute an unowned job. */
export class UnavailableBacktestRunRepository implements BacktestRunRepository {
async start(_config: BacktestConfig): Promise<RunIdentity> {
private unavailable(): never {
throw new Error('Backtest execution requires a PostgreSQL run repository');
}
async complete(_result: BacktestRunResult): Promise<void> {
throw new Error('Backtest run repository is unavailable');
async start(_config: BacktestConfig): Promise<RunClaim> {
return this.unavailable();
}
async load(_runId: string): Promise<null> {
return this.unavailable();
}
async rejectPending(_runId: string, _error: string): Promise<void> {
this.unavailable();
}
async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> {
return this.unavailable();
}
async complete(_result: BacktestRunResult, _attemptId: string): Promise<void> {
this.unavailable();
}
async updateProgress(): Promise<void> {
throw new Error('Backtest run repository is unavailable');
this.unavailable();
}
async updateControl(): Promise<void> {
throw new Error('Backtest run repository is unavailable');
this.unavailable();
}
async fail(_runId: string, _error: string): Promise<void> {
throw new Error('Backtest run repository is unavailable');
async fail(_runId: string, _error: string, _attemptId: string): Promise<void> {
this.unavailable();
}
async cancel(_runId: string): Promise<void> {
throw new Error('Backtest run repository is unavailable');
async cancel(_runId: string, _attemptId: string): Promise<void> {
this.unavailable();
}
}

View file

@ -136,7 +136,7 @@ export async function registerOrchestratorServices(
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator');
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
}
// For backward compatibility, export a container getter

View file

@ -17,6 +17,11 @@ export class BacktestHandler extends BaseHandler<OrchestratorServices> {
if (typeof payload !== 'object' || payload === null) {
throw new Error('Invalid backtest job');
}
// Durable notifications carry identity only; execution always uses the SQL snapshot.
if ('runId' in payload && !('strategy' in payload)) {
const { runId } = z.object({ runId: z.string().uuid() }).parse(payload);
return this.runner.runQueued(runId);
}
// Old jobs omitted these fields. Normalize the envelope, never the execution result.
const config = { mode: 'backtest', dataFrequency: '1d', ...payload };
const results = await this.runner.runBacktest(config);

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);
}

View file

@ -215,14 +215,16 @@ export function useBacktestV2(): UseBacktestV2Return {
}, [currentRun]);
const cancelRun = useCallback(async () => {
if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) {
if (!currentRun || !['pending', 'running', 'paused'].includes(currentRun.status)) {
return;
}
try {
await backtestApiV2.cancelRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'cancelled' } : null));
stopMonitoringRun();
// Acceptance is not completion: keep monitoring the owner's persisted acknowledgement.
const updated = await backtestApiV2.getRun(currentRun.id);
setCurrentRun(updated);
setRuns(prev => prev.map(run => (run.id === updated.id ? updated : run)));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to cancel run');
}

View file

@ -26,6 +26,8 @@ export interface Run {
completedAt?: string;
pausedAt?: string;
progress: number;
cancelRequested?: boolean;
attemptNumber?: number;
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;