728 lines
28 KiB
TypeScript
728 lines
28 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import type { PoolClient, QueryResultRow } from 'pg';
|
|
import { z } from 'zod';
|
|
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
|
import { canonicalStrategyExecution } from '@stock-bot/stock-config/canonical-research';
|
|
import type {
|
|
CostSensitivityInput,
|
|
WorkbenchExperimentDetail,
|
|
WorkbenchExperimentPreview,
|
|
WorkbenchExperimentRetryResult,
|
|
} from '@stock-bot/stock-config/cost-sensitivity';
|
|
import type {
|
|
ExperimentCounts,
|
|
ExperimentDetail,
|
|
ExperimentInput,
|
|
ExperimentPreview,
|
|
ExperimentSummary,
|
|
ExperimentTrial,
|
|
ExperimentTrialRetry,
|
|
} from '@stock-bot/stock-config/experiments';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
|
import { admitCanonicalRequest, readCanonicalDataset } from './canonical-research.service';
|
|
import {
|
|
buildCostSensitivityPreview,
|
|
parseCostSensitivityInput,
|
|
parseCostSensitivitySubmission,
|
|
retainedWorkbenchPreview,
|
|
workbenchTrialRequest,
|
|
} from './cost-sensitivity-input';
|
|
import { compareExperiments, parseExperimentComparison } from './experiment-comparison';
|
|
import {
|
|
buildExperimentPreview,
|
|
ExperimentError,
|
|
experimentHash,
|
|
experimentId,
|
|
experimentReceipt,
|
|
parseExperimentInput,
|
|
parseExperimentSubmission,
|
|
PREVIEW_RUN_ID,
|
|
} from './experiment-input';
|
|
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
|
import {
|
|
lockExperimentResearchAgent,
|
|
lockResearchAgent,
|
|
verifyCandidateGrant,
|
|
} from './research-agent-budget';
|
|
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
|
import { StrategyCatalogError } from './strategy-catalog.service';
|
|
import { parseChronologicalValidation, prepareChronologicalValidation } from './validation-preview';
|
|
|
|
interface Query {
|
|
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
|
}
|
|
const equal = (left: unknown, right: unknown) =>
|
|
left !== undefined &&
|
|
right !== undefined &&
|
|
canonicalStrategyJson(left) === canonicalStrategyJson(right);
|
|
const metricsSchema = z
|
|
.object({
|
|
totalReturn: z.number().finite().nullable(),
|
|
cagr: z.number().finite().nullable(),
|
|
maxDrawdown: z.number().finite().nullable(),
|
|
exposureTime: z.number().finite().nullable(),
|
|
volatility: z.number().finite().nullable(),
|
|
downsideDeviation: z.number().finite().nullable(),
|
|
sharpeRatio: z.number().finite().nullable(),
|
|
sortinoRatio: z.number().finite().nullable(),
|
|
var95: z.number().finite().nullable(),
|
|
cvar95: z.number().finite().nullable(),
|
|
var99: z.number().finite().nullable(),
|
|
alpha: z.null(),
|
|
beta: z.null(),
|
|
informationRatio: z.null(),
|
|
roundTripCount: z.null(),
|
|
winRate: z.null(),
|
|
profitFactor: z.null(),
|
|
avgWin: z.null(),
|
|
avgLoss: z.null(),
|
|
})
|
|
.strict();
|
|
const reasons = z.enum([
|
|
'nonpositive-baseline',
|
|
'negative-terminal-equity',
|
|
'zero-duration',
|
|
'nonfinite-result',
|
|
'undefined-period-return',
|
|
'insufficient-periods',
|
|
'missing-risk-free',
|
|
'missing-benchmark',
|
|
'zero-variance',
|
|
'zero-downside-deviation',
|
|
'unsupported-round-trips',
|
|
]);
|
|
const unavailableSchema = z.record(metricsSchema.keyof(), reasons);
|
|
const summaryColumns = `CASE WHEN e.preview->>'version'='cost-sensitivity-preview/v1' THEN 'cost-sensitivity' ELSE 'parameters' END AS kind,e.id,e.name,e.backtest_id,e.created_at,e.cancel_requested,e.preview_hash,
|
|
jsonb_array_length(e.preview->'candidates') AS trial_count,
|
|
e.preview#>>'{request,datasetHash}' AS dataset_hash,
|
|
e.preview#>>'{request,strategy,versionId}' AS strategy_version_id,
|
|
(SELECT jsonb_object_agg(status, n) FROM (SELECT status,count(*) AS n FROM runs WHERE experiment_id=e.id GROUP BY status) counts) AS counts`;
|
|
const summary = (row: QueryResultRow): ExperimentSummary => ({
|
|
id: row.id,
|
|
kind: row.kind ?? 'parameters',
|
|
name: row.name,
|
|
backtestId: row.backtest_id,
|
|
createdAt: new Date(row.created_at).toISOString(),
|
|
cancelRequested: row.cancel_requested,
|
|
trialCount: Number(row.trial_count),
|
|
datasetHash: row.dataset_hash,
|
|
strategyVersionId: row.strategy_version_id,
|
|
previewHash: row.preview_hash,
|
|
counts: Object.fromEntries(
|
|
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
|
status,
|
|
Number(row.counts?.[status] ?? 0),
|
|
])
|
|
) as ExperimentCounts,
|
|
});
|
|
|
|
/** The manifest receipt and all durable children commit together; the existing worker owns execution. */
|
|
export class ExperimentsService {
|
|
private readonly database;
|
|
constructor(private readonly container: IServiceContainer) {
|
|
this.database = requireServices(container, 'postgres').postgres;
|
|
}
|
|
async preview(raw: unknown, principal = 'operator'): Promise<ExperimentPreview> {
|
|
const input = parseExperimentInput(raw);
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, principal);
|
|
return this.lockedPreview(client, input, principal);
|
|
});
|
|
}
|
|
async previewCosts(raw: unknown, principal = 'operator') {
|
|
const input = parseCostSensitivityInput(raw);
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, principal);
|
|
return this.lockedCostPreview(client, input, principal);
|
|
});
|
|
}
|
|
private async lockedCostPreview(
|
|
client: PoolClient,
|
|
input: CostSensitivityInput,
|
|
principal = 'operator'
|
|
) {
|
|
const source = await this.lockedPreview(
|
|
client,
|
|
{
|
|
backtestId: input.backtestId,
|
|
name: input.name,
|
|
grid: {},
|
|
...(input.candidate ? { candidate: input.candidate } : {}),
|
|
},
|
|
principal
|
|
);
|
|
return buildCostSensitivityPreview(input, source);
|
|
}
|
|
async previewValidation(raw: unknown, principal = 'operator') {
|
|
const input = parseChronologicalValidation(raw);
|
|
const { recipe: _recipe, ...sourceInput } = input;
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, principal);
|
|
const source = await this.lockedPreview(client, sourceInput, principal);
|
|
const dataset = await readCanonicalDataset(client, source.request.datasetHash);
|
|
return prepareChronologicalValidation(input, source, dataset).preview;
|
|
});
|
|
}
|
|
async lockedPreview(
|
|
client: PoolClient,
|
|
input: ExperimentInput,
|
|
principal = 'operator'
|
|
): Promise<ExperimentPreview> {
|
|
const parent = (
|
|
await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId])
|
|
).rows[0];
|
|
if (!parent) {
|
|
throw new ExperimentError(404, 'Backtest not found');
|
|
}
|
|
if (parent.archived_at !== null) {
|
|
throw new ExperimentError(409, 'Restore the archived backtest before creating an experiment');
|
|
}
|
|
if (!parent.strategy_version_id) {
|
|
throw new ExperimentError(409, 'Experiments require a retained canonical built-in template');
|
|
}
|
|
let request;
|
|
try {
|
|
request = await admitCanonicalRequest(
|
|
client,
|
|
this.container,
|
|
{
|
|
name: parent.name,
|
|
strategyVersionId: parent.strategy_version_id,
|
|
strategyParameters: parent.strategy_parameters,
|
|
symbols: parent.symbols,
|
|
startDate: parent.start_date,
|
|
endDate: parent.end_date,
|
|
initialCapital: Number(parent.initial_capital),
|
|
config: parent.config,
|
|
},
|
|
input.backtestId,
|
|
PREVIEW_RUN_ID,
|
|
input.candidate
|
|
);
|
|
} catch (cause) {
|
|
if (
|
|
cause instanceof HistoricalDataRequestError ||
|
|
cause instanceof StrategyCatalogError ||
|
|
cause instanceof z.ZodError
|
|
) {
|
|
throw new ExperimentError(409, `Canonical experiment unavailable: ${cause.message}`);
|
|
}
|
|
if (
|
|
cause &&
|
|
typeof cause === 'object' &&
|
|
'code' in cause &&
|
|
['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code))
|
|
) {
|
|
throw new ExperimentError(409, 'The canonical build is not installed');
|
|
}
|
|
throw cause;
|
|
}
|
|
await verifyCandidateGrant(client, request, principal);
|
|
return buildExperimentPreview(
|
|
input,
|
|
request,
|
|
(await readCanonicalDataset(client, request.datasetHash)).manifest
|
|
);
|
|
}
|
|
async submit(raw: unknown, actor: { principal: string; key: string }): Promise<ExperimentDetail> {
|
|
const detail = await this.submitWorkbench(raw, actor, 'parameters');
|
|
return this.parameterDetail(detail);
|
|
}
|
|
async submitCosts(
|
|
raw: unknown,
|
|
actor: { principal: string; key: string }
|
|
): Promise<WorkbenchExperimentDetail> {
|
|
return this.submitWorkbench(raw, actor, 'cost-sensitivity');
|
|
}
|
|
private async submitWorkbench(
|
|
raw: unknown,
|
|
actor: { principal: string; key: string },
|
|
kind: 'parameters' | 'cost-sensitivity'
|
|
): Promise<WorkbenchExperimentDetail> {
|
|
const submission =
|
|
kind === 'parameters' ? parseExperimentSubmission(raw) : parseCostSensitivitySubmission(raw);
|
|
const receipt = experimentReceipt(actor);
|
|
const { previewHash, ...input } = submission;
|
|
const hash = experimentHash({
|
|
version: 1,
|
|
operation: kind === 'parameters' ? 'create-experiment' : 'create-cost-sensitivity',
|
|
submission,
|
|
});
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, receipt.principal);
|
|
const replay = async () => {
|
|
const row = (
|
|
await client.query(
|
|
'SELECT id,submission_hash FROM research_experiments WHERE submission_principal=$1 AND submission_key=$2',
|
|
[receipt.principal, receipt.key]
|
|
)
|
|
).rows[0];
|
|
if (row && row.submission_hash !== hash) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Idempotency-Key already belongs to a different experiment intent'
|
|
);
|
|
}
|
|
return row ? this.readDetail(client, row.id) : null;
|
|
};
|
|
const previous = await replay();
|
|
if (previous) {
|
|
return previous;
|
|
}
|
|
// Serialize same-parent admissions, then recheck accepted receipts before current eligibility.
|
|
await client.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [input.backtestId]);
|
|
const concurrent = await replay();
|
|
if (concurrent) {
|
|
return concurrent;
|
|
}
|
|
const preview: WorkbenchExperimentPreview =
|
|
'scenarios' in input
|
|
? await this.lockedCostPreview(client, input, receipt.principal)
|
|
: await this.lockedPreview(client, input, receipt.principal);
|
|
if (preview.previewHash !== previewHash) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Experiment preview is stale; preview the current inputs again'
|
|
);
|
|
}
|
|
const experimentId = randomUUID();
|
|
const inserted = await client.query(
|
|
`INSERT INTO research_experiments (id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING id`,
|
|
[
|
|
experimentId,
|
|
input.backtestId,
|
|
input.name,
|
|
preview,
|
|
previewHash,
|
|
receipt.principal,
|
|
receipt.key,
|
|
hash,
|
|
]
|
|
);
|
|
if (!inserted.rows.length) {
|
|
const winner = await replay();
|
|
if (!winner) {
|
|
throw new Error('Concurrent experiment receipt disappeared');
|
|
}
|
|
return winner;
|
|
}
|
|
let runNumber = Number(
|
|
(
|
|
await client.query(
|
|
'SELECT COALESCE(MAX(run_number),0) AS n FROM runs WHERE backtest_id=$1',
|
|
[input.backtestId]
|
|
)
|
|
).rows[0].n
|
|
);
|
|
for (const candidate of preview.candidates) {
|
|
const runId = randomUUID();
|
|
const request = workbenchTrialRequest(preview, candidate, runId);
|
|
await client.query(
|
|
`INSERT INTO runs (id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
|
VALUES ($1,$2,$3,'pending',NULL,$4,$5,$6,$7,$8)`,
|
|
[
|
|
runId,
|
|
input.backtestId,
|
|
++runNumber,
|
|
request,
|
|
request.datasetHash,
|
|
experimentId,
|
|
candidate.trialKey,
|
|
candidate.index,
|
|
]
|
|
);
|
|
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
|
}
|
|
return this.readDetail(client, experimentId);
|
|
});
|
|
}
|
|
async list(backtestId?: string): Promise<ExperimentSummary[]> {
|
|
if (backtestId !== undefined) {
|
|
experimentId(backtestId);
|
|
}
|
|
const rows = await this.database.query(
|
|
`SELECT ${summaryColumns} FROM research_experiments e
|
|
WHERE e.validation_phase IS NULL ${backtestId === undefined ? '' : 'AND e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
|
backtestId === undefined ? [] : [backtestId]
|
|
);
|
|
return rows.rows.map(summary);
|
|
}
|
|
async compare(raw: unknown) {
|
|
const input = parseExperimentComparison(raw);
|
|
return this.database.transaction(async client => {
|
|
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
|
const rows = (
|
|
await client.query(
|
|
'SELECT id,validation_phase FROM research_experiments WHERE id=ANY($1::uuid[])',
|
|
[[input.leftId, input.rightId]]
|
|
)
|
|
).rows;
|
|
if (rows.length !== 2) {
|
|
throw new ExperimentError(404, 'Comparison experiment not found');
|
|
}
|
|
if (rows.some(row => row.validation_phase !== null)) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Compare standalone experiments; chronological phases have their own workflow'
|
|
);
|
|
}
|
|
const left = await this.readDetail(client, input.leftId),
|
|
right = await this.readDetail(client, input.rightId);
|
|
return compareExperiments(input, [left, right]);
|
|
});
|
|
}
|
|
async get(id: string): Promise<WorkbenchExperimentDetail> {
|
|
experimentId(id);
|
|
return this.readDetail(this.database, id);
|
|
}
|
|
async cancel(id: string): Promise<WorkbenchExperimentDetail> {
|
|
experimentId(id);
|
|
return this.database.transaction(async client => {
|
|
const row = (
|
|
await client.query(
|
|
'UPDATE research_experiments SET cancel_requested=TRUE WHERE id=$1 RETURNING id',
|
|
[id]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new ExperimentError(404, 'Experiment not found');
|
|
}
|
|
await client.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 experiment_id=$1 AND status IN ('pending','running','paused')`,
|
|
[id]
|
|
);
|
|
return this.readDetail(client, id);
|
|
});
|
|
}
|
|
async listTrialRetries(id: string, runId: string): Promise<ExperimentTrialRetry[]> {
|
|
experimentId(id);
|
|
experimentId(runId);
|
|
const experiment = (
|
|
await this.database.query('SELECT id FROM research_experiments WHERE id=$1', [id])
|
|
).rows[0];
|
|
if (!experiment) {
|
|
throw new ExperimentError(404, 'Experiment not found');
|
|
}
|
|
const run = (await this.database.query('SELECT experiment_id FROM runs WHERE id=$1', [runId]))
|
|
.rows[0];
|
|
if (!run) {
|
|
throw new ExperimentError(404, 'Trial run not found');
|
|
}
|
|
if (run.experiment_id !== id) {
|
|
throw new ExperimentError(409, 'Run does not belong to this experiment');
|
|
}
|
|
return (
|
|
await this.database.query(
|
|
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.run_id=$1 ORDER BY h.retry_number`,
|
|
[runId]
|
|
)
|
|
).rows.map(mapExperimentRetry);
|
|
}
|
|
async retryTrial(
|
|
id: string,
|
|
runId: string,
|
|
raw: unknown,
|
|
actor: { principal: string; key: string }
|
|
): Promise<WorkbenchExperimentRetryResult> {
|
|
experimentId(id);
|
|
experimentId(runId);
|
|
const input = parseExperimentRetry(raw);
|
|
const receipt = experimentReceipt(actor);
|
|
const hash = experimentHash({
|
|
version: 1,
|
|
operation: 'retry-experiment-trial',
|
|
experimentId: id,
|
|
runId,
|
|
...input,
|
|
});
|
|
return this.database.transaction(async client => {
|
|
await lockResearchAgent(client, receipt.principal);
|
|
const replay = async (): Promise<WorkbenchExperimentRetryResult | null> => {
|
|
const saved = (
|
|
await client.query(
|
|
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.principal=$1 AND h.submission_key=$2`,
|
|
[receipt.principal, receipt.key]
|
|
)
|
|
).rows[0];
|
|
if (!saved) {
|
|
return null;
|
|
}
|
|
if (saved.submission_hash !== hash) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Idempotency-Key already belongs to a different trial retry intent'
|
|
);
|
|
}
|
|
return {
|
|
retry: mapExperimentRetry(saved),
|
|
experiment: await this.readDetail(client, saved.experiment_id),
|
|
};
|
|
};
|
|
const previous = await replay();
|
|
if (previous) {
|
|
return previous;
|
|
}
|
|
await lockExperimentResearchAgent(client, id, receipt.principal);
|
|
// Same ordering as admission, followed by the existing original-family verification lock.
|
|
const parent = (
|
|
await client.query(
|
|
'SELECT id,archived_at FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=$1) FOR UPDATE',
|
|
[id]
|
|
)
|
|
).rows[0];
|
|
const concurrent = await replay();
|
|
if (concurrent) {
|
|
return concurrent;
|
|
}
|
|
if (!parent) {
|
|
throw new ExperimentError(404, 'Experiment not found');
|
|
}
|
|
const experiment = (
|
|
await client.query('SELECT * FROM research_experiments WHERE id=$1 FOR UPDATE', [id])
|
|
).rows[0];
|
|
const run = (
|
|
await client.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2 FOR UPDATE', [
|
|
runId,
|
|
id,
|
|
])
|
|
).rows[0];
|
|
if (!run) {
|
|
const exists = (await client.query('SELECT id FROM runs WHERE id=$1', [runId])).rows.length;
|
|
throw new ExperimentError(
|
|
exists ? 409 : 404,
|
|
exists ? 'Run does not belong to this experiment' : 'Trial run not found'
|
|
);
|
|
}
|
|
if (
|
|
parent.archived_at !== null ||
|
|
experiment.cancel_requested ||
|
|
run.cancel_requested ||
|
|
run.status !== 'failed'
|
|
) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'Retry requires an active backtest and a failed, uncancelled experiment trial'
|
|
);
|
|
}
|
|
if (
|
|
run.attempt_number !== input.expectedAttemptNumber ||
|
|
run.manual_retry_count !== input.expectedRetryCount
|
|
) {
|
|
throw new ExperimentError(
|
|
409,
|
|
'The trial failure changed; refresh before requesting a new retry'
|
|
);
|
|
}
|
|
if (run.manual_retry_count === 2147483647 || run.attempt_number === 2147483647) {
|
|
throw new ExperimentError(409, 'Trial attempt or retry counter is exhausted');
|
|
}
|
|
if (
|
|
(await client.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [runId])).rows.length
|
|
) {
|
|
throw new ExperimentError(409, 'A run with a retained result cannot be retried');
|
|
}
|
|
const preview = retainedWorkbenchPreview(experiment.preview);
|
|
const candidate = preview.candidates[run.trial_index];
|
|
if (!candidate || candidate.trialKey !== run.trial_key || run.backtest_id !== parent.id) {
|
|
throw new ExperimentError(409, 'Trial does not match its retained experiment candidate');
|
|
}
|
|
const request = workbenchTrialRequest(preview, candidate, runId);
|
|
if (!equal(request, run.request_snapshot) || request.datasetHash !== run.dataset_hash) {
|
|
throw new ExperimentError(409, 'Trial frozen request does not match its experiment');
|
|
}
|
|
let reviewId;
|
|
try {
|
|
reviewId = await verifyReproductionInputs(client, this.container, request);
|
|
} catch (error) {
|
|
if (error instanceof RunReproductionError) {
|
|
throw new ExperimentError(409, error.message);
|
|
}
|
|
throw error;
|
|
}
|
|
const retryId = randomUUID();
|
|
const inserted = await client.query(
|
|
`INSERT INTO experiment_trial_retries
|
|
(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,
|
|
started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
|
|
SELECT $1,experiment_id,id,trial_key,manual_retry_count+1,attempt_number,attempt_id,error,progress,current_simulation_date,
|
|
started_at,completed_at,paused_at,updated_at,$3,$4,$5,$6 FROM runs WHERE id=$2
|
|
ON CONFLICT (principal,submission_key) DO NOTHING RETURNING id`,
|
|
[retryId, runId, receipt.principal, reviewId, receipt.key, hash]
|
|
);
|
|
if (!inserted.rows.length) {
|
|
const winner = await replay();
|
|
if (!winner) {
|
|
throw new Error('Concurrent retry receipt disappeared');
|
|
}
|
|
return winner;
|
|
}
|
|
await client.query(
|
|
`UPDATE runs SET status='pending',manual_retry_count=manual_retry_count+1,
|
|
attempt_id=NULL,lease_expires_at=NULL,error=NULL,current_simulation_date=NULL,started_at=NULL,completed_at=NULL,paused_at=NULL,
|
|
progress=0,updated_at=NOW() WHERE id=$1`,
|
|
[runId]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO backtest_dispatch (run_id,next_publish_at) VALUES ($1,NOW())
|
|
ON CONFLICT (run_id) DO UPDATE SET next_publish_at=NOW()`,
|
|
[runId]
|
|
);
|
|
const saved = (
|
|
await client.query(`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.id=$1`, [
|
|
retryId,
|
|
])
|
|
).rows[0];
|
|
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
|
});
|
|
}
|
|
private parameterDetail(detail: WorkbenchExperimentDetail): ExperimentDetail {
|
|
if (detail.preview.version !== 'research-experiment-preview/v1') {
|
|
throw new Error('Chronological validation requires a parameter experiment');
|
|
}
|
|
return detail as ExperimentDetail;
|
|
}
|
|
async readParameterDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
|
return this.parameterDetail(await this.readDetail(database, id));
|
|
}
|
|
async readDetail(database: Query, id: string): Promise<WorkbenchExperimentDetail> {
|
|
const row = (
|
|
await database.query(
|
|
`SELECT ${summaryColumns},e.preview,(to_jsonb(e) ? 'validation_phase' AND to_jsonb(e)->'validation_phase' = 'null'::jsonb) AS standalone FROM research_experiments e WHERE e.id=$1`,
|
|
[id]
|
|
)
|
|
).rows[0];
|
|
if (!row) {
|
|
throw new ExperimentError(404, 'Experiment not found');
|
|
}
|
|
const preview = retainedWorkbenchPreview(row.preview);
|
|
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
|
const runs = (
|
|
await database.query(
|
|
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.attempt_number,r.manual_retry_count,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
|
|
br.canonical_result->>'kind' AS result_kind,br.canonical_result->>'status' AS result_status,
|
|
br.canonical_result->>'runId' AS result_run_id,br.canonical_result->>'backtestId' AS result_backtest_id,
|
|
br.canonical_result->>'financialEngine' AS financial_engine,br.canonical_result->>'strategyExecution' AS strategy_execution,
|
|
br.canonical_result->'request' AS result_request,br.canonical_result#>'{analytics,policy}' AS analytics_policy,
|
|
br.canonical_result#>'{analytics,version}' AS analytics_version,
|
|
br.canonical_result#>'{financial,identity}' AS financial_identity,br.canonical_result#>'{financial,policy}' AS financial_policy,
|
|
br.canonical_result#>'{analytics,metrics}' AS metrics,br.canonical_result#>'{analytics,unavailable}' AS unavailable,
|
|
br.canonical_result#>'{financial,limitations}' AS limitations,br.canonical_result#>'{financial,modelLimitations}' AS model_limitations
|
|
FROM runs r LEFT JOIN backtest_results br ON br.run_id=r.id WHERE r.experiment_id=$1 ORDER BY r.trial_index`,
|
|
[id]
|
|
)
|
|
).rows;
|
|
const trials = preview.candidates.map(candidate => {
|
|
const run = runs.find(item => item.trial_index === candidate.index);
|
|
const trial: ExperimentTrial & { costs?: unknown } = {
|
|
...candidate,
|
|
runId: run?.id ?? null,
|
|
attemptNumber: run ? Number(run.attempt_number) : 0,
|
|
retryCount: run ? Number(run.manual_retry_count) : 0,
|
|
status: run?.status ?? 'missing',
|
|
progress: Number(run?.progress ?? 0),
|
|
cancelRequested: run?.cancel_requested ?? false,
|
|
error: run?.error ?? null,
|
|
comparable: false,
|
|
diagnostic: null,
|
|
metrics: null,
|
|
unavailable: null,
|
|
limitations: [],
|
|
};
|
|
if (!run) {
|
|
trial.diagnostic = 'Expected trial run is missing';
|
|
return trial;
|
|
}
|
|
const expected = workbenchTrialRequest(preview, candidate, run.id);
|
|
if (
|
|
run.trial_key !== candidate.trialKey ||
|
|
run.backtest_id !== preview.input.backtestId ||
|
|
run.dataset_hash !== expected.datasetHash ||
|
|
!equal(run.request_snapshot, expected)
|
|
) {
|
|
trial.diagnostic = 'Retained run inputs do not match the frozen experiment';
|
|
return trial;
|
|
}
|
|
if (run.status !== 'completed') {
|
|
trial.diagnostic = run.error ?? `Trial is ${run.status}`;
|
|
return trial;
|
|
}
|
|
const expectedPolicy: CanonicalBacktestAnalytics['policy'] = {
|
|
...expected.analyticsPolicy,
|
|
calendarId: expected.policy.matching.risk.ledger.riskSession.calendarId,
|
|
calendarRevision: expected.policy.matching.risk.ledger.riskSession.calendarRevision,
|
|
sampling: 'account-boundary-after-observations-v1',
|
|
marks: 'last-available-no-per-session-freshness-certification',
|
|
returnUnit: 'fraction',
|
|
variance: 'sample-n-minus-one',
|
|
riskFreeConversion: 'annual-rate-divided-by-periods-per-year',
|
|
downside: 'full-series-rms-relative-to-risk-free',
|
|
partialPeriods: 'visible-excluded-from-periodic-statistics',
|
|
drawdown: 'session-end-and-terminal-sampled',
|
|
exposureBasis: 'elapsed-calendar-time',
|
|
cagrBasis: 'elapsed-calendar-days-365',
|
|
zeroTerminalCagr: 'negative-one-for-positive-elapsed-time',
|
|
};
|
|
const metrics = metricsSchema.safeParse(run.metrics);
|
|
const unavailable = unavailableSchema.safeParse(run.unavailable);
|
|
if (
|
|
run.result_kind !== 'canonical-result/v1' ||
|
|
run.result_status !== 'completed' ||
|
|
run.result_run_id !== run.id ||
|
|
run.result_backtest_id !== expected.backtestId ||
|
|
run.financial_engine !== 'rust' ||
|
|
run.strategy_execution !== canonicalStrategyExecution(expected) ||
|
|
!equal(run.result_request, expected) ||
|
|
run.analytics_version !== 1 ||
|
|
!equal(run.analytics_policy, expectedPolicy) ||
|
|
!equal(run.financial_identity, {
|
|
version: 1,
|
|
sessionId: run.id,
|
|
datasetHash: expected.datasetHash,
|
|
}) ||
|
|
!equal(run.financial_policy, expected.policy) ||
|
|
!metrics.success ||
|
|
!unavailable.success ||
|
|
!Array.isArray(run.model_limitations) ||
|
|
run.model_limitations.some((item: unknown) => typeof item !== 'string') ||
|
|
!Array.isArray(run.limitations) ||
|
|
run.limitations.some((item: unknown) => typeof item !== 'string')
|
|
) {
|
|
trial.diagnostic = 'Completed result provenance or metrics are unavailable or inconsistent';
|
|
return trial;
|
|
}
|
|
if (
|
|
Object.entries(metrics.data).some(([key, value]) =>
|
|
value === null
|
|
? !Object.hasOwn(unavailable.data, key)
|
|
: Object.hasOwn(unavailable.data, key)
|
|
)
|
|
) {
|
|
trial.diagnostic = 'Completed result metric availability is inconsistent';
|
|
return trial;
|
|
}
|
|
trial.comparable = true;
|
|
trial.metrics = metrics.data;
|
|
trial.unavailable = unavailable.data;
|
|
trial.limitations = [...run.limitations, ...run.model_limitations];
|
|
return trial;
|
|
});
|
|
const counts = summary({ ...row, counts: {} }).counts;
|
|
for (const run of runs) {
|
|
if (Object.hasOwn(counts, run.status)) {
|
|
counts[run.status as keyof ExperimentCounts]++;
|
|
}
|
|
}
|
|
return {
|
|
...summary(row),
|
|
standalone: row.standalone === true,
|
|
counts,
|
|
preview,
|
|
trials,
|
|
} as WorkbenchExperimentDetail;
|
|
}
|
|
}
|