Freeze historical datasets and qualify backtest instrument identities

This commit is contained in:
Boki 2026-10-20 23:59:15 -04:00
parent 63c3856797
commit d6b09eb635
43 changed files with 2249 additions and 1230 deletions

View file

@ -25,6 +25,7 @@ import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/back
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
import {
@ -45,7 +46,7 @@ const config = BacktestConfigSchema.parse({
mode: 'backtest',
name: 'Workflow fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE'],
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
@ -75,11 +76,12 @@ async function fixture(
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0,
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0, dataset_hash text,
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
CREATE TABLE backtest_datasets (hash text PRIMARY KEY, payload jsonb, created_at timestamptz DEFAULT NOW());
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric, configuration jsonb, engine text);`);
@ -141,6 +143,49 @@ async function fixture(
}
describe('one backtest execution workflow', () => {
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
const f = await fixture();
const api = createBacktestV2Routes(f.services);
for (const request of [
{ ...config, symbols: ['FIXTURE'] },
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
{ ...config, config: { datasetHash: 'invalid' } },
]) {
const response = await api.request('/api/v2/backtests', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
expect(response.status).toBe(400);
}
expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0);
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0);
});
test('frozen inputs replay without reading mutable provider history and are recorded in results', async () => {
const f = await fixture();
const first = await f.runner.runBacktest(config);
expect(first.config.dataset?.barCount).toBe(70);
expect(first.config.dataset?.hash).toMatch(/^[a-f0-9]{64}$/);
const saved = await f.postgres.query('SELECT dataset_hash FROM runs WHERE id = $1', [
first.runId,
]);
expect(saved.rows[0]?.dataset_hash).toBe(first.config.dataset!.hash);
f.storage.getHistoricalBars = async () => {
throw new Error('Provider unavailable or revised');
};
const replay = await f.runner.runBacktest({
...config,
datasetHash: first.config.dataset!.hash,
});
expect(replay.config.dataset).toEqual(first.config.dataset);
expect(replay.trades).toEqual(first.trades);
expect(replay.metrics).toEqual(first.metrics);
expect(replay.equity).toEqual(first.equity);
expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
await expect(f.runner.runBacktest({ ...config, datasetHash: 'f'.repeat(64) })).rejects.toThrow(
'not found'
);
});
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
const f = await fixture();
const response = await f.routes.request('/api/backtest/run', {
@ -208,10 +253,17 @@ describe('one backtest execution workflow', () => {
expect(result.engine).toBe('typescript');
expect(result.trades.length).toBeGreaterThan(0);
expect(result.status).toBe('completed');
const repeated = await services.custom!.BacktestRunner!.runBacktest(config);
services.custom!.StorageService!.getHistoricalBars = async () => {
throw new Error('Provider unavailable');
};
const repeated = await services.custom!.BacktestRunner!.runBacktest({
...config,
datasetHash: result.config.dataset!.hash,
});
expect(repeated.config.dataset).toEqual(result.config.dataset);
expect(repeated.trades).toEqual(result.trades);
expect(repeated.metrics).toEqual(result.metrics);
expect(result.ohlcData.FIXTURE).toHaveLength(70);
expect(result.ohlcData['FIXTURE.TEST']).toHaveLength(70);
expect(result.trades.every(trade => trade.kind === 'closed')).toBe(true);
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
} finally {
@ -262,7 +314,7 @@ describe('one backtest execution workflow', () => {
const f = await fixture(true);
await expect(
new DataManager(f.storage).loadHistoricalData(
['FIXTURE'],
['FIXTURE.TEST'],
new Date(config.startDate),
new Date(config.endDate),
'1d'
@ -318,7 +370,10 @@ describe('one backtest execution workflow', () => {
if (sql.includes('INSERT INTO backtest_results')) {
throw new Error('Insert failed');
}
return { rows: [{ id: result.runId }], rowCount: 1 };
return {
rows: [{ id: result.runId, dataset_hash: result.config.dataset?.hash }],
rowCount: 1,
};
},
release() {
released = true;