Refactor execution boundaries and add durable strategy recovery

This commit is contained in:
Boki 2026-10-21 12:23:43 -04:00
parent d6b09eb635
commit 694c48bbdb
36 changed files with 3077 additions and 491 deletions

View file

@ -0,0 +1,334 @@
import { describe, expect, test } from 'bun:test';
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
import {
defaultRiskLimits,
type Account,
type StoredOrder,
} from '../../apps/stock/orchestrator/src/execution/model';
import type { ExecutionTransaction } from '../../apps/stock/orchestrator/src/execution/repository';
import type {
MarketInput,
StrategyCheckpoint,
StrategyOrderIntent,
} from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
const initial: Account = {
initialCapital: 10000,
cash: 10000,
realizedPnl: 0,
dailyPnl: 0,
day: '2024-01-01',
commission: 0.001,
slippage: 0,
limits: { ...defaultRiskLimits },
maxQuoteAgeMs: 60000,
positions: {},
quotes: {},
strategyPositions: {},
};
const input: MarketInput = {
id: '10',
sequence: 1,
status: 'pending',
market: {
type: 'trade',
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: 1 },
},
};
const request = {
symbol: 'A.US',
side: 'buy',
quantity: 1,
orderType: 'market',
timeInForce: 'DAY',
clientOrderId: '__proto__',
} as const;
const order: StoredOrder = {
request,
fingerprint: 'fingerprint',
policy: { commission: 0.001, slippage: 0 },
report: {
orderId: 'order',
clientOrderId: request.clientOrderId,
symbol: request.symbol,
side: request.side,
quantity: 1,
status: 'accepted',
fills: [],
timestamp: 1,
},
};
const checkpoint: StrategyCheckpoint = {
strategyId: 'strategy',
config: {
id: 'strategy',
name: 'test',
enabled: true,
symbols: ['A.US'],
parameters: {},
allocation: 1,
},
configHash: 'hash',
version: 'v1',
enabled: true,
cursor: 0,
state: { count: 0 },
};
const intent: StrategyOrderIntent = {
clientOrderId: request.clientOrderId,
strategyId: checkpoint.strategyId,
sequence: 1,
request,
status: 'pending',
};
const fill = { id: '__proto__', price: 100, quantity: 1, commission: 0.1, timestamp: 1, pnl: 0 };
const journal = {
kind: 'market' as const,
market: input.market,
recipients: ['strategy'],
account: initial,
};
async function fixture(account = initial) {
const repository = new BacktestExecutionRepository();
await repository.initialize('run', account);
return {
repository,
transact: <T>(work: (tx: ExecutionTransaction) => Promise<T>) =>
repository.transact('run', work),
};
}
describe('run-local execution transaction isolation', () => {
test('uninitialized stores fail explicitly', async () => {
await expect(new BacktestExecutionRepository().transact('run', async () => 1)).rejects.toThrow(
'not initialized'
);
});
test('a failed transaction rolls back every table, index, sequence and account mutation', async () => {
const f = await fixture();
await expect(
f.transact(async tx => {
tx.account.cash = 1;
await tx.putOrder(order);
await tx.insertFill(order.report.orderId, fill);
await tx.recordEvent('__proto__', 'hash');
await tx.putStrategy(checkpoint);
await tx.putIntent(intent);
await tx.putInput(input);
await tx.appendJournal(journal);
expect(await tx.findOrder('__proto__')).toEqual(order);
expect(await tx.nextJournal(0)).toMatchObject({ sequence: 1 });
throw new Error('rollback');
})
).rejects.toThrow('rollback');
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
expect(tx.account.strategySequence).toBeUndefined();
expect(await tx.findOrder('__proto__')).toBeUndefined();
expect(await tx.getOrder('order')).toBeUndefined();
expect(await tx.openOrders()).toEqual([]);
expect(await tx.strategies()).toEqual([]);
expect(await tx.nextIntent()).toBeUndefined();
expect(await tx.nextInput()).toBeUndefined();
expect(await tx.nextJournal(0)).toBeUndefined();
expect(await tx.recordEvent('__proto__', 'hash')).toBe(true);
expect(await tx.insertFill('order', fill)).toBe(true);
});
});
test('caller-owned objects, returned reads and retained transaction references cannot mutate commits', async () => {
const seed = structuredClone(initial);
const f = await fixture(seed);
seed.cash = 0;
const writes = structuredClone({ order, checkpoint, intent, input, journal });
let escaped!: ExecutionTransaction;
const result = await f.transact(async tx => {
escaped = tx;
await tx.putOrder(writes.order);
await tx.putStrategy(writes.checkpoint);
await tx.putIntent(writes.intent);
await tx.putInput(writes.input);
await tx.appendJournal(writes.journal);
return tx.account;
});
result.cash = 2;
escaped.account.cash = 3;
writes.order.report.status = 'rejected';
writes.checkpoint.enabled = false;
writes.intent.status = 'dispatched';
writes.input.status = 'applied';
writes.journal.account.cash = 4;
await expect(escaped.putInput(input)).rejects.toThrow('finished');
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
(await tx.getOrder('order'))!.report.status = 'rejected';
(await tx.strategies())[0]!.enabled = false;
(await tx.nextInput())!.status = 'applied';
(await tx.nextIntent())!.status = 'dispatched';
(await tx.nextJournal(0))!.payload.account.cash = 5;
});
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([order]);
expect(await tx.strategies()).toEqual([checkpoint]);
expect(await tx.nextInput()).toEqual(input);
expect(await tx.nextIntent()).toEqual(intent);
expect((await tx.nextJournal(0))?.payload.account.cash).toBe(10000);
});
});
test('uncloneable callback results roll back before publishing any staged writes', async () => {
const f = await fixture();
await expect(
f.transact(async tx => {
tx.account.cash = 0;
await tx.putOrder(order);
return () => {};
})
).rejects.toThrow();
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
expect(await tx.openOrders()).toEqual([]);
});
});
test('transactions serialize and a failed predecessor does not poison the queue', async () => {
const f = await fixture();
const results = await Promise.allSettled([
f.transact(async tx => {
tx.account.cash -= 1;
await Promise.resolve();
}),
f.transact(async tx => {
tx.account.cash = -1;
throw new Error('rollback');
}),
f.transact(async tx => {
tx.account.cash -= 2;
}),
]);
expect(results.map(result => result.status)).toEqual(['fulfilled', 'rejected', 'fulfilled']);
expect(await f.transact(async tx => tx.account.cash)).toBe(9997);
});
test('pending indexes reflect staged updates, and rollback preserves their previous heads', async () => {
const f = await fixture();
await f.transact(async tx => {
await tx.putOrder(order);
await tx.putInput(input);
await tx.putInput({ ...input, id: '2', sequence: 2 });
await tx.putIntent(intent);
await tx.putIntent({
...intent,
clientOrderId: 'next',
sequence: 2,
request: { ...request, clientOrderId: 'next' },
});
});
const drain = async (tx: ExecutionTransaction) => {
await tx.putOrder({ ...order, report: { ...order.report, status: 'filled' } });
await tx.putInput({ ...input, status: 'applied' });
await tx.putIntent({ ...intent, status: 'dispatched' });
expect(await tx.openOrders()).toEqual([]);
expect((await tx.nextInput())?.id).toBe('2');
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
};
await expect(
f.transact(async tx => {
await drain(tx);
throw new Error('rollback');
})
).rejects.toThrow('rollback');
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([order]);
expect(await tx.nextInput()).toEqual(input);
expect(await tx.nextIntent()).toEqual(intent);
await drain(tx);
});
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([]);
expect((await tx.nextInput())?.id).toBe('2');
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
});
});
test('journal lookup supports nonzero sequences, gaps at the cursor and staged appends', async () => {
const f = await fixture({ ...initial, strategySequence: 20 });
await f.transact(async tx => {
await tx.appendJournal(journal);
await tx.appendJournal(journal);
});
await f.transact(async tx => {
await tx.appendJournal(journal);
for (const [cursor, expected] of [
[-1, 21],
[20, 21],
[21, 22],
[22, 23],
[23, undefined],
[100, undefined],
]) {
expect((await tx.nextJournal(cursor!))?.sequence).toBe(expected);
}
});
});
test('sequence exhaustion cannot commit a partial journal or account change', async () => {
const f = await fixture({ ...initial, strategySequence: Number.MAX_SAFE_INTEGER });
await expect(
f.transact(async tx => {
tx.account.cash = 1;
await tx.appendJournal(journal);
})
).rejects.toThrow('exhausted');
expect(await f.transact(async tx => tx.account.cash)).toBe(10000);
});
test('pending-intent ties use deterministic sequence, strategy and client ID order', async () => {
const f = await fixture();
await f.transact(async tx => {
for (const [strategyId, clientOrderId, sequence] of [
['b', '1', 1],
['a', '2', 1],
['a', '10', 1],
['0', '0', 2],
] as const) {
await tx.putIntent({
...intent,
strategyId,
clientOrderId,
sequence,
request: { ...request, clientOrderId },
});
}
});
for (const expected of ['10', '2', '1', '0']) {
await f.transact(async tx => {
const next = (await tx.nextIntent())!;
expect(next.clientOrderId).toBe(expected);
await tx.putIntent({ ...next, status: 'dispatched' });
});
}
expect(await f.transact(tx => tx.nextIntent())).toBeUndefined();
});
test('duplicate financial identities are indexed safely, including special JavaScript keys', async () => {
const f = await fixture();
await f.transact(async tx => {
await tx.putOrder(order);
expect(await tx.findOrder('__proto__')).toEqual(order);
expect(await tx.insertFill('order', fill)).toBe(true);
expect(await tx.insertFill('order', fill)).toBe(false);
expect(await tx.recordEvent('constructor', 'hash')).toBe(true);
expect(await tx.recordEvent('constructor', 'hash')).toBe(false);
});
await expect(
f.transact(tx => tx.putOrder({ ...order, report: { ...order.report, orderId: 'duplicate' } }))
).rejects.toThrow('already exists');
await expect(f.transact(tx => tx.recordEvent('constructor', 'different'))).rejects.toThrow(
'Conflicting'
);
expect(await f.transact(tx => tx.insertFill('order', fill))).toBe(false);
});
});

View file

@ -216,11 +216,8 @@ describe('one simulation execution gateway', () => {
{} as ModeManager,
execution
);
await strategy.initialize();
await strategy.start();
// Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real.
Object.defineProperty(manager, 'strategies', { value: new Map([['strategy', strategy]]) });
Object.defineProperty(manager, 'activeStrategies', { value: new Set(['strategy']) });
await manager.attachStrategy(strategy);
cleanup.push(() => manager.shutdown());
const first = quote('1');
const second = quote('2', 100, 100, start + 1);

View file

@ -0,0 +1,192 @@
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<void>)[] = [];
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);
});
});

View file

@ -0,0 +1,110 @@
import { afterEach, describe, expect, test } from 'bun:test';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
import { config, logger, makeExecution, quote } from '../fixtures/execution';
import { CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture() {
const { execution, engine } = makeExecution();
await execution.initialize(config, engine);
cleanup.push(() => execution.shutdown());
const modeManager = { getTradingEngine: () => engine } as ModeManager;
return {
execution,
dependencies: { modeManager, execution },
services: { logger, custom: { ModeManager: modeManager, ExecutionService: execution } },
};
}
describe('strategy registration and expansion', () => {
test('custom lazy factories integrate with ordinary initialization, recovery and restart', async () => {
const f = await fixture();
let created = 0;
const registry = new StrategyRegistry().register(
['fixture', 'custom-alias'],
(config, dependencies) => {
created++;
expect(dependencies.execution).toBe(f.execution);
return new CounterStrategy(dependencies.execution, config);
}
);
expect(created).toBe(0);
const manager = new StrategyManager(f.services, registry);
cleanup.push(() => manager.shutdown());
await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]);
await manager.onMarketData(quote('first'));
expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1);
await manager.shutdown();
const restarted = new StrategyManager(f.services, registry);
cleanup.push(() => restarted.shutdown());
await restarted.restoreStrategies();
expect(created).toBe(2);
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1);
await restarted.onMarketData(quote('second'));
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2);
});
test('aliases are normalized and registration conflicts fail atomically', async () => {
const f = await fixture();
const registry = new StrategyRegistry().register(
['fixture'],
config => new CounterStrategy(f.execution, config)
);
const factory = () => new CounterStrategy(f.execution);
expect(() => registry.register(['new', 'FIXTURE'], factory)).toThrow('already registered');
await expect(
registry.create({ ...recoveryConfig, name: 'new' }, f.dependencies)
).rejects.toThrow('Unknown strategy');
for (const aliases of [[], [''], [' '], ['duplicate', 'DUPLICATE']]) {
expect(() => registry.register(aliases, factory)).toThrow('nonempty and distinct');
}
expect(
(await registry.create({ ...recoveryConfig, name: ' FIXTURE ' }, f.dependencies)).getConfig()
.id
).toBe('counter');
});
test('built-in aliases keep their implementations and unknown names fail closed', async () => {
const f = await fixture();
const registry = createBuiltinStrategyRegistry();
for (const name of ['meanreversion', 'mean-reversion']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBe('mean-reversion/v1');
}
for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBe('sma-crossover-fixed/v1');
}
for (const name of ['mlenhanced', 'ml-enhanced']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBeUndefined();
}
await expect(
registry.create({ ...recoveryConfig, name: 'missing' }, f.dependencies)
).rejects.toThrow('Unknown strategy: missing');
});
test('factory failures propagate before an invalid strategy can be activated', async () => {
const f = await fixture();
const registry = new StrategyRegistry().register(['fixture'], async () => {
throw new Error('factory failed');
});
const manager = new StrategyManager(f.services, registry);
cleanup.push(() => manager.shutdown());
await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed');
expect(manager.getActiveStrategies()).toEqual([]);
expect(await f.execution.registeredStrategies()).toEqual([]);
});
});