351 lines
11 KiB
TypeScript
351 lines
11 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { setImmediate } from 'node:timers/promises';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
|
import { parseInstrumentId, type HistoricalDataset } from '@stock-bot/types';
|
|
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
|
import { datasetSchema } from '../../apps/stock/orchestrator/src/contracts/historical';
|
|
import {
|
|
loadDataset,
|
|
prepareDataset,
|
|
resolveDataset,
|
|
validateDataset,
|
|
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
|
import {
|
|
StorageService,
|
|
type HistoricalBar,
|
|
} from '../../apps/stock/orchestrator/src/services/StorageService';
|
|
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
|
import { logger } from '../fixtures/execution';
|
|
|
|
const config = BacktestConfigSchema.parse({
|
|
mode: 'backtest',
|
|
strategy: 'sma-crossover',
|
|
symbols: ['A.US', 'B.US'],
|
|
startDate: '2024-01-01T00:00:00.000Z',
|
|
endDate: '2025-01-01T00:00:00.000Z',
|
|
initialCapital: 10000,
|
|
dataFrequency: '1m',
|
|
speed: 'max',
|
|
});
|
|
const start = Date.parse(config.startDate);
|
|
|
|
function rows(symbol: string, count = 3): HistoricalBar[] {
|
|
return Array.from({ length: count }, (_, i) => ({
|
|
symbol,
|
|
source: 'questdb',
|
|
timestamp: new Date(start + i * 60_000),
|
|
open: 100,
|
|
high: 102,
|
|
low: 99,
|
|
close: 100.25,
|
|
volume: i,
|
|
vwap: 100.125,
|
|
}));
|
|
}
|
|
|
|
/** Independent pre-refactor v1 construction: whole-schema parse and whole-string SHA-256. */
|
|
function legacyFixture(count = 3): HistoricalDataset {
|
|
const bars = config.symbols
|
|
.flatMap(symbol =>
|
|
rows(symbol, count).map(bar => ({
|
|
symbol,
|
|
timestamp: bar.timestamp.getTime(),
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
vwap: bar.vwap,
|
|
}))
|
|
)
|
|
.sort((a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : 1));
|
|
const dataset = datasetSchema.parse({
|
|
manifest: {
|
|
version: 1,
|
|
hash: '0'.repeat(64),
|
|
instruments: config.symbols.map(parseInstrumentId),
|
|
startDate: config.startDate,
|
|
endDate: config.endDate,
|
|
interval: config.dataFrequency,
|
|
policy: { adjustment: 'raw', timestamp: 'utc-instant' },
|
|
volumePolicy: 'reported',
|
|
qualityPolicy: 'reject-invalid-no-interpolation',
|
|
sources: config.symbols.map(instrumentId => ({
|
|
instrumentId,
|
|
provider: 'questdb',
|
|
revision: 'historical-normalization-v1',
|
|
})),
|
|
barCount: bars.length,
|
|
},
|
|
bars,
|
|
});
|
|
const { hash: _hash, ...manifest } = dataset.manifest;
|
|
dataset.manifest.hash = createHash('sha256')
|
|
.update(JSON.stringify({ manifest, bars: dataset.bars }))
|
|
.digest('hex');
|
|
return dataset;
|
|
}
|
|
|
|
describe('historical dataset preparation', () => {
|
|
test('preserves v1 whole-JSON hashes and canonical key ordering, including Unicode metadata', async () => {
|
|
const expected = legacyFixture();
|
|
const loaded = await loadDataset(
|
|
{
|
|
async getHistoricalBars(symbol) {
|
|
return rows(symbol);
|
|
},
|
|
},
|
|
config
|
|
);
|
|
expect(loaded).toEqual(expected);
|
|
const reordered = JSON.parse(JSON.stringify(expected), (_key, value) =>
|
|
value && typeof value === 'object' && !Array.isArray(value)
|
|
? Object.fromEntries(Object.entries(value).reverse())
|
|
: value
|
|
);
|
|
expect(await prepareDataset(reordered, config)).toEqual(expected);
|
|
expected.manifest.sources[0]!.revision = 'révision-市場';
|
|
const { hash: _hash, ...manifest } = expected.manifest;
|
|
expected.manifest.hash = createHash('sha256')
|
|
.update(JSON.stringify({ manifest, bars: expected.bars }))
|
|
.digest('hex');
|
|
const result = validateDataset(expected, config);
|
|
expect(result.manifest.hash).toBe(expected.manifest.hash);
|
|
});
|
|
|
|
test('only deeply immutable detached preparations are reused; mutable inputs are always rechecked', async () => {
|
|
const input = legacyFixture();
|
|
const dataset = await prepareDataset(input, config);
|
|
expect(dataset).not.toBe(input);
|
|
expect(validateDataset(dataset, config)).toBe(dataset);
|
|
expect(
|
|
await resolveDataset(
|
|
{
|
|
getHistoricalBars: async () => {
|
|
throw new Error('must not load');
|
|
},
|
|
},
|
|
config,
|
|
async () => dataset
|
|
)
|
|
).toBe(dataset);
|
|
for (const value of [
|
|
dataset,
|
|
dataset.bars,
|
|
dataset.bars[0],
|
|
dataset.manifest,
|
|
dataset.manifest.policy,
|
|
dataset.manifest.instruments,
|
|
dataset.manifest.instruments[0],
|
|
dataset.manifest.sources,
|
|
dataset.manifest.sources[0],
|
|
]) {
|
|
expect(Object.isFrozen(value)).toBe(true);
|
|
}
|
|
expect(() => {
|
|
dataset.bars[0]!.close = 101;
|
|
}).toThrow();
|
|
expect(() => {
|
|
dataset.manifest.policy.adjustment = 'provider-adjusted';
|
|
}).toThrow();
|
|
input.bars[0]!.volume++;
|
|
expect(() => validateDataset(input)).toThrow('hash/content');
|
|
expect(dataset.bars[0]?.volume).toBe(0);
|
|
});
|
|
|
|
test('cached preparations still enforce request identity', async () => {
|
|
const dataset = await prepareDataset(legacyFixture());
|
|
expect(() => validateDataset(dataset, { ...config, symbols: ['A.US'] })).toThrow(
|
|
'does not match'
|
|
);
|
|
expect(() => validateDataset(dataset, { ...config, datasetHash: 'f'.repeat(64) })).toThrow(
|
|
'does not match'
|
|
);
|
|
});
|
|
|
|
test('all requested instruments and bars are retained without a listing ceiling', async () => {
|
|
const request = { ...config, symbols: Array.from({ length: 101 }, (_, i) => `S${i}.US`) };
|
|
const loaded = await loadDataset(
|
|
{
|
|
async getHistoricalBars(symbol) {
|
|
return rows(symbol);
|
|
},
|
|
},
|
|
request
|
|
);
|
|
expect(loaded.manifest.instruments).toHaveLength(101);
|
|
expect(loaded.bars).toHaveLength(303);
|
|
expect(loaded.manifest.barCount).toBe(303);
|
|
expect(await prepareDataset(structuredClone(loaded), request)).toEqual(loaded);
|
|
});
|
|
|
|
test('resolver and storage reads receive the same cancellation signal directly', async () => {
|
|
const controller = new AbortController();
|
|
const seen: string[] = [];
|
|
const storage = {
|
|
async getHistoricalBars(
|
|
symbol: string,
|
|
_start: Date,
|
|
_end: Date,
|
|
_interval?: string,
|
|
_policy?: unknown,
|
|
signal?: AbortSignal
|
|
) {
|
|
expect(signal).toBe(controller.signal);
|
|
seen.push(symbol);
|
|
return rows(symbol);
|
|
},
|
|
};
|
|
const dataset = await resolveDataset(
|
|
storage,
|
|
config,
|
|
async (load, signal) => {
|
|
expect(signal).toBe(controller.signal);
|
|
return load();
|
|
},
|
|
controller.signal
|
|
);
|
|
expect(seen).toEqual(config.symbols);
|
|
expect(dataset).toEqual(legacyFixture());
|
|
});
|
|
|
|
test('QuestDB reads the full requested range without a row cap', async () => {
|
|
const questdb = {
|
|
async query(sql: string, parameters: unknown[]) {
|
|
expect(sql).not.toContain('LIMIT');
|
|
expect(parameters).toEqual(['A.US', new Date(config.startDate), new Date(config.endDate)]);
|
|
return { rows: rows('A.US', 5) };
|
|
},
|
|
} as unknown as QuestDBClient;
|
|
const storage = new StorageService(logger, null, questdb);
|
|
expect(
|
|
await storage.getHistoricalBars(
|
|
'A.US',
|
|
new Date(config.startDate),
|
|
new Date(config.endDate),
|
|
'1m'
|
|
)
|
|
).toHaveLength(5);
|
|
});
|
|
|
|
test('Mongo reads retain their historical-field projection without a row cap', async () => {
|
|
const mongodb = {
|
|
async find(_collection: string, _filter: unknown, options: { projection: unknown }) {
|
|
expect(options).not.toHaveProperty('limit');
|
|
expect(options.projection).toHaveProperty('eodSearchCode', 1);
|
|
return Array.from({ length: 5 }, (_, i) => ({
|
|
symbol: 'A',
|
|
exchange: 'US',
|
|
eodSearchCode: 'A.US',
|
|
date: new Date(start + i * 86400000).toISOString().slice(0, 10),
|
|
open: 100,
|
|
high: 102,
|
|
low: 99,
|
|
close: 100,
|
|
volume: 1,
|
|
}));
|
|
},
|
|
} as unknown as MongoDBClient;
|
|
const storage = new StorageService(logger, mongodb, null);
|
|
const read = () =>
|
|
storage.getHistoricalBars('A.US', new Date(config.startDate), new Date(config.endDate), '1d');
|
|
expect(await read()).toHaveLength(5);
|
|
});
|
|
|
|
test('unknown resolver values still pass the full content boundary and replay requires durability', async () => {
|
|
const storage = {
|
|
async getHistoricalBars() {
|
|
throw new Error('must not load');
|
|
},
|
|
};
|
|
const tampered = legacyFixture();
|
|
tampered.bars[0]!.volume++;
|
|
await expect(resolveDataset(storage, config, async () => tampered)).rejects.toThrow(
|
|
'hash/content'
|
|
);
|
|
await expect(
|
|
resolveDataset(storage, { ...config, datasetHash: legacyFixture().manifest.hash })
|
|
).rejects.toThrow('durable');
|
|
expect(() => validateDataset({ ...legacyFixture(), extra: 1 })).toThrow(
|
|
'Invalid historical dataset'
|
|
);
|
|
});
|
|
|
|
test('already-cancelled admission performs no reads; late database completion cannot resume preparation', async () => {
|
|
const controller = new AbortController();
|
|
const reason = new BacktestCancelledError();
|
|
let reads = 0;
|
|
let release!: (bars: HistoricalBar[]) => void;
|
|
const storage = {
|
|
async getHistoricalBars() {
|
|
reads++;
|
|
return new Promise<HistoricalBar[]>(resolve => {
|
|
release = resolve;
|
|
});
|
|
},
|
|
};
|
|
const work = loadDataset(storage, config, controller.signal);
|
|
controller.abort(reason);
|
|
release(rows('A.US'));
|
|
expect(await work.catch(error => error)).toBe(reason);
|
|
await expect(loadDataset(storage, config, controller.signal)).rejects.toBe(reason);
|
|
expect(reads).toBe(1);
|
|
});
|
|
|
|
test('CPU preparation yields to cancellation before consuming the rest of a large snapshot', async () => {
|
|
const input = legacyFixture(5000);
|
|
const controller = new AbortController();
|
|
const reason = new BacktestCancelledError();
|
|
// If cancellation did not stop the next batch, this later bar would be inspected.
|
|
Object.defineProperty(input.bars, 4096, {
|
|
get() {
|
|
throw new Error('read after cancellation');
|
|
},
|
|
});
|
|
const work = prepareDataset(input, config, controller.signal);
|
|
await setImmediate();
|
|
controller.abort(reason);
|
|
expect(await work.catch(error => error)).toBe(reason);
|
|
});
|
|
|
|
test('removing size limits does not permit invalid bars, manifests or request identities', async () => {
|
|
for (const change of [
|
|
(dataset: HistoricalDataset) => {
|
|
dataset.bars[0]!.volume = -1;
|
|
},
|
|
(dataset: HistoricalDataset) => {
|
|
dataset.bars[0]!.close = NaN;
|
|
},
|
|
(dataset: HistoricalDataset) => {
|
|
dataset.bars.reverse();
|
|
},
|
|
(dataset: HistoricalDataset) => {
|
|
dataset.manifest.barCount++;
|
|
},
|
|
(dataset: HistoricalDataset) => {
|
|
dataset.manifest.sources.pop();
|
|
},
|
|
]) {
|
|
const dataset = legacyFixture();
|
|
change(dataset);
|
|
await expect(prepareDataset(dataset)).rejects.toThrow();
|
|
}
|
|
let reads = 0;
|
|
await expect(
|
|
loadDataset(
|
|
{
|
|
async getHistoricalBars() {
|
|
reads++;
|
|
return [];
|
|
},
|
|
},
|
|
{
|
|
...config,
|
|
symbols: ['A.US', 'A.US'],
|
|
}
|
|
)
|
|
).rejects.toThrow('distinct');
|
|
expect(reads).toBe(0);
|
|
});
|
|
});
|