fix(engine): validate native market data atomically

This commit is contained in:
Boki 2026-10-22 14:50:24 -04:00
parent 6d357af983
commit ee670a3bd1
2 changed files with 266 additions and 35 deletions

View file

@ -0,0 +1,172 @@
import { describe, expect, test } from 'bun:test';
import { BacktestEngine } from '@stock-bot/engine';
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
function engine() {
return new BacktestEngine({
name: 'Native data admission',
symbols: ['A.US', 'B.US'],
startDate: new Date(0).toISOString(),
endDate: new Date(4_000).toISOString(),
initialCapital: 100,
commission: 0,
slippage: 0,
dataFrequency: '1m',
});
}
function bar(timestamp = 1_001, price = 10): Record<string, unknown> {
return {
symbol: 'A.US',
timestamp,
type: 'bar',
open: price,
high: price,
low: price,
close: price,
volume: 1_000,
vwap: price,
};
}
describe('native market-data admission', () => {
test('retains distinct millisecond timestamps in replay order', () => {
const subject = engine();
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
[1_001, 10],
[1_999, 11],
]);
expect(result.equity.map(row => Date.parse(row.date))).toEqual([0, 1_001, 1_999]);
});
const invalidFields: Array<[string, unknown]> = [
['open', Number.NaN],
['open', 0],
['open', -1],
['high', Number.POSITIVE_INFINITY],
['high', 9],
['low', Number.NEGATIVE_INFINITY],
['low', 11],
['close', Number.NaN],
['close', '10'],
['volume', -1],
['volume', Number.NaN],
['volume', Number.POSITIVE_INFINITY],
['vwap', Number.NaN],
['vwap', Number.POSITIVE_INFINITY],
['vwap', 0],
['vwap', -1],
['vwap', '10'],
['timestamp', Number.NaN],
['timestamp', Number.POSITIVE_INFINITY],
['timestamp', 1_500.5],
['timestamp', Number.MAX_SAFE_INTEGER + 1],
['timestamp', Number.MAX_SAFE_INTEGER],
['timestamp', '1500'],
['type', 'quote'],
['symbol', ' '],
];
for (const [field, value] of invalidFields) {
test(`rejects invalid ${field}=${String(value)} with the zero-based row index`, () => {
const subject = engine();
expect(() =>
subject.loadMarketData([bar(500), { ...bar(1_500), [field]: value }, bar(2_500)])
).toThrow(/Market data row 1:/);
});
}
for (const field of ['symbol', 'timestamp', 'type', 'open', 'high', 'low', 'close', 'volume']) {
test(`rejects missing ${field} with the zero-based row index`, () => {
const subject = engine();
const incomplete = bar(1_500);
delete incomplete[field];
expect(() => subject.loadMarketData([bar(500), incomplete, bar(2_500)])).toThrow(
/Market data row 1:/
);
});
}
for (const value of [null, undefined, 1, 'bar', []]) {
test(`rejects a non-record row (${String(value)}) with its index`, () => {
const subject = engine();
expect(() => subject.loadMarketData([bar(500), value as object, bar(2_500)])).toThrow(
/Market data row 1:/
);
});
}
test('a malformed replacement preserves all previously admitted data', () => {
const subject = engine();
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
expect(() =>
subject.loadMarketData([bar(500, 20), { ...bar(1_500, 30), low: 31 }, bar(2_500, 40)])
).toThrow(/Market data row 1:/);
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
[1_001, 10],
[1_999, 11],
]);
});
test('an invalid first load does not admit its valid neighboring rows', () => {
const subject = engine();
expect(() =>
subject.loadMarketData([bar(500), { ...bar(1_500), close: Number.NaN }, bar(2_500)])
).toThrow(/Market data row 1:/);
expect(() => subject.run()).toThrow('No market data loaded');
});
test('a valid replacement after a rejected load succeeds without stale rows', () => {
const subject = engine();
subject.loadMarketData([bar(500)]);
expect(() => subject.loadMarketData([{ ...bar(1_001), type: 'quote' }])).toThrow(
/Market data row 0: Unsupported market data type: quote/
);
subject.loadMarketData([bar(1_999, 11)]);
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([[1_999, 11]]);
});
for (const conflicting of [false, true]) {
test(`rejects ${conflicting ? 'conflicting' : 'identical'} duplicates without replacing good data`, () => {
const subject = engine();
subject.loadMarketData([bar(1_001)]);
expect(() => subject.loadMarketData([bar(1_500), bar(1_500, conflicting ? 11 : 10)])).toThrow(
/Market data row 1: Duplicate bar identity A\.US at 1500ms \(first at row 0\)/
);
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
expect(result.ohlcData['A.US']?.map(row => row.timestamp)).toEqual([1_001]);
});
}
test('rejects decreasing timestamps instead of relying on an invalid historical seek order', () => {
const subject = engine();
expect(() => subject.loadMarketData([bar(1_999), bar(1_001)])).toThrow(
/Market data row 1: Timestamps must be nondecreasing/
);
});
test('accepts distinct same-time symbols, zero volume and optional absent VWAP', () => {
const subject = engine();
const withoutVwap = { ...bar(1_001), volume: 0 };
delete withoutVwap.vwap;
subject.loadMarketData([
{ ...bar(1_001), symbol: 'B.US', vwap: null },
withoutVwap,
{ ...bar(1_999), vwap: undefined },
]);
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
expect(result.ohlcData['A.US']).toHaveLength(2);
expect(result.ohlcData['B.US']).toHaveLength(1);
expect(result.ohlcData['A.US']?.[0]?.volume).toBe(0);
});
test('rejects loading into a consumed engine explicitly', () => {
const subject = engine();
subject.loadMarketData([bar()]);
subject.run();
expect(() => subject.loadMarketData([bar()])).toThrow('Engine already consumed');
});
});