feat(paper): gate canonical execution on durable feed readiness

This commit is contained in:
Boki 2026-10-23 16:50:35 -04:00
parent c01e96e4dd
commit 75abae2cfc
24 changed files with 3720 additions and 66 deletions

View file

@ -6,14 +6,19 @@ import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
import { ModeManager } from './core/ModeManager';
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
import { validatePaperConfiguration } from './paper/feed';
import { PaperTradingManager } from './paper/PaperTradingManager';
import { AnalyticsService } from './services/AnalyticsService';
import { ExecutionService } from './services/ExecutionService';
import { MarketDataService } from './services/MarketDataService';
import { StorageService } from './services/StorageService';
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
import { createBuiltinStrategy } from './strategies/canonical-sma';
import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
@ -47,11 +52,20 @@ export async function registerOrchestratorServices(
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
strategyRegistry?: StrategyRegistry;
canonicalPaper?: PaperConfigurationInput;
paperTradingCapital?: number;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'paper' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
if (options.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
const canonicalPaper =
options.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(options.canonicalPaper);
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
// Create a service adapter that provides the expected interface
@ -60,6 +74,24 @@ export async function registerOrchestratorServices(
if (!services.custom) {
Object.defineProperty(services, 'custom', { value: custom, enumerable: true });
}
if (
custom.CanonicalPaperRuntime ||
container.hasRegistration('CanonicalPaperRuntime') ||
(canonicalPaper &&
(
[
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
] as const
).some(key => custom[key] || container.hasRegistration(key)))
) {
throw new Error('Canonical paper requires a fresh runtime composition');
}
// Create storage service first as it's needed by other services
const storageService = new StorageService(
@ -70,6 +102,67 @@ export async function registerOrchestratorServices(
options
);
if (canonicalPaper) {
if (!services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const paper = new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
});
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(services.postgres),
logger: services.logger,
});
const analytics = new AnalyticsService(services);
// No legacy order gateway, feed listener or mode initializer is exposed in
// this composition. Research still runs in the existing isolated worker.
Object.assign(custom, {
StorageService: storageService,
AnalyticsService: analytics,
CanonicalPaperRuntime: paper,
BacktestEngine: engine,
BacktestRunner: runner,
});
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
orchestratorServices: IServiceContainer;
}
>;
canonicalContainer.register({
StorageService: asValue(storageService),
AnalyticsService: asValue(analytics),
CanonicalPaperRuntime: asValue(paper),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
try {
if (options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper.shutdown().catch(() => {});
throw error;
}
return;
}
// Callbacks are invoked after composition: the feed drains the manager, and
// factories receive the current mode without either service locating its peers.
const marketDataService: MarketDataService = new MarketDataService({
@ -174,7 +267,10 @@ export async function registerOrchestratorServices(
// Initialize mode manager with default paper trading mode
if (role === 'paper' && options.initializeMode !== false) {
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
await modeManager.initializeMode({
mode: 'paper',
startingCapital: options.paperTradingCapital ?? 100000,
});
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });