Freeze historical datasets and qualify backtest instrument identities
This commit is contained in:
parent
63c3856797
commit
d6b09eb635
43 changed files with 2249 additions and 1230 deletions
2
test/fixtures/execution.ts
vendored
2
test/fixtures/execution.ts
vendored
|
|
@ -15,7 +15,7 @@ export const start = Date.parse('2024-01-01T00:00:00Z');
|
|||
export const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A', 'B'],
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: '2025-01-01T00:00:00Z',
|
||||
initialCapital: 10000,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,15 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { MongoDBClient } from '@stock-bot/services';
|
||||
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||
import {
|
||||
persistEodPrices,
|
||||
type EodPrice,
|
||||
} from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import {
|
||||
loadDataset,
|
||||
validateDataset,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
|
|
@ -48,13 +52,13 @@ function memoryStore() {
|
|||
},
|
||||
async find(
|
||||
collection: string,
|
||||
filter: { symbol: string; date: { $gte: string; $lt: string } }
|
||||
filter: { eodSearchCode: string; date: { $gte: string; $lt: string } }
|
||||
) {
|
||||
expect(collection).toBe('eodPrices');
|
||||
return documents
|
||||
.filter(
|
||||
row =>
|
||||
row.symbol === filter.symbol &&
|
||||
row.eodSearchCode === filter.eodSearchCode &&
|
||||
row.date >= filter.date.$gte &&
|
||||
row.date < filter.date.$lt
|
||||
)
|
||||
|
|
@ -65,6 +69,176 @@ function memoryStore() {
|
|||
}
|
||||
|
||||
describe('deterministic ingestion → storage → native backtest', () => {
|
||||
test('intraday queries bind qualified IDs and reject timezone-less instants or wrong listings', async () => {
|
||||
let timestamp = '2024-01-01T10:00:00-05:00';
|
||||
let symbol = identity.eodSearchCode;
|
||||
const questdb = {
|
||||
async query(_sql: string, parameters: unknown[]) {
|
||||
expect(parameters[0]).toBe(identity.eodSearchCode);
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
symbol,
|
||||
timestamp,
|
||||
open: 100,
|
||||
high: 101,
|
||||
low: 99,
|
||||
close: 100,
|
||||
volume: 1000,
|
||||
vwap: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
} as unknown as QuestDBClient;
|
||||
const storage = new StorageService({ logger }, null, null, questdb);
|
||||
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m');
|
||||
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T15:00:00.000Z');
|
||||
timestamp = '2024-01-01T10:00:00';
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
|
||||
).rejects.toThrow('explicit UTC offset');
|
||||
timestamp = '2024-01-01T15:00:00Z';
|
||||
symbol = 'FIXTURE.OTHER';
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
|
||||
).rejects.toThrow('identity mismatch');
|
||||
});
|
||||
test('provider routing namespaces remain distinct from venue metadata, including legacy rows', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
const listing = { symbol: 'FIXTURE', exchange: 'NASDAQ', eodSearchCode: 'FIXTURE.US' };
|
||||
await persistEodPrices(mongodb, listing, [fixture[0]!]);
|
||||
expect(documents[0]?.exchange).toBe('NASDAQ');
|
||||
expect((documents[0] as unknown as { providerExchange: string }).providerExchange).toBe('US');
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
expect(
|
||||
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.symbol
|
||||
).toBe('FIXTURE.US');
|
||||
delete (documents[0] as unknown as { providerExchange?: string }).providerExchange;
|
||||
expect(
|
||||
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.close
|
||||
).toBe(fixture[0]!.close);
|
||||
});
|
||||
test('same ticker on different exchanges never shares bars and bare tickers fail closed', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const other = { symbol: 'FIXTURE', exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
|
||||
await persistEodPrices(mongodb, identity, [fixture[0]!]);
|
||||
await persistEodPrices(mongodb, other, [
|
||||
{ ...fixture[0]!, open: 200, high: 201, low: 199, close: 200 },
|
||||
]);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
expect(
|
||||
(await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'))[0]?.close
|
||||
).toBe(fixture[0]!.close);
|
||||
expect((await storage.getHistoricalBars(other.eodSearchCode, start, end, '1d'))[0]?.close).toBe(
|
||||
200
|
||||
);
|
||||
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
|
||||
'exchange-qualified'
|
||||
);
|
||||
expect(
|
||||
BacktestConfigSchema.safeParse({ ...datasetConfig(), symbols: ['FIXTURE'] }).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('split and dividend adjusted-close factors apply to every OHLC price, never to reported volume', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const prices = [
|
||||
{
|
||||
...fixture[0]!,
|
||||
open: 100,
|
||||
high: 110,
|
||||
low: 90,
|
||||
close: 100,
|
||||
adjusted_close: 50,
|
||||
volume: 1000,
|
||||
},
|
||||
{ ...fixture[1]!, open: 50, high: 55, low: 45, close: 50, adjusted_close: 49, volume: 2000 },
|
||||
];
|
||||
await persistEodPrices(mongodb, identity, prices);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const raw = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d');
|
||||
const adjusted = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
|
||||
adjustment: 'provider-adjusted',
|
||||
timestamp: 'utc-session-date',
|
||||
});
|
||||
expect(raw.map(b => b.close)).toEqual([100, 50]);
|
||||
expect(adjusted.map(b => [b.open, b.high, b.low, b.close, b.volume])).toEqual([
|
||||
[50, 55, 45, 50, 1000],
|
||||
[49, 53.9, 44.1, 49, 2000],
|
||||
]);
|
||||
const a = await loadDataset(storage, datasetConfig());
|
||||
const b = await loadDataset(storage, {
|
||||
...datasetConfig(),
|
||||
dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' },
|
||||
});
|
||||
expect(a.manifest.hash).not.toBe(b.manifest.hash);
|
||||
});
|
||||
|
||||
test('missing provider factors cannot silently turn adjusted requests into raw data', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, [fixture[0]!]);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
await expect(
|
||||
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
|
||||
adjustment: 'provider-adjusted',
|
||||
timestamp: 'utc-session-date',
|
||||
})
|
||||
).rejects.toThrow('unavailable');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, adjusted_close: 0 }])
|
||||
).rejects.toThrow('Invalid OHLCV');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, { ...identity, symbol: 'WRONG' }, [fixture[0]!])
|
||||
).rejects.toThrow('identity mismatch');
|
||||
});
|
||||
|
||||
test('daily timestamps are UTC session labels with aligned, exclusive ranges', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture.slice(0, 3));
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const bars = await storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
start,
|
||||
new Date(start.getTime() + 86400000),
|
||||
'1d'
|
||||
);
|
||||
expect(bars).toHaveLength(1);
|
||||
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T00:00:00.000Z');
|
||||
await expect(
|
||||
storage.getHistoricalBars(
|
||||
identity.eodSearchCode,
|
||||
new Date(start.getTime() + 3600000),
|
||||
end,
|
||||
'1d'
|
||||
)
|
||||
).rejects.toThrow('UTC midnight');
|
||||
await expect(
|
||||
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, date: '2024-02-30' }])
|
||||
).rejects.toThrow('Invalid OHLCV');
|
||||
});
|
||||
|
||||
test('dataset hashes survive JSON key reordering and reject tampering or mismatched requests', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const first = await loadDataset(storage, datasetConfig());
|
||||
const reordered = JSON.parse(JSON.stringify(first), (_key, value) =>
|
||||
value && !Array.isArray(value) && typeof value === 'object'
|
||||
? Object.fromEntries(Object.entries(value).reverse())
|
||||
: value
|
||||
);
|
||||
expect(validateDataset(reordered, datasetConfig())).toEqual(first);
|
||||
const changed = structuredClone(first);
|
||||
changed.bars[0]!.volume++;
|
||||
expect(() => validateDataset(changed)).toThrow('hash/content');
|
||||
expect(() =>
|
||||
validateDataset(first, { ...datasetConfig(), symbols: ['FIXTURE.OTHER'] })
|
||||
).toThrow('does not match');
|
||||
expect(() =>
|
||||
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
|
||||
).toThrow('does not match');
|
||||
});
|
||||
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
|
|
@ -76,7 +250,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
name: 'Fixed replay',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
|
|
@ -98,6 +272,28 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
|
||||
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const other = { ...identity, exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
|
||||
await persistEodPrices(mongodb, identity, fixture);
|
||||
await persistEodPrices(mongodb, other, fixture);
|
||||
const config = {
|
||||
...datasetConfig(),
|
||||
symbols: [identity.eodSearchCode, other.eodSearchCode],
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
for (const id of config.symbols) {
|
||||
expect(first.ohlcData[id]).toHaveLength(fixture.length);
|
||||
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
|
||||
}
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
});
|
||||
|
||||
test('rejects malformed provider records before writing anything', async () => {
|
||||
const { documents, mongodb } = memoryStore();
|
||||
await expect(
|
||||
|
|
@ -108,7 +304,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
|
||||
test('missing storage never silently produces synthetic prices', async () => {
|
||||
const storage = new StorageService({ logger }, null, null, null);
|
||||
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
|
||||
await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow(
|
||||
'explicit opt-in'
|
||||
);
|
||||
});
|
||||
|
|
@ -118,8 +314,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
allowSyntheticData: true,
|
||||
syntheticSeed: 7,
|
||||
});
|
||||
expect(await storage.getHistoricalBars('FIXTURE', start, end, '1d')).toEqual(
|
||||
await storage.getHistoricalBars('FIXTURE', start, end, '1d')
|
||||
expect(await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).toEqual(
|
||||
await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -128,7 +324,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: ['FIXTURE'],
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
|
|
@ -142,3 +338,15 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function datasetConfig() {
|
||||
return BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: [identity.eodSearchCode],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backte
|
|||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
|
|
@ -65,7 +66,11 @@ async function fixture() {
|
|||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`);
|
||||
for (const filename of ['09-backtest-run-contract.sql', '10-durable-backtest-dispatch.sql']) {
|
||||
for (const filename of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
|
|
@ -103,7 +108,7 @@ async function fixture() {
|
|||
{
|
||||
name: 'Durable 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,
|
||||
|
|
@ -112,25 +117,33 @@ async function fixture() {
|
|||
{ autoStart: false }
|
||||
);
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 2_000);
|
||||
const history = { reads: 0, unavailable: false };
|
||||
const storage = {
|
||||
async getHistoricalBars() {
|
||||
history.reads++;
|
||||
if (history.unavailable) {
|
||||
throw new Error('Provider history unavailable');
|
||||
}
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
symbol: 'FIXTURE.TEST',
|
||||
source: 'eod',
|
||||
timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
} as unknown as StorageService;
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger,
|
||||
custom: {
|
||||
StorageService: {
|
||||
async getHistoricalBars() {
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
} as unknown as StorageService,
|
||||
StorageService: storage,
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 5_000 }
|
||||
|
|
@ -189,10 +202,112 @@ async function fixture() {
|
|||
enqueueWorker,
|
||||
snapshot,
|
||||
expire,
|
||||
history,
|
||||
storage,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
PERFORM pg_sleep(0.35); RETURN NEW; END $$;
|
||||
CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`);
|
||||
const short = new PostgresBacktestRunRepository(f.postgres, 250);
|
||||
const claim = await short.start(config);
|
||||
await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
|
||||
.dataset_hash
|
||||
).toBeNull();
|
||||
});
|
||||
test('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => {
|
||||
const f = await fixture();
|
||||
const first = await f.runner.runQueued(
|
||||
(await f.api.createRun({ backtestId: f.definition.id })).id
|
||||
);
|
||||
const baseline = (await f.api.getRunResults(first.runId))!;
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const old = await f.repository.start(await f.snapshot(run.id));
|
||||
const frozen = await f.repository.loadDataset(
|
||||
run.id,
|
||||
old.attemptId,
|
||||
baseline.config.dataset!.hash
|
||||
);
|
||||
expect(frozen?.bars).toHaveLength(70);
|
||||
await f.expire(run.id);
|
||||
await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf(
|
||||
BacktestLeaseLostError
|
||||
);
|
||||
const reads = f.history.reads;
|
||||
f.history.unavailable = true;
|
||||
await f.dispatcher.tick();
|
||||
await f.runner.runQueued(run.id);
|
||||
const replay = (await f.api.getRunResults(run.id))!;
|
||||
expect(f.history.reads).toBe(reads);
|
||||
expect(replay.config.dataset).toEqual(baseline.config.dataset);
|
||||
expect(replay.trades).toEqual(baseline.trades);
|
||||
expect(replay.metrics).toEqual(baseline.metrics);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
const config = await f.snapshot(run.id);
|
||||
const claim = await f.repository.start(config);
|
||||
const dataset = await loadDataset(f.storage, config);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$;
|
||||
CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`);
|
||||
await expect(f.repository.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow(
|
||||
'injected'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0);
|
||||
expect(
|
||||
(await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0]
|
||||
.dataset_hash
|
||||
).toBeNull();
|
||||
await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs');
|
||||
await f.repository.freezeDataset(run.id, claim.attemptId, dataset);
|
||||
const different = await loadDataset(f.storage, {
|
||||
...config,
|
||||
dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
});
|
||||
await expect(f.repository.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow(
|
||||
'already frozen'
|
||||
);
|
||||
expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe(
|
||||
dataset.manifest.hash
|
||||
);
|
||||
});
|
||||
|
||||
test('an explicit dataset replay rejects a different listing or date range', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
await f.runner.runQueued(run.id);
|
||||
const result = (await f.api.getRunResults(run.id))!;
|
||||
await expect(
|
||||
f.runner.runBacktest({
|
||||
...(await f.snapshot(run.id)),
|
||||
runId: undefined,
|
||||
endDate: '2024-03-16T00:00:00.000Z',
|
||||
datasetHash: result.config.dataset!.hash,
|
||||
})
|
||||
).rejects.toThrow('does not match');
|
||||
});
|
||||
test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => {
|
||||
const f = await fixture();
|
||||
await f.pool
|
||||
|
|
@ -218,7 +333,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
).toHaveLength(1);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
config: { fastPeriod: 999 },
|
||||
symbols: ['MUTATED'],
|
||||
symbols: ['MUTATED.TEST'],
|
||||
});
|
||||
// A fresh dispatcher models an API restart after SQL commit but before the first publish.
|
||||
const restarted = new BacktestDispatcher(f.postgres, f.queue, logger);
|
||||
|
|
@ -227,7 +342,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
f.enqueueWorker();
|
||||
await until(async () => (await f.api.getRun(run.id))?.status === 'completed');
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE']);
|
||||
expect(result?.config.symbols).toEqual(['FIXTURE.TEST']);
|
||||
expect(result?.config.parameters.fastPeriod).toBe(3);
|
||||
expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1);
|
||||
});
|
||||
|
|
@ -288,6 +403,7 @@ describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Red
|
|||
BacktestLeaseLostError
|
||||
);
|
||||
expect((await f.api.getRun(run.id))?.status).toBe('running');
|
||||
await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash);
|
||||
await f.repository.complete(result, replacement.attemptId);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue