334 lines
11 KiB
TypeScript
334 lines
11 KiB
TypeScript
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);
|
|
});
|
|
});
|