Bound backtest dataset preparation and preserve replay identity

This commit is contained in:
Boki 2026-10-21 23:18:23 -04:00
parent cca5d71e6e
commit 6bd671d92a
20 changed files with 1420 additions and 155 deletions

View file

@ -1,8 +1,10 @@
import { randomUUID } from 'node:crypto';
import type { PoolClient } from 'pg';
import type { TransactionCallback } from '@stock-bot/postgres';
import type { PostgresClient } from '@stock-bot/services';
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
import { validateDataset } from '../data/historical-dataset';
import { assertDatasetLimit, datasetLimits, type DatasetLimits } from '../data/dataset-limits';
import { prepareDataset } from '../data/historical-dataset';
import { BacktestConfigSchema, type BacktestConfig } from '../types';
import { BacktestCancelledError } from './execution-engine';
import {
@ -14,10 +16,13 @@ import {
/** The attempt UUID is a fencing token. PostgreSQL time, not worker clocks, defines ownership. */
export class PostgresBacktestRunRepository implements BacktestRunRepository {
private readonly datasetLimits: Readonly<DatasetLimits>;
constructor(
private readonly postgres: Pick<PostgresClient, 'transaction'>,
private readonly leaseMs = 30_000
private readonly leaseMs = 30_000,
limits?: Partial<DatasetLimits>
) {
this.datasetLimits = datasetLimits(limits);
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
throw new Error('Invalid execution lease duration');
}
@ -130,8 +135,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
async loadDataset(
runId: string,
attemptId: string,
requestedHash?: string
requestedHash?: string,
signal?: AbortSignal
): Promise<HistoricalDataset | null> {
signal?.throwIfAborted();
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
@ -148,16 +155,8 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
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 dataset = await this.readDataset(client, String(hash), signal);
signal?.throwIfAborted();
const pinned = await client.query(
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
@ -167,6 +166,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
if (!pinned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
}
signal?.throwIfAborted();
return dataset;
});
}
@ -174,9 +174,10 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
async freezeDataset(
runId: string,
attemptId: string,
input: HistoricalDataset
input: HistoricalDataset,
signal?: AbortSignal
): Promise<HistoricalDataset> {
const dataset = validateDataset(input);
const dataset = await prepareDataset(input, undefined, { limits: this.datasetLimits, signal });
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2
@ -190,17 +191,13 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) {
throw new BacktestConflictError('Run dataset is already frozen');
}
signal?.throwIfAborted();
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 frozen = await this.readDataset(client, hash, signal);
signal?.throwIfAborted();
const pinned = await client.query(
`UPDATE runs SET dataset_hash = $2 WHERE id = $1
AND attempt_id = $3 AND lease_expires_at > clock_timestamp()
@ -210,10 +207,38 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
if (!pinned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while pinning dataset');
}
signal?.throwIfAborted();
return frozen;
});
}
private async readDataset(
client: PoolClient,
hash: string,
signal?: AbortSignal
): Promise<HistoricalDataset> {
signal?.throwIfAborted();
// Never transfer/parse an oversized JSONB document into the application process.
const saved = await client.query(
`SELECT CASE WHEN octet_length(payload::text) <= $2 THEN payload ELSE NULL END AS payload,
octet_length(payload::text) AS payload_bytes FROM backtest_datasets WHERE hash = $1`,
[hash, this.datasetLimits.maxStoredBytes]
);
const row = saved.rows[0];
if (!row) {
throw new Error('Frozen dataset not found');
}
assertDatasetLimit(this.datasetLimits, 'maxStoredBytes', Number(row.payload_bytes));
const dataset = await prepareDataset(row.payload, undefined, {
limits: this.datasetLimits,
signal,
});
if (dataset.manifest.hash !== hash) {
throw new Error('Stored dataset identity mismatch');
}
return dataset;
}
/** 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> {