refactor(backtest): isolate legacy persistence capabilities (CL33)

This commit is contained in:
Boki 2026-10-28 14:45:12 -04:00
parent 24487d35da
commit ec582bd5e8
14 changed files with 413 additions and 311 deletions

View file

@ -7,10 +7,6 @@ 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 {
parseBacktestRequest,
rejectCatalogVersionReferences,
} from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
@ -19,29 +15,26 @@ import {
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type { BacktestRunResult, HistoricalDataset, HistoricalDatasetV2 } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { assertDatasetV2Executable } from '../data/historical-dataset-v2';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError } from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
/**
* An attempt UUID is a fencing token: a delayed worker cannot write after replacement.
* Ownership also requires an active status and an unexpired lease measured by PostgreSQL
* time. Canonical methods consume pre-admitted requests; legacy methods remain for older
* contracts and fixtures and do not enable legacy execution through BacktestRunner.
* time. This concrete repository exposes only the current, pre-admitted execution path.
* Historical writers use a separate compatibility adapter with the same fencing helpers.
*/
export class PostgresBacktestRunRepository implements BacktestRunRepository {
constructor(
private readonly postgres: Pick<PostgresClient, 'transaction'>,
private readonly leaseMs = 30_000
protected readonly postgres: Pick<PostgresClient, 'transaction'>,
protected readonly leaseMs = 30_000
) {
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
throw new Error('Invalid execution lease duration');
@ -59,92 +52,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
/** Legacy claim/create path. Current queued research uses startCanonical instead. */
async start(config: BacktestConfig): Promise<RunClaim> {
rejectCatalogVersionReferences(config);
const attemptId = randomUUID();
return this.postgres.transaction(async client => {
if (config.runId) {
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [config.runId]);
const claimed = await client.query(
`UPDATE runs SET status = 'running', progress = 0, error = NULL,
started_at = NOW(), completed_at = NULL, paused_at = NULL, updated_at = NOW(),
attempt_id = $3, attempt_number = attempt_number + 1,
lease_expires_at = clock_timestamp() + $4::interval
WHERE id = $1 AND status = 'pending' AND NOT cancel_requested
AND request_snapshot IS NOT NULL
AND ($2::uuid IS NULL OR backtest_id = $2::uuid)
RETURNING id, backtest_id, request_snapshot`,
[config.runId, config.backtestId ?? null, attemptId, `${this.leaseMs} milliseconds`]
);
const run = claimed.rows[0];
if (!run) {
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
}
const snapshot = parseBacktestRequest(run.request_snapshot);
return {
runId: String(run.id),
backtestId: String(run.backtest_id),
attemptId,
config: snapshot,
};
}
const backtestId = config.backtestId ?? randomUUID();
if (!config.backtestId) {
await client.query(
`INSERT INTO backtests
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
backtestId,
config.name ?? 'Backtest',
config.strategy,
JSON.stringify(config.symbols),
config.startDate,
config.endDate,
config.initialCapital,
JSON.stringify({
...config.config,
dataFrequency: config.dataFrequency,
commission: config.commission,
slippage: config.slippage,
}),
]
);
}
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
backtestId,
]);
if (!parent.rows.length) {
throw new Error('Backtest definition not found');
}
const runId = randomUUID();
const snapshot = { ...config, runId, backtestId };
await client.query(
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier,
request_snapshot, attempt_id, attempt_number, lease_expires_at)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3,
$4::jsonb, $5::uuid, 1, clock_timestamp() + $6::interval
FROM runs WHERE backtest_id = $2`,
[
runId,
backtestId,
config.speed === 'max'
? null
: config.speed === 'realtime'
? 1
: Number.parseFloat(config.speed),
JSON.stringify(snapshot),
attemptId,
`${this.leaseMs} milliseconds`,
]
);
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
return { runId, backtestId, attemptId, config: snapshot };
});
}
/**
* Claim an existing pending run and verify the caller supplied its exact frozen inputs.
* The status/attempt update and snapshot checks share a transaction, so mismatches roll
@ -253,118 +160,12 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
/** Legacy v1 lookup/pinning; canonical admission already binds a retained v2 dataset. */
async loadDataset(
runId: string,
attemptId: 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
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 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()
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');
}
signal?.throwIfAborted();
return dataset;
});
}
/**
* Legacy v1 retention: save validated bytes and pin the run atomically. Reusing an
* existing hash still validates its stored payload; insertion success alone is no proof
* that old content is intact. Any late cancellation/lease failure rolls back the pin.
*/
async freezeDataset(
runId: string,
attemptId: string,
input: HistoricalDataset,
signal?: AbortSignal
): Promise<HistoricalDataset> {
const dataset = await prepareDataset(input, undefined, signal);
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');
}
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 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()
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');
}
signal?.throwIfAborted();
return frozen;
});
}
private async readDataset(
client: PoolClient,
hash: string,
signal?: AbortSignal
): Promise<HistoricalDataset> {
signal?.throwIfAborted();
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [
hash,
]);
const row = saved.rows[0];
if (!row) {
throw new Error('Frozen dataset not found');
}
const dataset = await prepareDataset(row.payload, undefined, signal);
if (dataset.manifest.hash !== hash) {
throw new Error('Stored dataset identity mismatch');
}
return dataset;
}
/**
* Lock first, then evaluate leases against actual DB time: an UPDATE predicate can be
* evaluated before waiting on a row lock, even with clock_timestamp(). This helper only
* acquires the lock; each callback must still check attempt, lease and allowed status.
*/
private ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
protected ownedTransaction<T>(runId: string, work: TransactionCallback<T>): Promise<T> {
return this.postgres.transaction(async client => {
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]);
return work(client);
@ -391,42 +192,19 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
/** Legacy result shape; canonical reports are persisted by completeCanonical. */
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
await this.ownedTransaction(result.runId, async client => {
const updated = await this.markComplete(client, result, attemptId);
if (!result.config.dataset || result.config.dataset.hash !== updated.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)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
[
result.runId,
result.completedAt,
JSON.stringify(result.metrics),
JSON.stringify(result.equity),
JSON.stringify(result.ohlcData),
JSON.stringify(result.trades),
JSON.stringify(result.positions),
JSON.stringify(result.analytics),
result.executionTime,
JSON.stringify(result.config),
result.engine,
]
);
});
}
/**
* Final ownership/cancellation gate inside the surrounding result transaction. A pending
* cancel wins over completion; loss of ownership is a different error. If later result
* validation or insertion fails, the caller's transaction rolls this status update back.
*/
private async markComplete(
protected async markComplete(
client: PoolClient,
result: Pick<BacktestRunResult, 'runId' | 'backtestId' | 'status' | 'completedAt'>,
result: {
runId: string;
backtestId: string;
status: 'completed' | 'cancelled';
completedAt: string;
},
attemptId: string
) {
const updated = await client.query(
@ -513,32 +291,6 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
});
}
async updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
attemptId: string
) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET status = COALESCE($2::run_status, status),
paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END,
speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW()
WHERE id = $1 AND attempt_id = $5 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`,
[
runId,
update.status ?? null,
update.speedMultiplier !== undefined,
update.speedMultiplier ?? null,
attemptId,
]
);
if (!result.rows.length) {
throw new BacktestLeaseLostError('No matching owned active run');
}
});
}
/**
* Best-effort terminal write for a still-owned attempt. A recorded cancel takes priority;
* a stale owner changes no rows. Unlike cancel(), this does not assert an acknowledgement.