refactor: share research domain and simplify application workflows
This commit is contained in:
parent
805a9f8fd4
commit
8c39ccf7ea
58 changed files with 3805 additions and 3081 deletions
128
apps/stock/web-api/src/services/backtests/contracts.ts
Normal file
128
apps/stock/web-api/src/services/backtests/contracts.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { BacktestDefinitionInput } from '@stock-bot/stock-config/backtest';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
ResearchActor,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
export type BacktestTransport = (url: string, init?: RequestInit) => Promise<Response>;
|
||||
/** Reads may share an existing transaction without acquiring another pool connection. */
|
||||
export interface BacktestResultQuery {
|
||||
query<T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
values?: unknown[]
|
||||
): Promise<{ rows: T[] }>;
|
||||
}
|
||||
|
||||
export interface BacktestRequest {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
}
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
archivedAt: string | null;
|
||||
strategyVersionId: string | null;
|
||||
strategyParameters: Record<string, StrategyParameterValue> | null;
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
initialCapital: number;
|
||||
config: Record<string, unknown>;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
originalRunId: string | null;
|
||||
dataset: BacktestRunDatasetSelection;
|
||||
id: string;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
pausedAt?: Date;
|
||||
progress: number;
|
||||
cancelRequested: boolean;
|
||||
attemptNumber: number;
|
||||
currentDate?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface RunRequest {
|
||||
backtestId: string;
|
||||
speedMultiplier?: number | null;
|
||||
}
|
||||
|
||||
export interface RunSubmission {
|
||||
principal: ResearchActor;
|
||||
key: string;
|
||||
}
|
||||
|
||||
export class RunSubmissionConflictError extends Error {
|
||||
constructor() {
|
||||
super('This submission key was already used for a different run request');
|
||||
this.name = 'RunSubmissionConflictError';
|
||||
}
|
||||
}
|
||||
export class CatalogExecutionUnavailableError extends Error {
|
||||
readonly code = 'catalog_execution_unavailable';
|
||||
constructor(reason?: string) {
|
||||
super(
|
||||
reason ??
|
||||
'Configure an approved built-in, eligible v2 dataset and canonical policy before execution'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip only DTO metadata from legacy definitions; caller-supplied markers are rejected first. */
|
||||
export function legacyDefinition(input: BacktestDefinitionInput): BacktestDefinitionInput {
|
||||
return {
|
||||
name: input.name,
|
||||
strategy: input.strategy,
|
||||
symbols: input.symbols,
|
||||
startDate: input.startDate,
|
||||
endDate: input.endDate,
|
||||
initialCapital: input.initialCapital,
|
||||
config: input.config,
|
||||
};
|
||||
}
|
||||
|
||||
export class BacktestRetentionError extends Error {
|
||||
constructor(
|
||||
public readonly code: 'backtest_archived' | 'retained_runs',
|
||||
public readonly runCount?: number
|
||||
) {
|
||||
super(
|
||||
code === 'backtest_archived'
|
||||
? 'Backtest is archived; restore it before editing or submitting a new run'
|
||||
: `Backtest has ${runCount} retained run(s); archive it to preserve results and reproducibility`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Application service for editable templates and immutable run inputs/results.
|
||||
* Submission writes a PostgreSQL outbox row for BacktestDispatcher; execution
|
||||
* belongs to the orchestrator. Historical result readers remain available even
|
||||
* though new submissions require the canonical Rust research path.
|
||||
*/
|
||||
|
||||
export type BacktestContainer = IServiceContainer & {
|
||||
postgres: NonNullable<IServiceContainer['postgres']>;
|
||||
};
|
||||
76
apps/stock/web-api/src/services/backtests/mapping.ts
Normal file
76
apps/stock/web-api/src/services/backtests/mapping.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import type { QueryResultRow } from 'pg';
|
||||
import { datasetHashSchema, parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { BacktestRunDatasetSelection } from '@stock-bot/types';
|
||||
import type { Backtest, Run } from './contracts';
|
||||
|
||||
export function mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null,
|
||||
strategyVersionId: row.strategy_version_id ?? null,
|
||||
strategyParameters: row.strategy_parameters ?? null,
|
||||
name: row.name,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
export function mapRun(row: QueryResultRow): Run {
|
||||
return {
|
||||
originalRunId: row.original_run_id ?? null,
|
||||
dataset: datasetSelectionForRun(row),
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
runNumber: row.run_number,
|
||||
status: row.status,
|
||||
speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier),
|
||||
error: row.error,
|
||||
startedAt: row.started_at,
|
||||
completedAt: row.completed_at,
|
||||
pausedAt: row.paused_at,
|
||||
progress: parseFloat(row.progress),
|
||||
cancelRequested: row.cancel_requested === true,
|
||||
attemptNumber: Number(row.attempt_number ?? 0),
|
||||
currentDate: row.current_simulation_date,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
/** Provenance comes from the immutable request and bound dataset, never its template. */
|
||||
export function datasetSelectionForRun(row: QueryResultRow): BacktestRunDatasetSelection {
|
||||
const hash = datasetHashSchema.safeParse(row.dataset_hash);
|
||||
const pinnedHash = hash.success ? hash.data : null;
|
||||
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
|
||||
const canonical = canonicalRunRequestSchema.safeParse(row.request_snapshot);
|
||||
return {
|
||||
requestedHash: canonical.success ? canonical.data.datasetHash : null,
|
||||
pinnedHash,
|
||||
source: null,
|
||||
state: canonical.success ? (pinnedHash ? 'pinned' : 'unavailable') : 'unknown',
|
||||
};
|
||||
}
|
||||
let snapshot;
|
||||
try {
|
||||
snapshot = parseBacktestRequest(row.request_snapshot);
|
||||
} catch {
|
||||
return { requestedHash: null, pinnedHash, source: null, state: 'unknown' };
|
||||
}
|
||||
return {
|
||||
requestedHash: snapshot.datasetHash ?? null,
|
||||
pinnedHash,
|
||||
source: snapshot.dataSource ?? 'auto',
|
||||
state: pinnedHash
|
||||
? 'pinned'
|
||||
: ['completed', 'failed', 'cancelled'].includes(row.status)
|
||||
? 'unavailable'
|
||||
: ['running', 'paused'].includes(row.status)
|
||||
? 'preparing'
|
||||
: 'requested',
|
||||
};
|
||||
}
|
||||
243
apps/stock/web-api/src/services/backtests/reproduction.ts
Normal file
243
apps/stock/web-api/src/services/backtests/reproduction.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalReproductionComparison,
|
||||
type CanonicalReproductionPreview,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { canonicalReproductionHash } from '../reproduction-comparison';
|
||||
import { RunReproductionError, verifyReproductionInputs } from '../run-reproduction';
|
||||
import {
|
||||
BacktestRetentionError,
|
||||
RunSubmissionConflictError,
|
||||
type BacktestContainer,
|
||||
type Run,
|
||||
type RunSubmission,
|
||||
} from './contracts';
|
||||
import { mapRun } from './mapping';
|
||||
import type { BacktestResults } from './results';
|
||||
|
||||
/** Focused reproduction operations; transaction order is preserved. */
|
||||
export class BacktestReproduction {
|
||||
constructor(
|
||||
private readonly container: BacktestContainer,
|
||||
private readonly results: BacktestResults
|
||||
) {}
|
||||
async getReproductionPreview(originalRunId: string): Promise<CanonicalReproductionPreview> {
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const preview: CanonicalReproductionPreview = {
|
||||
originalRunId,
|
||||
backtestId: source.backtest_id,
|
||||
available: false,
|
||||
reason: null,
|
||||
request: null,
|
||||
currentReviewId: null,
|
||||
};
|
||||
try {
|
||||
const request = await this.originalCanonicalRequest(client, source);
|
||||
preview.request = request;
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'Backtest is archived; restore it before reproducing a run'
|
||||
);
|
||||
}
|
||||
preview.currentReviewId = await verifyReproductionInputs(client, this.container, request);
|
||||
preview.available = true;
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof RunReproductionError)) {
|
||||
throw cause;
|
||||
}
|
||||
preview.reason = cause.message;
|
||||
}
|
||||
return preview;
|
||||
});
|
||||
}
|
||||
|
||||
async reproduceRun(originalRunId: string, submission: RunSubmission): Promise<Run> {
|
||||
if (
|
||||
!submission ||
|
||||
!['operator', 'service'].includes(submission.principal) ||
|
||||
!/^[\x21-\x7e]{1,200}$/.test(submission.key)
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt');
|
||||
}
|
||||
const submissionHash = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
operation: 'reproduce-original',
|
||||
originalRunId,
|
||||
})
|
||||
)
|
||||
.digest('hex');
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[submission.principal, submission.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (saved && saved.submission_hash !== submissionHash) {
|
||||
throw new RunSubmissionConflictError();
|
||||
}
|
||||
return saved;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const original = await this.originalCanonicalRequest(client, source);
|
||||
const reviewId = await verifyReproductionInputs(client, this.container, original);
|
||||
const runId = uuidv4();
|
||||
const snapshot = structuredClone(original);
|
||||
snapshot.runId = runId;
|
||||
snapshot.policy.matching.risk.ledger.sessionId = runId;
|
||||
snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
snapshot.strategy.reviewId = reviewId;
|
||||
canonicalRunRequestSchema.parse(snapshot);
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,
|
||||
submission_principal,submission_key,submission_hash,original_run_id)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8
|
||||
FROM runs WHERE backtest_id=$2
|
||||
ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
source.backtest_id,
|
||||
JSON.stringify(snapshot),
|
||||
snapshot.datasetHash,
|
||||
submission.principal,
|
||||
submission.key,
|
||||
submissionHash,
|
||||
originalRunId,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows[0]) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent reproduction disappeared; retry with the same key');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return inserted.rows[0];
|
||||
});
|
||||
return mapRun(row);
|
||||
}
|
||||
|
||||
async getReproductionComparison(runId: string): Promise<CanonicalReproductionComparison> {
|
||||
const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0];
|
||||
if (!current) {
|
||||
throw new RunReproductionError(404, 'Run not found');
|
||||
}
|
||||
const comparison: CanonicalReproductionComparison = {
|
||||
version: 'canonical-reproduction/v1',
|
||||
runId,
|
||||
backtestId: current.backtest_id,
|
||||
originalRunId: current.original_run_id ?? null,
|
||||
status: 'not-reproduction',
|
||||
reason: null,
|
||||
originalHash: null,
|
||||
reproducedHash: null,
|
||||
};
|
||||
if (!comparison.originalRunId) {
|
||||
return comparison;
|
||||
}
|
||||
if (['pending', 'running', 'paused'].includes(current.status)) {
|
||||
return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' };
|
||||
}
|
||||
if (current.status !== 'completed') {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The reproduction did not complete successfully',
|
||||
};
|
||||
}
|
||||
const source = (
|
||||
await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [
|
||||
comparison.originalRunId,
|
||||
])
|
||||
).rows[0];
|
||||
if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The original completed run is unavailable',
|
||||
};
|
||||
}
|
||||
const original = await this.results.getRunResults(source.id);
|
||||
const reproduced = await this.results.getRunResults(runId);
|
||||
if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'Complete canonical results are unavailable',
|
||||
};
|
||||
}
|
||||
const originalHash = canonicalReproductionHash(original);
|
||||
const reproducedHash = canonicalReproductionHash(reproduced);
|
||||
return {
|
||||
...comparison,
|
||||
originalHash,
|
||||
reproducedHash,
|
||||
status: originalHash === reproducedHash ? 'match' : 'mismatch',
|
||||
};
|
||||
}
|
||||
|
||||
private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) {
|
||||
if (source.status !== 'completed') {
|
||||
throw new RunReproductionError(409, 'Only completed original runs can be reproduced');
|
||||
}
|
||||
if (source.request_snapshot?.kind !== 'canonical-research/v1') {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original run lacks compatible frozen canonical inputs'
|
||||
);
|
||||
}
|
||||
const request = canonicalRunRequestSchema.parse(source.request_snapshot);
|
||||
if (
|
||||
request.runId !== source.id ||
|
||||
request.backtestId !== source.backtest_id ||
|
||||
request.datasetHash !== source.dataset_hash
|
||||
) {
|
||||
throw new Error('The retained canonical source identity is inconsistent');
|
||||
}
|
||||
const result = await this.results.getRunResults(source.id, client);
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new RunReproductionError(409, 'The original canonical result is unavailable');
|
||||
}
|
||||
return request;
|
||||
}
|
||||
}
|
||||
79
apps/stock/web-api/src/services/backtests/results.ts
Normal file
79
apps/stock/web-api/src/services/backtests/results.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
canonicalStrategyExecution,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from '../backtest-result';
|
||||
import { type BacktestContainer, type BacktestResultQuery } from './contracts';
|
||||
|
||||
/** Focused results operations; transaction order is preserved. */
|
||||
export class BacktestResults {
|
||||
constructor(private readonly container: BacktestContainer) {}
|
||||
async getRunResults(
|
||||
runId: string,
|
||||
database: BacktestResultQuery = this.container.postgres
|
||||
): Promise<ResearchRunResult | null> {
|
||||
const result = await database.query<
|
||||
StoredBacktestResult & {
|
||||
canonical_result?: CanonicalRunResult | null;
|
||||
request_snapshot?: unknown;
|
||||
}
|
||||
>(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
r.status as run_status,
|
||||
r.request_snapshot,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
b.end_date,
|
||||
b.initial_capital,
|
||||
b.config as backtest_config
|
||||
FROM backtest_results br
|
||||
JOIN runs r ON r.id = br.run_id
|
||||
JOIN backtests b ON b.id = r.backtest_id
|
||||
WHERE br.run_id = $1`,
|
||||
[runId]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
if (row.canonical_result !== null && row.canonical_result !== undefined) {
|
||||
const saved = row.canonical_result;
|
||||
const request = canonicalRunRequestSchema.parse(row.request_snapshot);
|
||||
const financial = parseCanonicalFinancialResult(saved.financial, request);
|
||||
if (
|
||||
saved.kind !== 'canonical-result/v1' ||
|
||||
saved.runId !== runId ||
|
||||
saved.backtestId !== row.backtest_id ||
|
||||
saved.status !== 'completed' ||
|
||||
saved.financialEngine !== 'rust' ||
|
||||
saved.strategyExecution !== canonicalStrategyExecution(request) ||
|
||||
!Number.isFinite(Date.parse(saved.completedAt)) ||
|
||||
!Number.isFinite(saved.executionTime) ||
|
||||
saved.executionTime < 0 ||
|
||||
canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) ||
|
||||
canonicalStrategyJson(saved.analytics) !==
|
||||
canonicalStrategyJson(
|
||||
buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics
|
||||
)
|
||||
) {
|
||||
throw new Error('Saved canonical result does not match its admitted request');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
|
||||
throw new Error('Canonical result is missing; no legacy projection is available');
|
||||
}
|
||||
return mapStoredBacktestResult(row);
|
||||
}
|
||||
}
|
||||
246
apps/stock/web-api/src/services/backtests/runs.ts
Normal file
246
apps/stock/web-api/src/services/backtests/runs.ts
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { type CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../../websocket/run-updates';
|
||||
import { admitCanonicalRequest } from '../canonical-research.service';
|
||||
import {
|
||||
BacktestRetentionError,
|
||||
CatalogExecutionUnavailableError,
|
||||
RunSubmissionConflictError,
|
||||
type BacktestContainer,
|
||||
type BacktestTransport,
|
||||
type Run,
|
||||
type RunRequest,
|
||||
type RunSubmission,
|
||||
} from './contracts';
|
||||
import { mapBacktest, mapRun } from './mapping';
|
||||
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
|
||||
/** Focused runs operations; transaction order is preserved. */
|
||||
export class BacktestRuns {
|
||||
private wsHandler: WebSocketHandler | null = null;
|
||||
constructor(
|
||||
private readonly container: BacktestContainer,
|
||||
private readonly request: BacktestTransport
|
||||
) {}
|
||||
async createRun(request: RunRequest, submission?: RunSubmission): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new HistoricalDataRequestError('Speed multiplier must be positive or null');
|
||||
}
|
||||
// Hash submission intent, not the mutable definition or newly generated run ID.
|
||||
// A retry after an edit must still return the original run and its frozen snapshot.
|
||||
const submissionHash = submission
|
||||
? createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
backtestId: request.backtestId,
|
||||
speedMultiplier: multiplier,
|
||||
})
|
||||
)
|
||||
.digest('hex')
|
||||
: null;
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const replay = async () => {
|
||||
if (!submission) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = await client.query(
|
||||
'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2',
|
||||
[submission.principal, submission.key]
|
||||
);
|
||||
const saved = existing.rows[0];
|
||||
if (saved && saved.submission_hash !== submissionHash) {
|
||||
throw new RunSubmissionConflictError();
|
||||
}
|
||||
return saved;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (at(parent.rows, 0).archived_at) {
|
||||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const definition = mapBacktest(at(parent.rows, 0));
|
||||
const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog';
|
||||
if (!catalog) {
|
||||
throw new CatalogExecutionUnavailableError(
|
||||
'Legacy backtest execution is retired. Select an approved strategy version and retained canonical dataset.'
|
||||
);
|
||||
}
|
||||
if (multiplier !== null) {
|
||||
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
|
||||
}
|
||||
const snapshot = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
definition,
|
||||
definition.id,
|
||||
runId
|
||||
).catch((error: unknown) => {
|
||||
throw new CatalogExecutionUnavailableError(
|
||||
error instanceof Error ? error.message : 'Canonical execution unavailable'
|
||||
);
|
||||
});
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot, dataset_hash,
|
||||
submission_principal, submission_key, submission_hash)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $8, $5, $6, $7
|
||||
FROM runs WHERE backtest_id = $2
|
||||
${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''}
|
||||
RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
multiplier,
|
||||
JSON.stringify(snapshot),
|
||||
submission?.principal ?? null,
|
||||
submission?.key ?? null,
|
||||
submissionHash,
|
||||
snapshot.datasetHash,
|
||||
]
|
||||
);
|
||||
// Different parent locks can race for one principal/key. The unique index waits for
|
||||
// the winner's transaction; this next READ COMMITTED query sees its committed row.
|
||||
if (!result.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent submission disappeared; retry with the same key');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
return mapRun(row);
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapRun(at(result.rows, 0));
|
||||
}
|
||||
|
||||
async listRuns(backtestId: string): Promise<Run[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM runs
|
||||
WHERE backtest_id = $1
|
||||
ORDER BY run_number DESC`,
|
||||
[backtestId]
|
||||
);
|
||||
|
||||
return result.rows.map(row => mapRun(row));
|
||||
}
|
||||
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
updates: { progress?: number; currentDate?: Date; attemptId: string }
|
||||
): Promise<void> {
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]);
|
||||
return client.query(
|
||||
`UPDATE runs
|
||||
SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId]
|
||||
);
|
||||
});
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
runId: id,
|
||||
data: { status: row.status, ...updates, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async pauseRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'pause');
|
||||
}
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs SET cancel_requested = TRUE,
|
||||
status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END,
|
||||
completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`,
|
||||
[id]
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) {
|
||||
throw new Error('No cancellable run found');
|
||||
}
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
}
|
||||
|
||||
private async sendControl(runId: string, command: string, payload: object = {}): Promise<void> {
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...payload, runId }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`);
|
||||
}
|
||||
// The runner, not the API client, commits acknowledged state changes.
|
||||
}
|
||||
|
||||
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
|
||||
try {
|
||||
const execution = await this.container.postgres.transaction(async client => {
|
||||
const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id]))
|
||||
.rows[0];
|
||||
if (!row || row.archived_at !== null) {
|
||||
throw new Error('Backtest is missing or archived');
|
||||
}
|
||||
const request = await admitCanonicalRequest(client, this.container, mapBacktest(row), id);
|
||||
return request.strategy.origin === 'candidate' ? request.strategy.execution : undefined;
|
||||
});
|
||||
return { available: true, reason: null, ...(execution ? { execution } : {}) };
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
reason: error instanceof Error ? error.message : 'Canonical execution unavailable',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private getWebSocketHandler(): WebSocketHandler | null {
|
||||
// Try to get from global if not already set
|
||||
this.wsHandler ??= getWebSocketHandler();
|
||||
return this.wsHandler;
|
||||
}
|
||||
}
|
||||
321
apps/stock/web-api/src/services/backtests/templates.ts
Normal file
321
apps/stock/web-api/src/services/backtests/templates.ts
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
rejectCatalogVersionReferences,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
assertStrategyJsonText,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { validateCanonicalSetup } from '../canonical-research.service';
|
||||
import { assertSelectedDatasetMatchesRequest } from '../dataset-catalog.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from '../strategy-catalog.service';
|
||||
import {
|
||||
BacktestRetentionError,
|
||||
legacyDefinition,
|
||||
type Backtest,
|
||||
type BacktestContainer,
|
||||
type BacktestRequest,
|
||||
type Run,
|
||||
type RunRequest,
|
||||
} from './contracts';
|
||||
import { mapBacktest } from './mapping';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
/** Focused templates operations; transaction order is preserved. */
|
||||
export class BacktestTemplates {
|
||||
constructor(
|
||||
private readonly container: BacktestContainer,
|
||||
private readonly startRun: (request: RunRequest) => Promise<Run>
|
||||
) {}
|
||||
async createBacktest(
|
||||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
const catalog = request.strategy === 'catalog';
|
||||
if (catalog && options.autoStart !== false) {
|
||||
throw new HistoricalDataRequestError('Catalog drafts require explicit autoStart:false');
|
||||
}
|
||||
if (!catalog) {
|
||||
rejectCatalogVersionReferences(request);
|
||||
}
|
||||
const backtestId = uuidv4();
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
const definition = catalog ? await this.validateCatalogDraft(client, request) : request;
|
||||
if (!catalog) {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(definition)
|
||||
);
|
||||
}
|
||||
return client.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, strategy_version_id, strategy_parameters)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
definition.name,
|
||||
definition.strategy,
|
||||
JSON.stringify(definition.symbols),
|
||||
definition.startDate,
|
||||
definition.endDate,
|
||||
definition.initialCapital,
|
||||
JSON.stringify(definition.config || {}),
|
||||
definition.strategyVersionId ?? null,
|
||||
definition.strategyParameters ? JSON.stringify(definition.strategyParameters) : null,
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
const backtest = mapBacktest(at(result.rows, 0));
|
||||
|
||||
// Automatically create and start a run for the new backtest
|
||||
if (options.autoStart !== false) {
|
||||
try {
|
||||
await this.startRun({
|
||||
backtestId: backtest.id,
|
||||
speedMultiplier: null, // Max speed (instant)
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to auto-create run for new backtest', {
|
||||
backtestId: backtest.id,
|
||||
error,
|
||||
});
|
||||
// Don't fail the backtest creation if run creation fails
|
||||
}
|
||||
}
|
||||
return backtest;
|
||||
}
|
||||
|
||||
async getBacktest(id: string): Promise<Backtest | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
|
||||
id,
|
||||
]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapBacktest(at(result.rows, 0));
|
||||
}
|
||||
|
||||
async updateBacktest(id: string, request: Partial<BacktestRequest>): Promise<Backtest | null> {
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const locked = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [id]);
|
||||
if (!locked.rows[0]) {
|
||||
return null;
|
||||
}
|
||||
if (locked.rows[0].archived_at) {
|
||||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const existing = mapBacktest(locked.rows[0]);
|
||||
const catalog = existing.strategyVersionId !== null;
|
||||
let next = { ...existing, ...request };
|
||||
if (catalog) {
|
||||
CatalogBacktestDefinitionSchema.partial().parse(request);
|
||||
if (
|
||||
request.strategyVersionId !== undefined &&
|
||||
request.strategyVersionId !== existing.strategyVersionId &&
|
||||
request.strategyParameters === undefined
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Changing a selected version requires explicit strategyParameters'
|
||||
);
|
||||
}
|
||||
const normalized = await this.validateCatalogDraft(
|
||||
client,
|
||||
{
|
||||
...legacyDefinition(next),
|
||||
strategyVersionId: next.strategyVersionId,
|
||||
strategyParameters: next.strategyParameters,
|
||||
},
|
||||
existing.strategyVersionId
|
||||
);
|
||||
next = { ...next, ...normalized } as typeof next;
|
||||
} else {
|
||||
rejectCatalogVersionReferences(request);
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(legacyDefinition(next))
|
||||
);
|
||||
}
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
||||
if (request.name !== undefined) {
|
||||
updates.push(`name = $${paramCount++}`);
|
||||
values.push(catalog ? next.name : request.name);
|
||||
}
|
||||
if (request.strategy !== undefined) {
|
||||
updates.push(`strategy = $${paramCount++}`);
|
||||
values.push(catalog ? next.strategy : request.strategy);
|
||||
}
|
||||
if (request.symbols !== undefined) {
|
||||
updates.push(`symbols = $${paramCount++}`);
|
||||
values.push(JSON.stringify(catalog ? next.symbols : request.symbols));
|
||||
}
|
||||
if (request.startDate !== undefined) {
|
||||
updates.push(`start_date = $${paramCount++}`);
|
||||
values.push(catalog ? next.startDate : request.startDate);
|
||||
}
|
||||
if (request.endDate !== undefined) {
|
||||
updates.push(`end_date = $${paramCount++}`);
|
||||
values.push(catalog ? next.endDate : request.endDate);
|
||||
}
|
||||
if (request.initialCapital !== undefined) {
|
||||
updates.push(`initial_capital = $${paramCount++}`);
|
||||
values.push(catalog ? next.initialCapital : request.initialCapital);
|
||||
}
|
||||
if (request.config !== undefined) {
|
||||
updates.push(`config = $${paramCount++}`);
|
||||
values.push(JSON.stringify(catalog ? next.config : request.config));
|
||||
}
|
||||
if (catalog) {
|
||||
updates.push(
|
||||
`strategy_version_id = $${paramCount++}`,
|
||||
`strategy_parameters = $${paramCount++}`
|
||||
);
|
||||
values.push(next.strategyVersionId, JSON.stringify(next.strategyParameters));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
values.push(id);
|
||||
const result = await client.query(
|
||||
`UPDATE backtests
|
||||
SET ${updates.join(', ')}, updated_at = NOW()
|
||||
WHERE id = $${paramCount}
|
||||
RETURNING *`,
|
||||
values
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapBacktest(at(result.rows, 0));
|
||||
});
|
||||
}
|
||||
|
||||
async listBacktests(params: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
includeArchived?: boolean;
|
||||
}): Promise<Backtest[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
WHERE ($3::boolean OR archived_at IS NULL)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset, params.includeArchived === true]
|
||||
);
|
||||
|
||||
return result.rows.map(row => mapBacktest(row));
|
||||
}
|
||||
|
||||
async deleteBacktest(id: string): Promise<void> {
|
||||
await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]);
|
||||
if (!parent.rows[0]) {
|
||||
return;
|
||||
}
|
||||
const retained = await client.query(
|
||||
'SELECT count(*)::int AS count FROM runs WHERE backtest_id=$1',
|
||||
[id]
|
||||
);
|
||||
const count = Number(retained.rows[0]?.count ?? 0);
|
||||
if (count > 0) {
|
||||
throw new BacktestRetentionError('retained_runs', count);
|
||||
}
|
||||
await client.query('DELETE FROM backtests WHERE id=$1', [id]);
|
||||
});
|
||||
}
|
||||
|
||||
async archiveBacktest(id: string, archived: boolean): Promise<Backtest | null> {
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [id]);
|
||||
if (!parent.rows[0]) {
|
||||
return null;
|
||||
}
|
||||
const updated = await client.query(
|
||||
`UPDATE backtests
|
||||
SET archived_at=CASE WHEN $2::boolean THEN COALESCE(archived_at,NOW()) ELSE NULL END,
|
||||
updated_at=NOW() WHERE id=$1 RETURNING *`,
|
||||
[id, archived]
|
||||
);
|
||||
return mapBacktest(at(updated.rows, 0));
|
||||
});
|
||||
}
|
||||
|
||||
private async validateCatalogDraft(
|
||||
client: PoolClient,
|
||||
input: unknown,
|
||||
previousVersionId?: string | null
|
||||
): Promise<BacktestRequest> {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid catalog draft text'
|
||||
);
|
||||
}
|
||||
const draft = CatalogBacktestDefinitionSchema.parse(input);
|
||||
let parameters: Record<string, StrategyParameterValue>;
|
||||
const pkg = await new StrategyCatalogService(this.container).getVersionArtifact(
|
||||
draft.strategyVersionId,
|
||||
client
|
||||
);
|
||||
try {
|
||||
assertStrategyJsonText(draft);
|
||||
parameters = validateStrategyParameters(pkg, draft.strategyParameters);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid strategy parameters'
|
||||
);
|
||||
}
|
||||
const family = (
|
||||
await client.query(
|
||||
`SELECT s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[draft.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!family) {
|
||||
throw new StrategyCatalogError(404, 'Strategy version not found');
|
||||
}
|
||||
if (previousVersionId !== draft.strategyVersionId && family.archived_at) {
|
||||
throw new StrategyCatalogError(
|
||||
409,
|
||||
'Strategy is archived; restore it before selecting a new version'
|
||||
);
|
||||
}
|
||||
if (draft.config.canonical) {
|
||||
await validateCanonicalSetup(client, { ...draft, strategyParameters: parameters });
|
||||
return {
|
||||
...draft,
|
||||
startDate: new Date(draft.startDate).toISOString(),
|
||||
endDate: new Date(draft.endDate).toISOString(),
|
||||
strategyParameters: parameters,
|
||||
};
|
||||
}
|
||||
const settings = backtestSettingsFromDefinition(draft);
|
||||
await assertSelectedDatasetMatchesRequest(client, settings);
|
||||
return {
|
||||
...draft,
|
||||
startDate: settings.startDate,
|
||||
endDate: settings.endDate,
|
||||
strategyParameters: parameters,
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue