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

@ -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