fix(runtime): isolate legacy research from paper execution

This commit is contained in:
Boki 2026-10-22 14:50:24 -04:00
parent ee670a3bd1
commit 43ffb547be
7 changed files with 485 additions and 9 deletions

View file

@ -18,12 +18,29 @@ import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
export type OrchestratorRole = 'paper' | 'research-only';
export function assertSupportedComposition(role: OrchestratorRole, useRustEngine: boolean): void {
if (role !== 'paper' && role !== 'research-only') {
throw new Error('Unsupported runtime role: expected paper or research-only');
}
if (typeof useRustEngine !== 'boolean') {
throw new Error('Runtime useRustEngine option must be a boolean');
}
if (role !== 'research-only' && !useRustEngine) {
throw new Error(
'Unsupported runtime combination: TypeScript backtests require a research-only composition; paper requires the isolated native engine'
);
}
}
/**
* Register orchestrator-specific services in the DI container
*/
export async function registerOrchestratorServices(
container: AwilixContainer<ServiceDefinitions>,
options: {
role?: OrchestratorRole;
initializeMode?: boolean;
useRustEngine?: boolean;
allowSyntheticData?: boolean;
@ -32,6 +49,11 @@ export async function registerOrchestratorServices(
strategyRegistry?: StrategyRegistry;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'paper' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
// Create a service adapter that provides the expected interface
const services = container.resolve('serviceContainer') as IServiceContainer;
const custom = services.custom ?? {};
@ -55,7 +77,7 @@ export async function registerOrchestratorServices(
storage: storageService,
drainStrategies: () => strategyManager.drain(),
});
const executionService = new ExecutionService(services, storageService);
const executionService = new ExecutionService(services, storageService, { allowedMode });
const analyticsService = new AnalyticsService(services);
const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
const strategyManager: StrategyManager = new StrategyManager({
@ -65,13 +87,14 @@ export async function registerOrchestratorServices(
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
});
const modeManager: ModeManager = new ModeManager({
allowedMode,
logger: services.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const backtestEngine = options.useRustEngine
const backtestEngine = useRustEngine
? new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{
@ -93,12 +116,12 @@ export async function registerOrchestratorServices(
);
const backtestRunner = new BacktestRunner({
engine: backtestEngine,
engineName: options.useRustEngine ? 'native' : 'typescript',
engineName: useRustEngine ? 'native' : 'typescript',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config),
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
});
// Store custom services
@ -150,7 +173,7 @@ export async function registerOrchestratorServices(
strategyManager.setupEventListeners();
// Initialize mode manager with default paper trading mode
if (options.initializeMode !== false) {
if (role === 'paper' && options.initializeMode !== false) {
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
}
// Start job consumption only after the shared graph and initial mode are ready.

View file

@ -23,6 +23,7 @@ export class ModeManager extends EventEmitter {
private isInitialized = false;
constructor(
private readonly dependencies: {
allowedMode?: 'paper' | 'backtest';
logger: Pick<Logger, 'info'>;
marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
@ -37,6 +38,11 @@ export class ModeManager extends EventEmitter {
if (config.mode === 'live') {
throw new Error('Live trading is disabled: no real broker adapter exists');
}
if (this.dependencies.allowedMode && config.mode !== this.dependencies.allowedMode) {
throw new Error(
`Runtime composition only permits ${this.dependencies.allowedMode} mode; cannot initialize ${config.mode}`
);
}
// Validate config based on mode
switch (config.mode) {
case 'backtest':

View file

@ -60,7 +60,11 @@ export class ExecutionService extends EventEmitter {
constructor(
private readonly container: OrchestratorServices,
_storage: StorageService,
private readonly options: { repository?: ExecutionRepository; clock?: () => number } = {}
private readonly options: {
repository?: ExecutionRepository;
clock?: () => number;
allowedMode?: 'paper' | 'backtest';
} = {}
) {
super();
this.simulation = new SimulationExecution({
@ -93,6 +97,11 @@ export class ExecutionService extends EventEmitter {
'Live trading is disabled: no real broker adapter exists'
);
}
if (this.options.allowedMode && config.mode !== this.options.allowedMode) {
throw new UnsupportedExecutionError(
`Runtime composition only permits ${this.options.allowedMode} mode; cannot initialize ${config.mode}`
);
}
await this.tail;
this.closing = false;
this.mode = undefined;

View file

@ -1,10 +1,22 @@
import { ServiceContainerBuilder } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { registerOrchestratorServices } from './container';
import {
assertSupportedComposition,
registerOrchestratorServices,
type OrchestratorRole,
} from './container';
import type { OrchestratorServices } from './types';
/** Use the shared builder for connection setup and adapter ownership. */
export async function createContainer(config: StockAppConfig) {
export async function createContainer(
config: StockAppConfig,
options: { role?: OrchestratorRole } = {}
) {
const role = options.role === undefined ? 'paper' : options.role;
const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine;
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
// Fail before opening connections as well as before registering runtime services.
assertSupportedComposition(role, useRustEngine);
const container = await new ServiceContainerBuilder()
.withConfig(config)
.withOptions({
@ -18,7 +30,8 @@ export async function createContainer(config: StockAppConfig) {
})
.build();
await registerOrchestratorServices(container, {
useRustEngine: config.services?.orchestrator?.backtesting?.useRustEngine ?? true,
role,
useRustEngine,
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,

View file

@ -166,6 +166,8 @@ async function composedRuntime(
};
di.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(di, {
role: 'research-only',
useRustEngine: false,
initializeMode: false,
...options,
});

View file

@ -0,0 +1,151 @@
import { asFunction, asValue, createContainer as createDiContainer } from 'awilix';
import { afterEach, describe, expect, test } from 'bun:test';
import { ServiceContainerBuilder, type ServiceCradle } from '@stock-bot/di';
import type { StockAppConfig } from '@stock-bot/stock-config';
import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { defaultRiskLimits } from '../../apps/stock/orchestrator/src/execution/model';
import { createContainer } from '../../apps/stock/orchestrator/src/simple-container';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { config, logger, makeExecution } from '../fixtures/execution';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
async function compose(options: Parameters<typeof registerOrchestratorServices>[1] = {}) {
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const services: OrchestratorServices = { logger };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, options);
const runtime = services.custom!;
cleanup.push(async () => {
await runtime.BacktestRunner!.shutdown();
await runtime.ModeManager!.shutdown();
await runtime.StrategyManager!.shutdown();
await container.dispose();
});
return runtime;
}
describe('research runtime composition admission', () => {
test.each([true, false])(
'legacy_paper_combination_rejected_before_prepare (initializeMode=%s)',
async initializeMode => {
let resolved = 0;
const container = createDiContainer<ServiceCradle>();
container.register({
serviceContainer: asFunction(() => {
resolved++;
throw new Error('Runtime services must not be resolved');
}),
});
await expect(
registerOrchestratorServices(container, { useRustEngine: false, initializeMode })
).rejects.toThrow('TypeScript backtests require a research-only composition');
expect(resolved).toBe(0);
}
);
test('unsafe application startup fails before connection setup', async () => {
const config = {
services: { orchestrator: { backtesting: { useRustEngine: false } } },
} as StockAppConfig;
await expect(createContainer(config)).rejects.toThrow('Unsupported runtime combination');
});
test('unchecked role and backend options fail closed before service resolution', async () => {
const container = createDiContainer<ServiceCradle>();
for (const options of [
{ role: 'research' },
{ role: null },
{ useRustEngine: 'false' },
{ useRustEngine: null },
]) {
await expect(
registerOrchestratorServices(
container,
options as unknown as Parameters<typeof registerOrchestratorServices>[1]
)
).rejects.toThrow('role' in options ? 'Unsupported runtime role' : 'must be a boolean');
}
});
test('standalone_legacy_research_allowed without automatic paper initialization', async () => {
const runtime = await compose({
role: 'research-only',
useRustEngine: false,
allowSyntheticData: true,
syntheticSeed: 42,
});
expect(runtime.BacktestEngine).toBeInstanceOf(BacktestEngine);
expect(runtime.ModeManager!.getConfig()).toBeNull();
await runtime.ModeManager!.initializeMode(config);
const result = await runtime.BacktestEngine!.runBacktest(config);
expect(result.status).toBe('completed');
expect(result.trades.length).toBeGreaterThan(0);
expect(runtime.ModeManager!.getConfig()).toEqual(config);
});
test('research_only_paper_activation_denied through every exposed initializer', async () => {
const runtime = await compose({ role: 'research-only', useRustEngine: false });
const mode = runtime.ModeManager!;
const execution = runtime.ExecutionService!;
await mode.initializeMode(config);
const engine = mode.getTradingEngine();
const account = await execution.getAccount();
const paper = { mode: 'paper' as const, startingCapital: 123 };
let shutdowns = 0;
mode.on('shutdown', () => shutdowns++);
await expect(mode.initializeMode(paper)).rejects.toThrow('only permits backtest');
await expect(mode.transitionMode('backtest', 'paper', paper)).rejects.toThrow(
'only permits backtest'
);
await expect(execution.initialize(paper, engine)).rejects.toThrow('only permits backtest');
const live = {
mode: 'live' as const,
broker: 'ib',
accountId: 'not-a-real-account',
accountType: 'cash' as const,
riskLimits: { ...defaultRiskLimits },
};
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
expect(shutdowns).toBe(0);
expect(mode.getTradingEngine()).toBe(engine);
expect(mode.getConfig()).toEqual(config);
expect(await execution.getAccount()).toEqual(account);
});
test('paper composition defaults to native and cannot be switched to a legacy shared mode', async () => {
const runtime = await compose({ initializeMode: false });
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
await expect(runtime.ModeManager!.initializeMode(config)).rejects.toThrow('only permits paper');
await expect(
runtime.ExecutionService!.initialize(config, makeExecution().engine)
).rejects.toThrow('only permits paper');
expect(runtime.ModeManager!.getConfig()).toBeNull();
});
test('research-only native composition also forbids paper startup and activation', async () => {
const runtime = await compose({ role: 'research-only' });
expect(runtime.BacktestEngine).toBeInstanceOf(RustBacktestAdapter);
expect(runtime.ModeManager!.getConfig()).toBeNull();
await expect(
runtime.ModeManager!.initializeMode({ mode: 'paper', startingCapital: 10000 })
).rejects.toThrow('only permits backtest');
});
});

View file

@ -0,0 +1,272 @@
import { createHash, randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { asValue } from 'awilix';
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { Pool } from 'pg';
import { ServiceContainerBuilder } from '@stock-bot/di';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
import {
BacktestConfigSchema,
type OrchestratorServices,
} from '../../apps/stock/orchestrator/src/types';
import { logger, quote } from '../fixtures/execution';
import { CounterStrategy } from '../fixtures/strategy-recovery';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
const research = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['RESEARCH.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated safety database required');
}
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric);`);
for (const filename of [
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'11-simulation-execution-ledger.sql',
'12-historical-datasets.sql',
'13-strategy-recovery.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const container = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const services: OrchestratorServices = { logger, postgres };
container.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(container, {
initializeMode: false,
nativeExecutionTimeoutMs: 5000,
});
const runtime = services.custom!;
const mode = runtime.ModeManager!;
const runner = runtime.BacktestRunner!;
const market = runtime.MarketDataService!;
const storage = runtime.StorageService!;
const execution = runtime.ExecutionService!;
const strategies = runtime.StrategyManager!;
const feed = { connected: false };
// Only the external transport is offline; real admission, ledger, checkpoints and replay run.
const feedStart = spyOn(market, 'initialize').mockImplementation(async () => {
feed.connected = true;
});
const originalShutdown = market.shutdown.bind(market);
const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => {
feed.connected = false;
await originalShutdown();
});
const lifecycle = [
feedStart,
feedStop,
spyOn(execution, 'initialize'),
spyOn(execution, 'shutdown'),
spyOn(storage, 'initialize'),
spyOn(storage, 'shutdown'),
spyOn(strategies, 'restoreStrategies'),
spyOn(strategies, 'shutdown'),
];
cleanup.push(async () => {
try {
await runner.shutdown();
await mode.shutdown();
await strategies.shutdown();
await container.dispose();
} finally {
for (const method of lifecycle) method.mockRestore();
}
});
await mode.initializeMode({
mode: 'paper',
accountId: 'paper-fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
});
const strategy = new CounterStrategy(execution);
await strategies.attachStrategy(strategy);
await market.subscribeToSymbol('A');
market.ingest(quote('paper-one', 100, 100, Date.now()));
await market.flush();
expect(strategy.count).toBe(1);
expect((await execution.getAccount()).cash).toBe(9899.9);
let failedRead = false;
storage.getHistoricalBars = async () => {
if (failedRead) throw new Error('Injected research history failure');
return Array.from({ length: 70 }, (_, i) => {
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
return {
symbol: research.symbols[0]!,
source: 'eod' as const,
timestamp: new Date(Date.parse(research.startDate) + i * 86400000),
open: close,
high: close + 1,
low: close - 1,
close,
volume: 1000000,
};
});
};
const stateHash = async () => {
const state: unknown[] = [];
for (const [table, columns] of [
['simulation_accounts', 'id,state'],
['simulation_orders', 'id,payload'],
['simulation_fills', 'id,payload'],
['simulation_events', 'id,fingerprint'],
['simulation_market_inputs', 'id,payload'],
['simulation_strategy_journal', 'sequence,payload'],
['simulation_strategy_checkpoints', 'strategy_id,payload'],
['simulation_strategy_intents', 'client_order_id,payload'],
]) {
const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows;
state.push([table, rows.map(row => canonicalJson(row)).sort()]);
}
return createHash('sha256').update(canonicalJson(state)).digest('hex');
};
return {
services,
pool,
runner,
mode,
execution,
market,
strategies,
strategy,
feed,
stateHash,
lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length),
failHistory: (fail: boolean) => {
failedRead = fail;
},
};
}
describe.skipIf(!url)('research isolation from a real paper ledger', () => {
test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper');
await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow(
'only permits paper'
);
await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper');
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.isPaperMode()).toBe(true);
expect(f.feed.connected).toBe(true);
expect(f.lifecycleCounts()).toEqual(
lifecycle.map((count, index) => count + (index === 2 ? 1 : 0))
);
expect(await f.stateHash()).toBe(before);
});
test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => {
const f = await fixture();
const engine = f.mode.getTradingEngine();
const paperConfig = f.mode.getConfig();
const before = await f.stateHash();
const lifecycle = f.lifecycleCounts();
const unchanged = async () => {
expect(await f.stateHash()).toBe(before);
expect(f.mode.getTradingEngine()).toBe(engine);
expect(f.mode.getConfig()).toEqual(paperConfig);
expect(f.lifecycleCounts()).toEqual(lifecycle);
expect(f.market.listenerCount('marketDataBatch')).toBe(1);
expect(f.strategies.getActiveStrategies()).toEqual(['counter']);
expect(f.feed.connected).toBe(true);
};
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
for (let i = 0; i < 2; i++) {
let stopped: Promise<void> | undefined;
f.runner.once('progress', () => {
stopped = f.runner.stopBacktest();
});
const outcome = await f.runner.runBacktest(research).catch(error => error);
await stopped;
expect(stopped).toBeDefined();
expect(outcome).toBeInstanceOf(BacktestCancelledError);
await unchanged();
f.failHistory(true);
await expect(f.runner.runBacktest(research)).rejects.toThrow(
'Injected research history failure'
);
f.failHistory(false);
await unchanged();
}
expect((await f.runner.runBacktest(research)).status).toBe('completed');
await unchanged();
expect(
(
await f.pool.query(
'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text'
)
).rows
).toEqual([
{ status: 'cancelled', count: 2 },
{ status: 'completed', count: 2 },
{ status: 'failed', count: 2 },
]);
// The existing feed still makes exactly one new durable paper decision after research.
f.market.ingest(quote('paper-two', 101, 100, Date.now()));
await f.market.flush();
expect(f.strategy.count).toBe(2);
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
}, 15000);
});