stock-bot/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts

571 lines
24 KiB
TypeScript

/**
* PostgreSQL persistence boundary for research run ownership, retained inputs and results.
* It validates identities and commits worker output; it does not calculate trades, cash
* or equity. These transactions concern research tables, not paper-account execution.
*/
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,
parseCanonicalFinancialResult,
type CanonicalRunRequest,
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 { 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.
*/
export class PostgresBacktestRunRepository implements BacktestRunRepository {
constructor(
private readonly postgres: Pick<PostgresClient, 'transaction'>,
private readonly leaseMs = 30_000
) {
if (!Number.isInteger(leaseMs) || leaseMs < 100) {
throw new Error('Invalid execution lease duration');
}
}
/** Read admission state without claiming it; startCanonical must still arbitrate ownership. */
async load(runId: string) {
return this.postgres.transaction(async client => {
const result = await client.query('SELECT status, request_snapshot FROM runs WHERE id = $1', [
runId,
]);
const row = result.rows[0];
return row ? { status: String(row.status), config: row.request_snapshot as unknown } : null;
});
}
/** 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
* back the claim. Recovery must first return an expired run to pending; this method
* neither steals active leases nor creates a new run or dataset.
*/
async startCanonical(input: CanonicalRunRequest): Promise<CanonicalRunClaim> {
const request = canonicalRunRequestSchema.parse(input);
const attemptId = randomUUID();
return this.ownedTransaction(request.runId, async client => {
const claimed = await client.query(
`UPDATE runs AS r 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 backtest_id=$2 AND status='pending' AND NOT cancel_requested
AND request_snapshot IS NOT NULL RETURNING id,backtest_id,request_snapshot,dataset_hash,(to_jsonb(r)->>'research_deadline_at')::timestamptz AS research_deadline_at`,
[request.runId, request.backtestId, attemptId, `${this.leaseMs} milliseconds`]
);
const row = claimed.rows[0];
if (!row) {
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
}
const frozen = canonicalRunRequestSchema.parse(row.request_snapshot);
if (
canonicalStrategyJson(frozen) !== canonicalStrategyJson(request) ||
row.dataset_hash !== frozen.datasetHash
) {
throw new BacktestConflictError(
'Canonical request does not match its admitted snapshot and dataset'
);
}
return {
runId: String(row.id),
backtestId: String(row.backtest_id),
attemptId,
config: frozen,
...(row.research_deadline_at
? { executionDeadlineAt: new Date(row.research_deadline_at).getTime() }
: {}),
};
});
}
/**
* Load only the v2 bytes bound by admission. Check the request, run pointer and content
* hash together; no missing-data provider fallback is allowed. The final lease check
* prevents slow validation from authorizing execution after ownership has expired.
*/
async loadCanonicalDataset(
runId: string,
attemptId: string,
requestedHash: string,
signal?: AbortSignal
): Promise<HistoricalDatasetV2> {
signal?.throwIfAborted();
return this.ownedTransaction(runId, async client => {
const owned = await client.query(
`SELECT dataset_hash,request_snapshot 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]
);
const row = owned.rows[0];
if (!row) {
throw new BacktestLeaseLostError('Execution lease lost');
}
const request = canonicalRunRequestSchema.parse(row.request_snapshot);
if (row.dataset_hash !== requestedHash || request.datasetHash !== requestedHash) {
throw new BacktestConflictError('Canonical dataset does not match its immutable binding');
}
const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
requestedHash,
]);
if (!saved.rows[0]) {
throw new Error('Frozen canonical dataset not found');
}
signal?.throwIfAborted();
const dataset = assertDatasetV2Executable(saved.rows[0].payload);
if (dataset.manifest.hash !== requestedHash || dataset.manifest.eligibility !== 'eligible') {
throw new BacktestConflictError(
'Stored canonical dataset identity or eligibility mismatch'
);
}
signal?.throwIfAborted();
// Validation may outlast a lease; do not let a late read authorize execution.
const stillOwned = await client.query(
`SELECT id 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 (!stillOwned.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost while validating dataset');
}
return dataset;
});
}
/** Reject malformed/retired queued input only while unclaimed; never overwrite an owner. */
async rejectPending(runId: string, error: string) {
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET status = 'failed', error = $2,
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
[runId, error]
);
});
}
/** 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> {
return this.postgres.transaction(async client => {
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [runId]);
return work(client);
});
}
/**
* Renew a still-valid owner and return its cancellation flag in the same statement.
* A cancellation request does not immediately revoke ownership: the worker needs its
* lease to stop execution and commit cancellation. An expired lease cannot be renewed.
*/
async heartbeat(runId: string, attemptId: string) {
return this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET lease_expires_at = clock_timestamp() + $3::interval, updated_at = NOW()
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') RETURNING cancel_requested`,
[runId, attemptId, `${this.leaseMs} milliseconds`]
);
if (!result.rows[0]) {
throw new BacktestLeaseLostError('Execution lease lost');
}
return { cancelRequested: result.rows[0].cancel_requested === true };
});
}
/** 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(
client: PoolClient,
result: Pick<BacktestRunResult, 'runId' | 'backtestId' | 'status' | 'completedAt'>,
attemptId: string
) {
const updated = await client.query(
`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, dataset_hash`,
[result.runId, result.status, result.completedAt, result.backtestId, attemptId]
);
if (!updated.rows.length) {
const cancellation = await client.query(
`SELECT id FROM runs
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') AND cancel_requested`,
[result.runId, attemptId]
);
if (cancellation.rows.length) {
throw new BacktestCancelledError();
}
throw new BacktestLeaseLostError('Execution lease lost');
}
return updated.rows[0];
}
/**
* Validate the Rust report envelope and its admitted inputs, then atomically commit
* terminal status plus the full canonical result. Legacy financial columns stay null
* so readers do not mistake a second projection for an independent account record.
*/
async completeCanonical(result: CanonicalRunResult, attemptId: string): Promise<void> {
const request = canonicalRunRequestSchema.parse(result.request);
if (
result.kind !== 'canonical-result/v1' ||
result.status !== 'completed' ||
result.runId !== request.runId ||
result.backtestId !== request.backtestId ||
result.financialEngine !== 'rust' ||
result.strategyExecution !== canonicalStrategyExecution(request)
) {
throw new BacktestConflictError('Canonical result identity mismatch');
}
parseCanonicalFinancialResult(result.financial, request);
await this.ownedTransaction(result.runId, async client => {
const frozen = await client.query(
'SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1',
[result.runId]
);
const row = frozen.rows[0];
if (
!row ||
canonicalStrategyJson(row.request_snapshot) !== canonicalStrategyJson(request) ||
row.dataset_hash !== request.datasetHash
) {
throw new BacktestConflictError('Canonical result does not match its admitted inputs');
}
await this.markComplete(client, result, attemptId);
await client.query(
`INSERT INTO backtest_results
(run_id,completed_at,execution_time,canonical_result,metrics,equity_curve,ohlc_data,trades,positions,analytics)
VALUES ($1,$2,$3,$4::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb,'null'::jsonb)`,
[result.runId, result.completedAt, Math.round(result.executionTime), JSON.stringify(result)]
);
});
}
/** Monotonic progress within an attempt; starting a recovered attempt resets it to zero. */
async updateProgress(
runId: string,
progress: number,
currentDate: string | undefined,
attemptId: string
) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET progress = GREATEST(progress, $2),
current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
WHERE id = $1 AND attempt_id = $4 AND lease_expires_at > clock_timestamp()
AND status IN ('running', 'paused') RETURNING id`,
[runId, progress, currentDate ?? null, attemptId]
);
if (!result.rows.length) {
throw new BacktestLeaseLostError('Execution lease lost');
}
});
}
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.
*/
async fail(runId: string, error: string, attemptId: string) {
await this.ownedTransaction(runId, async client => {
await client.query(
`UPDATE runs SET status = CASE WHEN cancel_requested THEN 'cancelled'::run_status ELSE 'failed'::run_status END,
error = CASE WHEN cancel_requested THEN NULL ELSE $2 END,
completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
WHERE id = $1 AND attempt_id = $3 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused')`,
[runId, error, attemptId]
);
});
}
/** Confirm stopped execution under the current lease; failure to write is not success. */
async cancel(runId: string, attemptId: string) {
await this.ownedTransaction(runId, async client => {
const result = await client.query(
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), lease_expires_at = NULL, updated_at = NOW()
WHERE id = $1 AND attempt_id = $2 AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') RETURNING id`,
[runId, attemptId]
);
if (!result.rows.length) {
throw new BacktestLeaseLostError('No matching owned active run to cancel');
}
});
}
}