266 lines
10 KiB
TypeScript
266 lines
10 KiB
TypeScript
/** Historical-data fixtures and migration compatibility only. Production composition
|
|
* uses PostgresBacktestRunRepository, whose public surface has no legacy writer methods.
|
|
* Shared ownership/completion helpers keep both paths under the same transaction fences. */
|
|
import { randomUUID } from 'node:crypto';
|
|
import type { PoolClient } from 'pg';
|
|
import {
|
|
parseBacktestRequest,
|
|
rejectCatalogVersionReferences,
|
|
} from '@stock-bot/stock-config/backtest';
|
|
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
|
import { prepareDataset } from '../../data/historical-dataset';
|
|
import type { BacktestConfig } from '../../types';
|
|
import { PostgresBacktestRunRepository } from '../PostgresBacktestRunRepository';
|
|
import { BacktestConflictError, BacktestLeaseLostError, type RunIdentity } from '../run-repository';
|
|
|
|
interface LegacyRunClaim extends RunIdentity {
|
|
attemptId: string;
|
|
config: BacktestConfig;
|
|
}
|
|
export class LegacyBacktestRunWriter extends PostgresBacktestRunRepository {
|
|
/** Legacy claim/create path. Current queued research uses startCanonical instead. */
|
|
async start(config: BacktestConfig): Promise<LegacyRunClaim> {
|
|
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 };
|
|
});
|
|
}
|
|
|
|
/** 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;
|
|
}
|
|
|
|
/** 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,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
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');
|
|
}
|
|
});
|
|
}
|
|
}
|