import { describe, expect, test } from 'bun:test'; import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import { config, logger } from '../fixtures/execution'; function fixture(failAt?: string) { const calls: string[] = []; const failure = new Error('injected lifecycle failure'); const failures = new Map(); const resources = new Set(); if (failAt) { failures.set(failAt, failure); } const record = async (step: string) => { calls.push(step); 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, execution: { initialize: () => record('execution.initialize'), shutdown: () => record('execution.shutdown'), }, storage: { initialize: () => record('storage.initialize'), shutdown: () => record('storage.shutdown'), }, strategies: { restoreStrategies: () => record('strategies.restore'), shutdown: () => record('strategies.shutdown'), }, marketData: { initialize: () => record('market.initialize'), shutdown: () => record('market.shutdown'), }, }); return { mode, calls, failure, failures, resources }; } describe('explicit mode lifecycle dependencies', () => { test('paper recovery completes before the feed starts; shutdown drains the feed before strategies and execution', async () => { const f = fixture(); await f.mode.initializeMode({ mode: 'paper', startingCapital: 10000 }); expect(f.calls).toEqual([ 'execution.initialize', 'storage.initialize', 'strategies.restore', 'market.initialize', ]); await f.mode.shutdown(); expect(f.calls.slice(4)).toEqual([ 'market.shutdown', 'strategies.shutdown', 'execution.shutdown', 'storage.shutdown', ]); expect(() => f.mode.getTradingEngine()).toThrow('not initialized'); expect(f.mode.getConfig()).toBeNull(); await f.mode.shutdown(); expect(f.calls).toHaveLength(8); }); test('backtest mode replaces the current engine without restoring paper strategies', async () => { const f = fixture(); await f.mode.initializeMode(config); const prior = f.mode.getTradingEngine(); await f.mode.initializeMode(config); expect(f.mode.getTradingEngine()).not.toBe(prior); expect(f.calls).toEqual([ 'execution.initialize', 'storage.initialize', 'market.initialize', 'market.shutdown', 'strategies.shutdown', 'execution.shutdown', 'storage.shutdown', 'execution.initialize', 'storage.initialize', 'market.initialize', ]); await f.mode.shutdown(); }); test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown', 'storage.shutdown'])( '%s failure still closes every other dependency and clears the mode engine', async failAt => { const f = fixture(failAt); await f.mode.initializeMode(config); await expect(f.mode.shutdown()).rejects.toBe(f.failure); expect(f.calls.slice(3)).toEqual([ 'market.shutdown', 'strategies.shutdown', 'execution.shutdown', '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(); }); });