stock-bot/apps/stock/orchestrator/src/backtest/strategy-runtime.ts
Boki 4cd6038063 refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
2026-11-27 00:11:50 -05:00

98 lines
3.8 KiB
TypeScript

/** Trusted synchronous programs on the canonical financial engine. Fresh
* attempts recompute from original inputs; diagnostics are not resume tokens. */
import type {
DeepReadonly,
StrategyDiagnosticSnapshot,
StrategyProgram,
} from '@stock-bot/research/strategy-api';
import {
replayConfigSchema,
replayIdentitySchema,
type ReplayOutput,
type ReplayProjectionResult,
type ReplayReportResult,
type ReplayResult,
} from '@stock-bot/stock-config/canonical-replay';
import { StrategyController } from '../strategies/strategy-controller';
import { freeze } from '../strategies/strategy-decision';
import {
NativeReplaySession,
runReplaySession,
type prepareReplayLoad,
type ReplayMetrics,
type ReplayOptions,
} from './native-replay';
export type { StrategyProgram } from '@stock-bot/research/strategy-api';
export type StrategyReplayOptions = Omit<ReplayOptions, 'reverseCallbacks'>;
type StrategyRun<Result extends ReplayOutput> = {
result: Result;
/** decisionMs includes state staging, validation and admission feedback. */
metrics: ReplayMetrics;
diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>;
};
/** Replay failure plus the last confirmed callback diagnostics for investigation. */
export class StrategyReplayError extends Error {
constructor(
cause: unknown,
readonly diagnostics: DeepReadonly<StrategyDiagnosticSnapshot>
) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = 'StrategyReplayError';
}
}
/* 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[],
options: StrategyReplayOptions & { resultFormat: 'report' }
): StrategyRun<ReplayReportResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions & { resultFormat: 'projection' }
): StrategyRun<ReplayProjectionResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options?: StrategyReplayOptions & { resultFormat?: 'trace' }
): StrategyRun<ReplayResult>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions
): StrategyRun<ReplayOutput>;
export function runStrategyReplay(
load: ReturnType<typeof prepareReplayLoad>,
programs: readonly StrategyProgram[],
options: StrategyReplayOptions = {}
): StrategyRun<ReplayOutput> {
/* eslint-enable no-redeclare */
const identity = freeze(replayIdentitySchema.parse(load.identity));
const config = replayConfigSchema.parse(load.config);
const controller = new StrategyController(identity, programs, config);
try {
// Native construction synchronously detaches prepared data/config into Rust.
// Caller mutations during later callbacks cannot rewrite that loaded input.
const output = runReplaySession(
new NativeReplaySession({ ...load, identity, config }),
controller,
{ ...options }
);
return { ...output, diagnostics: controller.snapshot() };
} catch (cause) {
throw new StrategyReplayError(cause, controller.snapshot());
}
}