docs: explain strategy replay and durable execution code
This commit is contained in:
parent
8587c71cf3
commit
dd7ac53c51
19 changed files with 494 additions and 41 deletions
|
|
@ -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(),
|
||||
|
|
|
|||
|
|
@ -1,3 +1,8 @@
|
|||
/**
|
||||
* PostgreSQL persistence boundary for research run ownership, retained inputs and results.
|
||||
* It validates identities and commits worker output; it does not calculate trades, cash
|
||||
* or equity. These transactions concern research tables, not paper-account execution.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
|
|
@ -27,7 +32,12 @@ import {
|
|||
type RunClaim,
|
||||
} from './run-repository';
|
||||
|
||||
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
|
||||
/**
|
||||
* An attempt UUID is a fencing token: a delayed worker cannot write after replacement.
|
||||
* Ownership also requires an active status and an unexpired lease measured by PostgreSQL
|
||||
* time. Canonical methods consume pre-admitted requests; legacy methods remain for older
|
||||
* contracts and fixtures and do not enable legacy execution through BacktestRunner.
|
||||
*/
|
||||
export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
||||
constructor(
|
||||
private readonly postgres: Pick<PostgresClient, 'transaction'>,
|
||||
|
|
@ -38,6 +48,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
}
|
||||
|
||||
/** Read admission state without claiming it; startCanonical must still arbitrate ownership. */
|
||||
async load(runId: string) {
|
||||
return this.postgres.transaction(async client => {
|
||||
const result = await client.query('SELECT status, request_snapshot FROM runs WHERE id = $1', [
|
||||
|
|
@ -48,6 +59,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy claim/create path. Current queued research uses startCanonical instead. */
|
||||
async start(config: BacktestConfig): Promise<RunClaim> {
|
||||
rejectCatalogVersionReferences(config);
|
||||
const attemptId = randomUUID();
|
||||
|
|
@ -133,6 +145,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim an existing pending run and verify the caller supplied its exact frozen inputs.
|
||||
* The status/attempt update and snapshot checks share a transaction, so mismatches roll
|
||||
* back the claim. Recovery must first return an expired run to pending; this method
|
||||
* neither steals active leases nor creates a new run or dataset.
|
||||
*/
|
||||
async startCanonical(input: CanonicalRunRequest): Promise<CanonicalRunClaim> {
|
||||
const request = canonicalRunRequestSchema.parse(input);
|
||||
const attemptId = randomUUID();
|
||||
|
|
@ -171,6 +189,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load only the v2 bytes bound by admission. Check the request, run pointer and content
|
||||
* hash together; no missing-data provider fallback is allowed. The final lease check
|
||||
* prevents slow validation from authorizing execution after ownership has expired.
|
||||
*/
|
||||
async loadCanonicalDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
|
|
@ -219,6 +242,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Reject malformed/retired queued input only while unclaimed; never overwrite an owner. */
|
||||
async rejectPending(runId: string, error: string) {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
|
|
@ -229,6 +253,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy v1 lookup/pinning; canonical admission already binds a retained v2 dataset. */
|
||||
async loadDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
|
|
@ -268,6 +293,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy v1 retention: save validated bytes and pin the run atomically. Reusing an
|
||||
* existing hash still validates its stored payload; insertion success alone is no proof
|
||||
* that old content is intact. Any late cancellation/lease failure rolls back the pin.
|
||||
*/
|
||||
async freezeDataset(
|
||||
runId: string,
|
||||
attemptId: string,
|
||||
|
|
@ -329,8 +359,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
return dataset;
|
||||
}
|
||||
|
||||
/** 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(). */
|
||||
/**
|
||||
* Lock first, then evaluate leases against actual DB time: an UPDATE predicate can be
|
||||
* evaluated before waiting on a row lock, even with clock_timestamp(). This helper only
|
||||
* acquires the lock; each callback must still check attempt, lease and allowed status.
|
||||
*/
|
||||
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]);
|
||||
|
|
@ -338,6 +371,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renew a still-valid owner and return its cancellation flag in the same statement.
|
||||
* A cancellation request does not immediately revoke ownership: the worker needs its
|
||||
* lease to stop execution and commit cancellation. An expired lease cannot be renewed.
|
||||
*/
|
||||
async heartbeat(runId: string, attemptId: string) {
|
||||
return this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
|
|
@ -353,6 +391,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Legacy result shape; canonical reports are persisted by completeCanonical. */
|
||||
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
|
||||
await this.ownedTransaction(result.runId, async client => {
|
||||
const updated = await this.markComplete(client, result, attemptId);
|
||||
|
|
@ -380,6 +419,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Final ownership/cancellation gate inside the surrounding result transaction. A pending
|
||||
* cancel wins over completion; loss of ownership is a different error. If later result
|
||||
* validation or insertion fails, the caller's transaction rolls this status update back.
|
||||
*/
|
||||
private async markComplete(
|
||||
client: PoolClient,
|
||||
result: Pick<BacktestRunResult, 'runId' | 'backtestId' | 'status' | 'completedAt'>,
|
||||
|
|
@ -407,6 +451,11 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
return updated.rows[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the Rust report envelope and its admitted inputs, then atomically commit
|
||||
* terminal status plus the full canonical result. Legacy financial columns stay null
|
||||
* so readers do not mistake a second projection for an independent account record.
|
||||
*/
|
||||
async completeCanonical(result: CanonicalRunResult, attemptId: string): Promise<void> {
|
||||
const request = canonicalRunRequestSchema.parse(result.request);
|
||||
if (
|
||||
|
|
@ -443,6 +492,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Monotonic progress within an attempt; starting a recovered attempt resets it to zero. */
|
||||
async updateProgress(
|
||||
runId: string,
|
||||
progress: number,
|
||||
|
|
@ -489,6 +539,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort terminal write for a still-owned attempt. A recorded cancel takes priority;
|
||||
* a stale owner changes no rows. Unlike cancel(), this does not assert an acknowledgement.
|
||||
*/
|
||||
async fail(runId: string, error: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
await client.query(
|
||||
|
|
@ -501,6 +555,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
/** Confirm stopped execution under the current lease; failure to write is not success. */
|
||||
async cancel(runId: string, attemptId: string) {
|
||||
await this.ownedTransaction(runId, async client => {
|
||||
const result = await client.query(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
/** Additive trusted-host F07 boundary, not an active runner or S01 strategy runtime. */
|
||||
/**
|
||||
* Active TypeScript-to-Rust replay boundary used by strategy-runtime and the
|
||||
* isolated candidate host. This module validates native messages and drives a
|
||||
* pull loop; Rust owns the clock, order matching, risk and financial state.
|
||||
* Controllers receive published observations and decision views, never the handle.
|
||||
*/
|
||||
import { FinancialReplaySession } from '@stock-bot/engine';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
|
|
@ -68,7 +73,12 @@ export function marketDecimal(value: number): string {
|
|||
return parseFinancialDecimal(`${negative ? '-' : ''}${plain}`);
|
||||
}
|
||||
|
||||
/** Verify the actual payload in the worker, not an upstream supplied hash label. */
|
||||
/**
|
||||
* Verify the retained payload, bind execution series and translate domain names
|
||||
* into the native wire format. Prices become checked decimal strings; timestamp
|
||||
* and availability declarations are preserved rather than inferred here.
|
||||
* The worker verifies actual content instead of trusting an upstream hash label.
|
||||
*/
|
||||
export function prepareReplayLoad(datasetInput: unknown, configInput: ReplayConfig) {
|
||||
const dataset = validateDatasetV2(datasetInput),
|
||||
manifest = dataset.manifest;
|
||||
|
|
@ -145,7 +155,13 @@ function freeze<T>(value: T): T {
|
|||
}
|
||||
return value;
|
||||
}
|
||||
/** JSON transport is intentionally explicit and measured. No history/checkpoint API. */
|
||||
/**
|
||||
* Checked JSON facade over the NAPI FinancialReplaySession owned by this process.
|
||||
* Every response is schema/identity checked. The supported StrategyContext does
|
||||
* not expose this handle; trusted in-process code is not a security sandbox.
|
||||
* Byte/timing counters measure boundary overhead, not financial performance.
|
||||
* This research facade exposes no financial checkpoint restore operation.
|
||||
*/
|
||||
export class NativeReplaySession {
|
||||
readonly identity: ReplayIdentity;
|
||||
private readonly native: FinancialReplaySession;
|
||||
|
|
@ -160,6 +176,7 @@ export class NativeReplaySession {
|
|||
this.identity = freeze({ ...load.identity });
|
||||
this.native = new FinancialReplaySession(JSON.stringify(load));
|
||||
}
|
||||
/** Advance at most this many replay events, stopping earlier for a decision or completion. */
|
||||
advance(eventBudget: number): ReplayStep {
|
||||
const raw = this.native.advance(JSON.stringify({ identity: this.identity, eventBudget }));
|
||||
this.transport.advanceResponseBytes += Buffer.byteLength(raw);
|
||||
|
|
@ -174,6 +191,7 @@ export class NativeReplaySession {
|
|||
}
|
||||
return freeze(result);
|
||||
}
|
||||
/** Submit the complete due-owner batch; admission feedback is not later fill feedback. */
|
||||
submit(barrierId: string, decisions: FinancialStrategyDecision[]) {
|
||||
const request = JSON.stringify({
|
||||
identity: this.identity,
|
||||
|
|
@ -357,6 +375,7 @@ export function runReplaySession(
|
|||
}
|
||||
}
|
||||
|
||||
/** The isolated candidate controller may await IPC; it shares the synchronous driver's loop. */
|
||||
export async function runReplaySessionAsync(
|
||||
session: NativeReplaySession,
|
||||
controller: AsyncReplayController,
|
||||
|
|
@ -387,6 +406,12 @@ type ReplayAction =
|
|||
}
|
||||
| { kind: 'committed'; outcome: ReplaySubmissionOutcome };
|
||||
|
||||
/**
|
||||
* One ordered loop serves both trusted synchronous and isolated async decisions.
|
||||
* Observations accumulate across progress steps until a barrier; stage produces
|
||||
* all due intents, Rust admits them together, then committed confirms host state.
|
||||
* Generator cleanup disposes the native session even if a callback/IPC fails.
|
||||
*/
|
||||
function* replaySteps(
|
||||
session: NativeReplaySession,
|
||||
options: ReplayOptions
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ type StrategyRun<Result extends ReplayOutput> = {
|
|||
diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>;
|
||||
};
|
||||
|
||||
/** Replay failure plus the last confirmed callback diagnostics for investigation. */
|
||||
export class StrategyReplayError extends Error {
|
||||
constructor(
|
||||
cause: unknown,
|
||||
|
|
@ -43,6 +44,16 @@ export class StrategyReplayError extends Error {
|
|||
}
|
||||
|
||||
/* eslint-disable no-redeclare -- Keep selected native result formats precise. */
|
||||
/**
|
||||
* Run trusted synchronous programs against a newly constructed Rust session.
|
||||
* The shared replay driver advances to a barrier, asks StrategyController for
|
||||
* decisions, submits them together, then confirms callback state on admission.
|
||||
*
|
||||
* Prepared market input is copied into Rust before callbacks can run. Result
|
||||
* format selects trace, projection or report output, not different economics.
|
||||
* Replay failures carry confirmed diagnostics; retries start from original inputs
|
||||
* and initial program state, not from those diagnostic snapshots.
|
||||
*/
|
||||
export function runStrategyReplay(
|
||||
load: ReturnType<typeof prepareReplayLoad>,
|
||||
programs: readonly StrategyProgram[],
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue