/** * 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 { canonicalRunRequestSchema, canonicalStrategyExecution, parseCanonicalFinancialResult, type CanonicalRunRequest, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { HistoricalDatasetV2 } from '@stock-bot/types'; import { assertDatasetV2Executable } from '../data/historical-dataset-v2'; import { BacktestCancelledError } from './execution-engine'; import { BacktestConflictError, BacktestLeaseLostError, type BacktestRunRepository, type CanonicalRunClaim, } 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. 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( protected readonly postgres: Pick, protected 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; }); } /** * 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 { 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 { 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] ); }); } /** * 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. */ protected ownedTransaction(runId: string, work: TransactionCallback): Promise { 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 }; }); } /** * 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. */ protected async markComplete( client: PoolClient, result: { runId: string; backtestId: string; status: 'completed' | 'cancelled'; completedAt: string; }, 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 { 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'); } }); } /** * 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'); } }); } }