import { afterEach, describe, expect, test } from 'bun:test'; import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery'; import { config, makeExecution, order, quote, start } from '../fixtures/execution'; import { attachCounter, CounterStrategy, FaultRepository, recoveryConfig, } from '../fixtures/strategy-recovery'; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function fixture() { const repository = new FaultRepository(new BacktestExecutionRepository()); const { execution, engine } = makeExecution(repository); await execution.initialize(config, engine); cleanup.push(() => execution.shutdown()); const { manager, strategy } = await attachCounter(execution); cleanup.push(() => manager.shutdown()); return { repository, execution, manager, strategy }; } const isPending = (value: unknown) => (value as { status?: string }).status === 'pending'; const isDispatched = (value: unknown) => (value as { status?: string }).status === 'dispatched'; describe('transactional strategy recovery', () => { test('input order is its admission sequence, not JavaScript numeric object-key enumeration', async () => { const f = await fixture(); await f.execution.enqueueMarketData(quote('10')); await f.execution.enqueueMarketData(quote('2', 110, 100, start + 1)); await f.manager.recover(); expect(f.strategy.equities).toEqual([10000, 10009.9]); }); test('a failed decision restores indicators and leaves later admitted inputs recoverable', async () => { const f = await fixture(); f.strategy.failDecision = true; await f.execution.enqueueMarketData(quote('one')); await f.execution.enqueueMarketData(quote('two', 110, 100, start + 1)); await expect(f.manager.recover()).rejects.toThrow('decision failure'); expect(f.strategy.count).toBe(0); expect(f.strategy.getPosition('A')).toBe(0); expect((await f.execution.getRecoveryStatus()).pendingInputs).toBe(true); await expect(f.execution.submitOrder(order('manual'))).rejects.toThrow('backlog'); f.strategy.failDecision = false; await f.manager.recover(); expect(f.strategy.count).toBe(2); expect(f.strategy.getPosition('A')).toBe(2); expect(f.strategy.equities).toEqual([10000, 10009.9]); expect((await f.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); await f.manager.onMarketData(quote('one')); expect(f.strategy.count).toBe(2); }); test.each(['before', 'after'] as const)( 'checkpoint + intent roll back together on a %s intent-write failure', async stage => { const f = await fixture(); f.repository.fault = { method: 'putIntent', matches: isPending, stage }; await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('transaction failure'); expect(f.strategy.count).toBe(0); expect((await f.execution.getAccount()).cash).toBe(10000); expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false); await f.manager.recover(); expect(f.strategy.count).toBe(1); expect(f.strategy.getPosition('A')).toBe(1); } ); test('a lost checkpoint commit acknowledgement resumes from durable state, not a second decision', async () => { const f = await fixture(); f.repository.fault = { method: 'putIntent', matches: isPending, stage: 'commit' }; await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('commit acknowledgement'); expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(true); await f.manager.shutdown(); const restarted = await attachCounter(f.execution); cleanup.push(() => restarted.manager.shutdown()); expect(restarted.strategy.count).toBe(1); expect(restarted.strategy.getPosition('A')).toBe(1); expect(restarted.strategy.getPerformance().trades).toBe(1); await restarted.manager.onMarketData(quote('one')); expect(restarted.strategy.count).toBe(1); }); test.each(['after', 'commit'] as const)( 'outbox dispatch is idempotent after a %s dispatch-status failure', async stage => { const f = await fixture(); f.repository.fault = { method: 'putIntent', matches: isDispatched, stage }; await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('injected'); await f.manager.recover(); expect(f.strategy.count).toBe(1); expect(f.strategy.getPosition('A')).toBe(1); expect(f.strategy.getPerformance().trades).toBe(1); expect((await f.execution.getAccount()).cash).toBe(9899.9); expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false); } ); test('fill callback failure cannot lose a committed fill or advance its checkpoint', async () => { const f = await fixture(); f.strategy.failFill = true; await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('fill callback'); expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1); expect(f.strategy.getPosition('A')).toBe(0); expect(f.strategy.getPerformance().trades).toBe(0); f.strategy.failFill = false; await f.manager.recover(); await f.manager.recover(); expect(f.strategy.getPosition('A')).toBe(1); expect(f.strategy.getPerformance().trades).toBe(1); }); test('shutdown preserves unfilled orders, indicator history, and committed cursor', async () => { const f = await fixture(); await f.manager.onMarketData(quote('one', 100, 0)); const before = f.strategy.captureCheckpoint(); await f.manager.shutdown(); const restarted = await attachCounter(f.execution); cleanup.push(() => restarted.manager.shutdown()); expect(restarted.strategy.captureCheckpoint()).toEqual(before); expect((await f.execution.getStrategySnapshot('counter')).orders).toHaveLength(1); await restarted.manager.onMarketData(quote('two', 100, 100, start + 1)); expect(restarted.strategy.getPerformance().trades).toBe(2); }); test('configuration and implementation versions cannot silently reset an existing strategy', async () => { const f = await fixture(); await f.manager.onMarketData(quote('one')); await f.manager.shutdown(); const changed = new CounterStrategy(f.execution, { ...recoveryConfig, parameters: { changed: true }, }); await expect(attachCounter(f.execution, changed)).rejects.toThrow('version changed'); const version = new CounterStrategy(f.execution); version.version = 'counter/v2'; await expect(attachCounter(f.execution, version)).rejects.toThrow('version changed'); expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1); }); test('disabled-period inputs do not become retroactive trades when re-enabled', async () => { const f = await fixture(); await f.manager.onMarketData(quote('one')); await f.manager.disableStrategy('counter'); await f.manager.onMarketData(quote('two', 100, 100, start + 1)); await f.manager.enableStrategy('counter'); await f.manager.recover(); expect(f.strategy.count).toBe(1); await f.manager.onMarketData(quote('three', 100, 100, start + 2)); expect(f.strategy.count).toBe(2); }); test('observers run only after checkpoint commit and cannot roll back financial intent', async () => { const f = await fixture(); let signals = 0; f.strategy.on('signal', () => { signals++; throw new Error('observer'); }); f.execution.setObserver(async () => { throw new Error('observer'); }); await f.manager.onMarketData(quote('one')); expect(signals).toBe(1); expect(f.strategy.count).toBe(1); expect(f.strategy.getPosition('A')).toBe(1); }); test('checkpoint serialization rejects lossy or non-finite state', () => { for (const value of [NaN, Infinity, undefined, new Map(), new Date(), { hidden: undefined }]) { expect(() => canonicalJson(value)).toThrow('plain JSON'); } expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 })); }); test('a callback cannot open a nested repository transaction and deadlock its account', async () => { const f = await fixture(); f.strategy.onDecision = async () => { await f.execution.getOrderStatus('anything'); }; await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow( 'cannot perform repository I/O' ); expect(f.strategy.count).toBe(0); }); test('a reused intent ID cannot replace a dispatched request or advance its next decision', async () => { const f = await fixture(); f.strategy.onDecision = async () => { f.execution.captureStrategyOrder(order('fixed-id', 'buy', 1), 'counter'); }; await f.manager.onMarketData(quote('one')); await expect(f.manager.onMarketData(quote('two', 100, 100, start + 1))).rejects.toThrow( 'Conflicting strategy order intent' ); expect(f.strategy.count).toBe(1); expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2); }); });