docs: explain strategy replay and durable execution code

This commit is contained in:
Boki 2026-10-25 11:31:23 -04:00
parent 8587c71cf3
commit dd7ac53c51
19 changed files with 494 additions and 41 deletions

View file

@ -1,3 +1,9 @@
/**
* Supervises one durable research attempt: SQL claim -> engine replay -> SQL result.
* The engine owns financial execution; this class owns attempt lifetime and reporting.
* ResearchBacktestPool supplies a separate runner/engine per concurrent trial, so these
* mutable fields never represent a shared paper account or several simultaneous runs.
*/
import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
@ -32,7 +38,12 @@ function parseDurableRequest(input: unknown): DurableRequest {
: parseBacktestRequest(input);
}
/** One canonical workflow for durably admitted research jobs. */
/**
* Executes only requests already admitted to the durable run store. A run ID identifies
* the experiment trial; its attempt ID identifies the worker currently allowed to write.
* A recovered attempt replays the original inputs from the beginning. Creating a new
* reproduction run is an API operation, outside this supervisor.
*/
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: CanonicalRunClaim | undefined;
@ -62,6 +73,7 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
/** Reserve this in-process slot before execute() reaches its first database await. */
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
@ -77,7 +89,11 @@ export class BacktestRunner extends EventEmitter {
return this.execution;
}
/** Queue redelivery is an acknowledgement for terminal runs, never a second execution. */
/**
* Resolve queue identity into the saved request; a message never supplies executable
* configuration. Terminal redelivery only acknowledges status. The repository claim,
* not this preliminary read, arbitrates competing workers for a pending run.
*/
async runQueued(runId: string) {
const run = await this.dependencies.repository.load(runId);
if (!run) {
@ -108,6 +124,11 @@ export class BacktestRunner extends EventEmitter {
return { runId, status: result.status };
}
/**
* Keep a lease while preparing/executing/persisting, and finish only under that lease.
* Any uncertainty about renewal stops execution without writing a terminal state;
* the dispatcher later recovers expired attempts under its retry/deadline policy.
*/
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
@ -116,6 +137,7 @@ export class BacktestRunner extends EventEmitter {
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
// This wall-clock budget limits research work; it is not the historical replay clock.
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
@ -182,6 +204,8 @@ export class BacktestRunner extends EventEmitter {
Number.isFinite(Date.parse(data.currentDate))
? data.currentDate
: undefined;
// Serialize event-driven writes and capture this attempt's identity. Completion
// drains the chain so a delayed progress write cannot follow the terminal commit.
this.progressWrites = this.progressWrites
.then(() =>
this.dependencies.repository.updateProgress(
@ -228,6 +252,7 @@ export class BacktestRunner extends EventEmitter {
);
executionDeadline.unref();
}
// Execute the repository's claimed snapshot, never a newly edited template.
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
@ -235,6 +260,8 @@ export class BacktestRunner extends EventEmitter {
) {
throw new Error('Canonical claim identity mismatch');
}
// Do not pile up periodic renewals when SQL is slow. Keep the pending renewal
// available to finally so it cannot leak into this runner's next attempt.
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
@ -261,6 +288,8 @@ export class BacktestRunner extends EventEmitter {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
// Resolve retained data through the owning attempt. The adapter supplies its
// abort signal; neither this callback nor the worker fetches fresh provider bars.
const report = await engine.runCanonical(
executionConfig,
signal =>
@ -307,6 +336,8 @@ export class BacktestRunner extends EventEmitter {
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
// After lease loss, another worker may own the run. Even a failure/cancellation
// write would be an unauthorized state change, so leave recovery to the store.
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (failure instanceof BacktestCancelledError) {
@ -351,6 +382,7 @@ export class BacktestRunner extends EventEmitter {
}
}
/** Observer failures are diagnostics; they must not alter the execution outcome. */
private publish(event: string, value: unknown) {
try {
this.emit(event, value);
@ -365,6 +397,11 @@ export class BacktestRunner extends EventEmitter {
}
return this.active;
}
/**
* Stop the locally owned attempt and wait for its cancellation write. Remote API
* cancellation is observed separately through heartbeat's SQL cancel_requested flag.
* Once persistence starts, local stop refuses rather than racing a completed result.
*/
async stopBacktest(runId?: string) {
this.requireActive(runId);
if (this.phase === 'persisting') {
@ -389,6 +426,10 @@ export class BacktestRunner extends EventEmitter {
}
}
/**
* Refuse new work, cancel unfinished execution, and let an in-progress result commit
* finish before closing the engine. Call while the run repository is still available.
*/
async shutdown(): Promise<void> {
this.closing = true;
const execution = this.busy ? this.execution : undefined;
@ -409,6 +450,7 @@ export class BacktestRunner extends EventEmitter {
await this.dependencies.engine.shutdown();
}
}
/** Compatibility control; the engine must accept it before SQL records a pause. */
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
@ -439,6 +481,7 @@ export class BacktestRunner extends EventEmitter {
active.attemptId
);
}
/** Local worker projection; persisted run status remains authoritative after restart. */
getStatus() {
return {
...this.dependencies.engine.getStatus(),