fix(runtime): recover safely from partial initialization

This commit is contained in:
Boki 2026-10-22 14:17:25 -04:00
parent a21a1b8cb8
commit 3d26da07f5
2 changed files with 190 additions and 40 deletions

View file

@ -13,6 +13,9 @@ import {
type TradingMode,
} from '../types';
const shutdownOrder = ['marketData', 'strategies', 'execution', 'storage'] as const;
type LifecycleService = (typeof shutdownOrder)[number];
export class ModeManager extends EventEmitter {
private mode: TradingMode = 'paper';
private config: ModeConfig | null = null;
@ -49,15 +52,26 @@ export class ModeManager extends EventEmitter {
await this.shutdown();
}
this.mode = config.mode;
this.config = config;
const attempted = new Set<LifecycleService>();
try {
this.mode = config.mode;
this.config = config;
// Create Rust trading engine with appropriate config
const engineConfig = this.createEngineConfig(config);
this.tradingEngine = new TradingEngine(config.mode, engineConfig);
// Create Rust trading engine with appropriate config
const engineConfig = this.createEngineConfig(config);
this.tradingEngine = new TradingEngine(config.mode, engineConfig);
// Initialize services for the mode
await this.initializeServices(config);
await this.initializeServices(config, attempted);
} catch (error) {
try {
await this.shutdownServices(attempted);
} catch {
// Every cleanup was attempted; preserve the original initialization error.
} finally {
this.clearState();
}
throw error;
}
this.isInitialized = true;
this.emit('modeChanged', config);
@ -103,19 +117,54 @@ export class ModeManager extends EventEmitter {
}
}
private async initializeServices(config: ModeConfig): Promise<void> {
private async initializeServices(
config: ModeConfig,
attempted: Set<LifecycleService>
): Promise<void> {
// Register before each await: an initializer may acquire resources then fail.
// Configure execution service
attempted.add('execution');
await this.dependencies.execution.initialize(config, defined(this.tradingEngine));
// Configure storage
attempted.add('storage');
await this.dependencies.storage.initialize(config);
if (config.mode === 'paper') {
attempted.add('strategies');
await this.dependencies.strategies.restoreStrategies();
}
// Admission is ready before a real-time feed can deliver events.
attempted.add('marketData');
await this.dependencies.marketData.initialize(config);
}
private async shutdownServices(attempted: ReadonlySet<LifecycleService>): Promise<void> {
let failed = false;
let failure: unknown;
for (const service of shutdownOrder) {
if (!attempted.has(service)) {
continue;
}
try {
await this.dependencies[service].shutdown();
} catch (error) {
if (!failed) {
failure = error;
}
failed = true;
}
}
if (failed) {
throw failure;
}
}
private clearState(): void {
this.tradingEngine = null;
this.config = null;
this.isInitialized = false;
}
getCurrentMode(): TradingMode {
return this.mode;
}
@ -161,36 +210,11 @@ export class ModeManager extends EventEmitter {
this.dependencies.logger.info(`Shutting down ${this.mode} mode...`);
// Shutdown services
let failure: unknown;
try {
await this.dependencies.marketData.shutdown();
} catch (error) {
failure = error;
}
try {
await this.dependencies.strategies.shutdown();
} catch (error) {
failure ??= error;
}
try {
await this.dependencies.execution.shutdown();
} catch (error) {
failure ??= error;
}
try {
await this.dependencies.storage.shutdown();
} catch (error) {
failure ??= error;
}
// Cleanup trading engine
this.tradingEngine = null;
this.isInitialized = false;
this.emit('shutdown');
if (failure) {
throw failure;
await this.shutdownServices(new Set(shutdownOrder));
} finally {
this.clearState();
this.emit('shutdown');
}
}
}

View file

@ -4,10 +4,23 @@ import { config, logger } from '../fixtures/execution';
function fixture(failAt?: string) {
const calls: string[] = [];
const failure = new Error('injected shutdown failure');
const failure = new Error('injected lifecycle failure');
const failures = new Map<string, unknown>();
const resources = new Set<string>();
if (failAt) {
failures.set(failAt, failure);
}
const record = async (step: string) => {
calls.push(step);
if (step === failAt) throw failure;
const [service, operation] = step.split('.');
if (operation === 'shutdown') {
resources.delete(service);
} else {
resources.add(service);
}
if (failures.has(step)) {
throw failures.get(step);
}
};
const mode = new ModeManager({
logger,
@ -28,7 +41,7 @@ function fixture(failAt?: string) {
shutdown: () => record('market.shutdown'),
},
});
return { mode, calls, failure };
return { mode, calls, failure, failures, resources };
}
describe('explicit mode lifecycle dependencies', () => {
@ -49,6 +62,7 @@ describe('explicit mode lifecycle dependencies', () => {
'storage.shutdown',
]);
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
expect(f.mode.getConfig()).toBeNull();
await f.mode.shutdown();
expect(f.calls).toHaveLength(8);
});
@ -87,8 +101,120 @@ describe('explicit mode lifecycle dependencies', () => {
'storage.shutdown',
]);
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
expect(f.mode.getConfig()).toBeNull();
await f.mode.shutdown();
expect(f.calls).toHaveLength(7);
}
);
const paper = { mode: 'paper' as const, startingCapital: 10000 };
const initialization = [
'execution.initialize',
'storage.initialize',
'strategies.restore',
'market.initialize',
];
const cleanup = [
'market.shutdown',
'strategies.shutdown',
'execution.shutdown',
'storage.shutdown',
];
test.each(initialization)(
'partial acquisition in %s cleans up attempted stages and allows retry without a success event',
async failAt => {
const f = fixture(failAt);
const events: unknown[] = [];
f.mode.on('modeChanged', changed => events.push(changed));
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
const attempted = initialization.slice(0, initialization.indexOf(failAt) + 1);
const acquired = new Set(attempted.map(step => step.split('.')[0]));
const applicableCleanup = cleanup.filter(step => acquired.has(step.split('.')[0]));
expect(f.calls).toEqual([...attempted, ...applicableCleanup]);
expect(f.resources.size).toBe(0);
expect(events).toEqual([]);
expect(f.mode.getConfig()).toBeNull();
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
const cleanupCount = f.calls.length;
await f.mode.shutdown();
expect(f.calls).toHaveLength(cleanupCount);
f.failures.clear();
await f.mode.initializeMode(paper);
expect(f.calls.slice(cleanupCount)).toEqual(initialization);
expect(events).toEqual([paper]);
expect(f.mode.getConfig()).toEqual(paper);
expect(f.mode.getTradingEngine()).toBeDefined();
await f.mode.shutdown();
expect(f.calls.slice(cleanupCount + initialization.length)).toEqual(cleanup);
expect(f.resources.size).toBe(0);
}
);
test.each(cleanup)(
'%s cleanup failure does not mask initialization error or skip remaining cleanup',
async cleanupFailure => {
const f = fixture('market.initialize');
f.failures.set(cleanupFailure, new Error('injected cleanup failure'));
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
expect(f.calls).toEqual([...initialization, ...cleanup]);
expect(f.resources.size).toBe(0);
expect(f.mode.getConfig()).toBeNull();
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
f.failures.clear();
await f.mode.initializeMode(paper);
await f.mode.shutdown();
expect(f.calls).toEqual([...initialization, ...cleanup, ...initialization, ...cleanup]);
}
);
test('failed mode replacement does not expose the prior or partially created engine', async () => {
const f = fixture();
await f.mode.initializeMode(config);
const prior = f.mode.getTradingEngine();
f.failures.set('storage.initialize', f.failure);
await expect(f.mode.initializeMode(paper)).rejects.toBe(f.failure);
expect(f.mode.getConfig()).toBeNull();
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
f.failures.clear();
await f.mode.initializeMode(paper);
expect(f.mode.getTradingEngine()).not.toBe(prior);
await f.mode.shutdown();
});
test('invalid configuration and disabled live trading reject before lifecycle side effects', async () => {
const f = fixture();
await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow();
expect(f.calls).toEqual([]);
expect(f.mode.getConfig()).toBeNull();
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
const live = {
mode: 'live' as const,
broker: 'disabled',
accountId: 'disabled',
accountType: 'cash' as const,
riskLimits: {
maxPositionSize: 1,
maxDailyLoss: 1,
maxOrderSize: 1,
maxGrossExposure: 1,
maxSymbolExposure: 1,
},
};
await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
expect(f.calls).toEqual([]);
await f.mode.initializeMode(paper);
const engine = f.mode.getTradingEngine();
await expect(f.mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
await expect(f.mode.initializeMode({ mode: 'paper', startingCapital: -1 })).rejects.toThrow();
expect(f.calls).toEqual(initialization);
expect(f.mode.getConfig()).toEqual(paper);
expect(f.mode.getTradingEngine()).toBe(engine);
await f.mode.shutdown();
});
});