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

56
test/fixtures/strategy-crash-owner.ts vendored Normal file
View file

@ -0,0 +1,56 @@
/** Disposable process used only against an isolated stock_bot_safety schema. */
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { logger, makeExecution, start } from './execution';
import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery';
const url = process.env.PIPELINE_TEST_DATABASE_URL,
schema = process.env.STRATEGY_FIXTURE_SCHEMA,
phase = process.env.STRATEGY_FIXTURE_PHASE;
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
!schema ||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
!['decision', 'checkpoint', 'dispatch'].includes(phase ?? '')
) {
throw new Error('Unsafe strategy crash fixture');
}
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const repository = new FaultRepository(new PostgresExecutionRepository(postgres));
const { execution, engine } = makeExecution(repository, () => start + 100);
await execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
},
engine
);
const blocked = async () => {
process.send?.({ phase });
await new Promise<void>(() => {});
};
const strategy = new CounterStrategy(execution);
if (phase === 'decision') {
strategy.onDecision = blocked;
} else {
repository.fault = {
method: 'putIntent',
stage: 'commit',
matches: value =>
(value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'),
hook: blocked,
};
}
await attachCounter(execution, strategy);
throw new Error('Crash fixture did not reach its requested boundary');

126
test/fixtures/strategy-recovery.ts vendored Normal file
View file

@ -0,0 +1,126 @@
import { z } from 'zod';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import type {
ExecutionRepository,
ExecutionTransaction,
} from '../../apps/stock/orchestrator/src/execution/repository';
import type {
ExecutionService,
StrategyFill,
} from '../../apps/stock/orchestrator/src/services/ExecutionService';
import {
BaseStrategy,
type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
import { logger } from './execution';
export const recoveryConfig: StrategyConfig = {
id: 'counter',
name: 'fixture',
symbols: ['A'],
parameters: {},
allocation: 1,
enabled: true,
};
export class CounterStrategy extends BaseStrategy {
count = 0;
equities: number[] = [];
failDecision = false;
failFill = false;
onDecision?: () => Promise<void>;
version = 'counter/v1';
constructor(execution: ExecutionService, config = recoveryConfig) {
super(config, {} as ModeManager, execution);
}
override getCheckpointVersion() {
return this.version;
}
protected override captureIndicators() {
return { count: this.count, equities: this.equities };
}
protected override restoreIndicators(input: unknown) {
const state = z
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
.parse(input);
this.count = state.count;
this.equities = state.equities;
}
protected updateIndicators() {
this.count++;
}
protected async generateSignal(data: MarketData): Promise<Signal | null> {
this.equities.push((await this.executionService.getAccount()).equity);
await this.onDecision?.();
if (this.failDecision) {
throw new Error('injected decision failure');
}
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
}
override async onFill(fill: StrategyFill) {
await super.onFill(fill);
if (this.failFill) {
throw new Error('injected fill callback failure');
}
}
}
export async function attachCounter(
execution: ExecutionService,
strategy = new CounterStrategy(execution)
) {
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } });
await manager.attachStrategy(strategy);
return { manager, strategy };
}
export class FaultRepository implements ExecutionRepository {
fault?: {
method: keyof ExecutionTransaction;
matches: (argument: unknown) => boolean;
stage: 'before' | 'after' | 'commit';
hook?: () => Promise<void>;
};
constructor(private readonly delegate: ExecutionRepository) {}
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
return this.delegate.initialize(...args);
}
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
let matched: typeof this.fault;
const result = await this.delegate.transact(account, tx =>
work(
new Proxy(tx, {
get: (target, key: keyof ExecutionTransaction) => {
const value = target[key];
if (typeof value !== 'function') {
return value;
}
return async (...args: unknown[]) => {
const fault = this.fault;
const hit = fault && key === fault.method && fault.matches(args[0]);
if (hit) {
this.fault = undefined;
matched = fault;
}
if (hit && fault.stage === 'before') {
throw new Error('injected transaction failure');
}
const answer = await Reflect.apply(value, target, args);
if (hit && fault.stage === 'after') {
throw new Error('injected transaction failure');
}
return answer;
};
},
})
)
);
if (matched?.stage === 'commit') {
if (matched.hook) {
await matched.hook();
}
throw new Error('injected lost commit acknowledgement');
}
return result;
}
}

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([]);
});
});

View file

@ -30,6 +30,12 @@ async function fixture() {
);
await pool.query(sql);
await pool.query(sql);
await pool.query(
readFileSync(
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
'utf8'
)
);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger

View file

@ -0,0 +1,369 @@
import { fork } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { logger, makeExecution, quote, start } from '../fixtures/execution';
import { attachCounter, CounterStrategy, recoveryConfig } 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();
}
});
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();
});
for (const migration of ['11-simulation-execution-ledger.sql', '13-strategy-recovery.sql']) {
await pool.query(
readFileSync(new URL('../../database/postgres/init/' + migration, 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) });
let now = start + 100;
const make = async (
accountId = 'fixture',
repository: ExecutionRepository = new PostgresExecutionRepository(postgres)
) => {
const runtime = makeExecution(repository, () => now);
await runtime.execution.initialize(
{
mode: 'paper',
accountId,
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
},
runtime.engine
);
cleanup.push(() => runtime.execution.shutdown());
return runtime;
};
return {
pool,
postgres,
schema,
make,
setTime: (time: number) => {
now = time;
},
getTime: () => now,
};
}
describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
test('paper mode restores registered strategies and drains their inbox before starting the feed', async () => {
const f = await fixture();
const original = await f.make();
const config = {
...recoveryConfig,
id: 'sma',
name: 'sma-crossover',
parameters: { initialCapital: 10000 },
};
const prior = new StrategyManager({
logger,
custom: {
ExecutionService: original.execution,
ModeManager: { getTradingEngine: () => original.engine } as ModeManager,
},
});
await prior.initializeStrategies([config]);
await prior.onMarketData(quote('one'));
await prior.shutdown();
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1));
const services: OrchestratorServices = { logger, postgres: f.postgres, custom: {} };
const storage = new StorageService(services, null, f.postgres, null);
const execution = new ExecutionService(services, storage, { clock: f.getTime });
let feedStarted = false;
class OfflineMarket extends MarketDataService {
override async initialize() {
feedStarted = true;
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(false);
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
}
}
const market = new OfflineMarket(services);
const manager = new StrategyManager(services),
mode = new ModeManager(services, market, execution, storage);
Object.assign(services.custom!, {
StorageService: storage,
ExecutionService: execution,
MarketDataService: market,
StrategyManager: manager,
ModeManager: mode,
});
cleanup.push(() => mode.shutdown());
await mode.initializeMode({
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
});
expect(feedStarted).toBe(true);
expect(manager.getActiveStrategies()).toEqual(['sma']);
});
test.each(['decision', 'checkpoint', 'dispatch'] as const)(
'hard kill at %s resumes without skipped decisions or duplicate fills',
async phase => {
const f = await fixture();
const { execution } = await f.make();
const initial = await attachCounter(execution);
await initial.manager.shutdown();
await execution.enqueueMarketData(quote('one'));
const child = fork(
fileURLToPath(new URL('../fixtures/strategy-crash-owner.ts', import.meta.url)),
[],
{
execPath: process.execPath,
execArgv: [],
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
env: { ...process.env, STRATEGY_FIXTURE_SCHEMA: f.schema, STRATEGY_FIXTURE_PHASE: phase },
}
);
const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
cleanup.push(async () => {
child.kill('SIGKILL');
await exited;
});
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Crash fixture boundary timeout')), 5000);
child.once('message', message => {
clearTimeout(timeout);
if ((message as { phase: string }).phase === phase) {
resolve();
} else {
reject(new Error('Wrong crash boundary'));
}
});
child.once('exit', () => {
clearTimeout(timeout);
reject(new Error('Crash fixture exited before its boundary'));
});
});
child.kill('SIGKILL');
await exited;
const restarted = await f.make();
const resumed = await attachCounter(restarted.execution);
cleanup.push(() => resumed.manager.shutdown());
expect(resumed.strategy.count).toBe(1);
expect(resumed.strategy.getPosition('A')).toBe(1);
expect(resumed.strategy.getPerformance().trades).toBe(1);
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
await resumed.manager.onMarketData(quote('one'));
expect(resumed.strategy.count).toBe(1);
expect((await restarted.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
}
);
test('checkpoint and order-intent SQL writes roll back together on an injected trigger failure', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager, strategy } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await f.pool
.query(`CREATE FUNCTION reject_intent() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent failure'; END $$;
CREATE TRIGGER reject_intent BEFORE INSERT ON simulation_strategy_intents FOR EACH ROW EXECUTE FUNCTION reject_intent()`);
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('intent failure');
expect(strategy.count).toBe(0);
expect(
(await f.pool.query('SELECT payload FROM simulation_strategy_checkpoints')).rows[0].payload
.cursor
).toBe(0);
expect((await f.pool.query('SELECT * FROM simulation_strategy_intents')).rows).toHaveLength(0);
await f.pool.query('DROP TRIGGER reject_intent ON simulation_strategy_intents');
await manager.recover();
expect(strategy.count).toBe(1);
expect(strategy.getPosition('A')).toBe(1);
});
test('input admission survives a rollback before quote application and journal creation', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await f.pool
.query(`CREATE FUNCTION reject_input_apply() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected application failure'; END $$;
CREATE TRIGGER reject_input_apply BEFORE UPDATE ON simulation_market_inputs FOR EACH ROW EXECUTE FUNCTION reject_input_apply()`);
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('application failure');
expect((await execution.getAccount()).quotes.A).toBeUndefined();
expect((await f.pool.query('SELECT * FROM simulation_strategy_journal')).rows).toHaveLength(0);
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(true);
await manager.shutdown();
await f.pool.query('DROP TRIGGER reject_input_apply ON simulation_market_inputs');
const restarted = await f.make();
const resumed = await attachCounter(restarted.execution);
cleanup.push(() => resumed.manager.shutdown());
expect(resumed.strategy.count).toBe(1);
expect(resumed.strategy.getPosition('A')).toBe(1);
});
test('competing owners restore the locked checkpoint before every decision and consume one intent', async () => {
const f = await fixture();
const one = await f.make(),
two = await f.make();
const first = await attachCounter(one.execution),
second = await attachCounter(two.execution);
cleanup.push(
() => first.manager.shutdown(),
() => second.manager.shutdown()
);
await one.execution.enqueueMarketData(quote('one'));
await Promise.all([first.manager.recover(), second.manager.recover()]);
await Promise.all([first.manager.recover(), second.manager.recover()]);
expect(first.strategy.count).toBe(1);
expect(second.strategy.count).toBe(1);
expect(first.strategy.getPosition('A')).toBe(1);
expect(second.strategy.getPosition('A')).toBe(1);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
});
test('stale admitted inputs restore indicators but never fabricate stale paper fills', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager, strategy } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await execution.enqueueMarketData(quote('one'));
f.setTime(start + 5000);
await manager.recover();
expect(strategy.count).toBe(1);
expect(strategy.getPosition('A')).toBe(0);
const orders = (await f.pool.query('SELECT payload FROM simulation_orders')).rows;
expect(orders[0].payload.report.status).toBe('rejected');
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0);
});
test('real SMA indicator checkpoints reproduce an uninterrupted run across process replacement', async () => {
const f = await fixture();
const smaConfig = {
...recoveryConfig,
id: 'sma',
name: 'sma-crossover',
parameters: { initialCapital: 10000 },
};
const makeManager = async (account: string) => {
const runtime = await f.make(account);
const services = {
logger,
custom: {
ExecutionService: runtime.execution,
ModeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
},
};
const manager = new StrategyManager(services);
await manager.initializeStrategies([smaConfig]);
cleanup.push(() => manager.shutdown());
return { ...runtime, manager };
};
const bars = Array.from({ length: 45 }, (_, index) => {
const price = 100 + Math.sin(index / 3) * 8;
return {
type: 'bar' as const,
eventId: 'bar-' + index,
data: {
symbol: 'A',
timestamp: start + index * 86400000,
open: price,
high: price + 1,
low: price - 1,
close: price,
volume: 100000,
},
};
});
const baseline = await makeManager('baseline');
for (const bar of bars) {
f.setTime(bar.data.timestamp);
await baseline.manager.onMarketData(bar);
}
f.setTime(start);
const interrupted = await makeManager('interrupted');
for (const bar of bars.slice(0, 22)) {
f.setTime(bar.data.timestamp);
await interrupted.manager.onMarketData(bar);
}
await interrupted.manager.shutdown();
const restarted = await makeManager('interrupted');
for (const bar of bars.slice(22)) {
f.setTime(bar.data.timestamp);
await restarted.manager.onMarketData(bar);
}
const meaningfulState = (manager: StrategyManager) => {
const {
seenFills: _seenFills,
pendingOrders: _pendingOrders,
...state
} = manager.getStrategy('sma')!.captureCheckpoint() as Record<string, unknown>;
return state;
};
expect(meaningfulState(restarted.manager)).toEqual(meaningfulState(baseline.manager));
expect((await restarted.execution.getAccount()).cash).toBe(
(await baseline.execution.getAccount()).cash
);
expect(
(await f.pool.query("SELECT * FROM simulation_fills WHERE account_id = 'baseline'")).rows
.length
).toBeGreaterThan(0);
});
test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
const f = await fixture();
const { execution, engine } = await f.make();
const manager = new StrategyManager({
logger,
custom: {
ExecutionService: execution,
ModeManager: { getTradingEngine: () => engine } as ModeManager,
},
});
cleanup.push(() => manager.shutdown());
await expect(
manager.initializeStrategies([{ ...recoveryConfig, name: 'ml-enhanced' }])
).rejects.toThrow('versioned checkpoint');
expect((await f.pool.query('SELECT * FROM simulation_strategy_checkpoints')).rows).toHaveLength(
0
);
const active = await attachCounter(execution);
cleanup.push(() => active.manager.shutdown());
await active.manager.onMarketData(quote('one'));
await f.pool.query(
readFileSync(
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
'utf8'
)
);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
});
});