1071 lines
38 KiB
TypeScript
1071 lines
38 KiB
TypeScript
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
|
import type { PoolClient, QueryResultRow } from 'pg';
|
|
import { authenticatedServiceFetch } from '@stock-bot/di';
|
|
import { at } from '@stock-bot/invariants';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
|
import {
|
|
backtestRequestFromDefinition,
|
|
backtestSettingsFromDefinition,
|
|
CatalogBacktestDefinitionSchema,
|
|
datasetHashSchema,
|
|
parseBacktestRequest,
|
|
rejectCatalogVersionReferences,
|
|
type BacktestDefinitionInput,
|
|
} from '@stock-bot/stock-config/backtest';
|
|
import {
|
|
canonicalRunRequestSchema,
|
|
canonicalStrategyExecution,
|
|
parseCanonicalFinancialResult,
|
|
type CanonicalReproductionComparison,
|
|
type CanonicalReproductionPreview,
|
|
type CanonicalRunCapability,
|
|
type CanonicalRunResult,
|
|
type ResearchRunResult,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import {
|
|
assertStrategyJsonText,
|
|
canonicalStrategyJson,
|
|
validateStrategyParameters,
|
|
} from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
BacktestRunDatasetSelection,
|
|
ResearchActor,
|
|
StrategyParameterValue,
|
|
} from '@stock-bot/types';
|
|
import { HistoricalDataRequestError } from '@stock-bot/types';
|
|
import { buildCanonicalBacktestReport } from '../../../orchestrator/src/backtest/canonical-result';
|
|
import { getWebSocketHandler } from '../websocket/run-updates';
|
|
import type { WebSocketHandler } from '../websocket/run-updates';
|
|
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
|
import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service';
|
|
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
|
import { canonicalReproductionHash } from './reproduction-comparison';
|
|
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
|
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
|
|
|
const logger = getLogger('backtest-v2-service');
|
|
|
|
// Use environment variable or default
|
|
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
|
|
|
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. */
|
|
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 class BacktestServiceV2 {
|
|
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
|
private wsHandler: WebSocketHandler | null = null;
|
|
|
|
constructor(
|
|
container: IServiceContainer,
|
|
private readonly request: BacktestTransport = authenticatedServiceFetch
|
|
) {
|
|
this.container = requireServices(container, 'postgres');
|
|
logger.info('BacktestServiceV2 initialized');
|
|
}
|
|
|
|
// Backtest CRUD operations
|
|
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 = this.mapBacktest(at(result.rows, 0));
|
|
|
|
// Automatically create and start a run for the new backtest
|
|
if (options.autoStart !== false) {
|
|
try {
|
|
await this.createRun({
|
|
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 this.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 = this.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 this.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 => this.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 this.mapBacktest(at(updated.rows, 0));
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Admit one logical run, saving its request and dispatch intent atomically.
|
|
* A principal/key identifies the submission, not the template's current contents:
|
|
* the same retry returns the original run even after a template edit. Conflicting
|
|
* reuse fails. No queue operation occurs inside this transaction.
|
|
*/
|
|
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 = this.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 (catalog && multiplier !== null) {
|
|
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
|
|
}
|
|
let canonical;
|
|
if (catalog) {
|
|
try {
|
|
canonical = await admitCanonicalRequest(
|
|
client,
|
|
this.container,
|
|
definition,
|
|
definition.id,
|
|
runId
|
|
);
|
|
} catch (error) {
|
|
throw new CatalogExecutionUnavailableError(
|
|
error instanceof Error ? error.message : 'Canonical execution unavailable'
|
|
);
|
|
}
|
|
}
|
|
const snapshot =
|
|
canonical ??
|
|
backtestRequestFromDefinition(legacyDefinition(definition), {
|
|
runId,
|
|
backtestId: definition.id,
|
|
speedMultiplier: multiplier,
|
|
});
|
|
if (!canonical) {
|
|
await assertSelectedDatasetMatchesRequest(
|
|
client,
|
|
snapshot as ReturnType<typeof backtestRequestFromDefinition>
|
|
);
|
|
}
|
|
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,
|
|
canonical?.datasetHash ?? null,
|
|
]
|
|
);
|
|
// 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 this.mapRun(row);
|
|
}
|
|
|
|
/** Preview validates retained inputs without admitting work or consulting current settings. */
|
|
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;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Create a new run from original retained inputs, not today's editable template.
|
|
* Current review and retained-build checks still apply. Only execution/account
|
|
* identity and the current review reference are rebound; economics stay pinned.
|
|
*/
|
|
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 this.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.getRunResults(source.id);
|
|
const reproduced = await this.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.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;
|
|
}
|
|
|
|
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 this.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 => this.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.
|
|
}
|
|
|
|
/**
|
|
* Read saved results and verify canonical provenance and derived analytics
|
|
* against the frozen request. Recomputing statistics checks integrity; it does
|
|
* not simulate fills again. Missing canonical data must not fall back to a
|
|
* legacy result projection, which has different financial semantics.
|
|
*/
|
|
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);
|
|
}
|
|
|
|
/** Preview admission for the UI without saving a run; submission must recheck it. */
|
|
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,
|
|
this.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 methods
|
|
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,
|
|
};
|
|
}
|
|
private 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,
|
|
};
|
|
}
|
|
|
|
private getWebSocketHandler(): WebSocketHandler | null {
|
|
// Try to get from global if not already set
|
|
this.wsHandler ??= getWebSocketHandler();
|
|
return this.wsHandler;
|
|
}
|
|
|
|
private 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',
|
|
};
|
|
}
|