feat(research): run retained strategies through durable canonical engine
This commit is contained in:
parent
d929db707a
commit
618fb9e33c
58 changed files with 6596 additions and 779 deletions
|
|
@ -6,14 +6,23 @@ import {
|
|||
parseBacktestRequest,
|
||||
rejectCatalogVersionReferences,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
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';
|
||||
|
||||
|
|
@ -123,6 +132,89 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
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 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`,
|
||||
[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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
async rejectPending(runId: string, error: string) {
|
||||
await this.postgres.transaction(async client => {
|
||||
await client.query(
|
||||
|
|
@ -259,26 +351,8 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
|
||||
async complete(result: BacktestRunResult, attemptId: string): Promise<void> {
|
||||
await this.ownedTransaction(result.runId, async client => {
|
||||
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');
|
||||
}
|
||||
if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) {
|
||||
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(
|
||||
|
|
@ -302,6 +376,69 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
});
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
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 !== 'typescript-retained-builtin/v1'
|
||||
) {
|
||||
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)]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async updateProgress(
|
||||
runId: string,
|
||||
progress: number,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue