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 {