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

@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
import type { TransactionCallback } from '@stock-bot/postgres';
import type { PostgresClient } from '@stock-bot/services';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
import { validateDataset } from '../data/historical-dataset';
import { BacktestConfigSchema, type BacktestConfig } from '../types';
import { BacktestCancelledError } from './execution-engine';
import {
@ -126,6 +127,93 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
async loadDataset(
runId: string,
attemptId: string,
requestedHash?: string
): Promise<HistoricalDataset | null> {
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
[runId, attemptId]
);
if (!owned.rows[0]) {
throw new BacktestLeaseLostError('Execution lease lost');
}
const hash = owned.rows[0].dataset_hash ?? requestedHash;
if (!hash) {
return null;
}
if (requestedHash && requestedHash !== hash) {
throw new BacktestConflictError('Run dataset is already frozen');
}
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
hash,
]);
if (!saved.rows[0]) {
throw new Error('Frozen dataset not found');
}
const dataset = validateDataset(saved.rows[0].payload);
if (dataset.manifest.hash !== hash) {
throw new Error('Stored dataset identity mismatch');
}
const pinned = await client.query(
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
[runId, hash, attemptId]
);
if (!pinned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
}
return dataset;
});
}
async freezeDataset(
runId: string,
attemptId: string,
input: HistoricalDataset
): Promise<HistoricalDataset> {
const dataset = validateDataset(input);
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`,
[runId, attemptId]
);
if (!owned.rows[0]) {
throw new BacktestLeaseLostError('Execution lease lost');
}
const hash = dataset.manifest.hash;
if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) {
throw new BacktestConflictError('Run dataset is already frozen');
}
await client.query(
'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING',
[hash, JSON.stringify(dataset)]
);
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
hash,
]);
const frozen = validateDataset(saved.rows[0]?.payload);
if (frozen.manifest.hash !== hash) {
throw new Error('Stored dataset identity mismatch');
}
const pinned = await client.query(
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
[runId, hash, attemptId]
);
if (!pinned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
}
return frozen;
});
}
/** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its
* predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
@ -156,7 +244,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
`UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused')
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`,
AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`,
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
);
if (!updated.rows.length) {
@ -171,6 +259,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
}
throw new BacktestLeaseLostError('Execution lease lost');
}
if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) {
throw new BacktestConflictError('Result does not reference the run frozen dataset');
}
await client.query(
`INSERT INTO backtest_results
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine)