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