From 6f64ef62ba233b293ea1374c753bd0b467703792 Mon Sep 17 00:00:00 2001 From: Boki Date: Sat, 24 Oct 2026 10:33:05 -0400 Subject: [PATCH] feat(research): add retained-input parameter sweep workbench --- apps/stock/config/package.json | 4 + .../stock/config/src/contracts/experiments.ts | 97 +++ .../src/migrations/migration-runner.ts | 3 +- .../stock/web-api/src/routes/create-routes.ts | 2 + .../web-api/src/routes/experiments.routes.ts | 81 ++ .../web-api/src/services/experiment-input.ts | 180 +++++ .../src/services/experiments.service.ts | 420 ++++++++++ apps/stock/web-app/src/app/App.tsx | 5 + .../web-app/src/components/layout/Layout.tsx | 3 + .../backtest/BacktestDetailPageV2.tsx | 8 + .../experiments/ExperimentDetailPage.tsx | 237 ++++++ .../experiments/ExperimentListPage.tsx | 116 +++ .../components/ExperimentCounts.tsx | 22 + .../components/ExperimentEditor.tsx | 333 ++++++++ .../components/ExperimentInputs.tsx | 86 ++ .../web-app/src/features/experiments/index.ts | 2 + .../experiments/services/experimentApi.ts | 298 +++++++ apps/stock/web-app/src/lib/constants.ts | 1 + database/postgres/init/22-experiments.sql | 326 ++++++++ docs/development/ROADMAP.md | 20 +- docs/development/backlog/README.md | 10 +- docs/development/backlog/dependencies.mmd | 10 +- docs/development/backlog/manifest.json | 191 ++++- docs/development/backlog/tasks/R06.md | 18 +- docs/development/backlog/tasks/R07.md | 16 +- test/e2e/fixture.ts | 2 + test/e2e/workbench.test.ts | 184 +++++ test/integration/experiments-api.test.ts | 347 +++++++++ .../integration/experiments-contracts.test.ts | 24 + test/integration/experiments-ui.test.tsx | 732 ++++++++++++++++++ .../canonical-durable-backtest.test.ts | 1 + test/postgres/canonical-research.test.ts | 1 + test/postgres/catalog-backtest-drafts.test.ts | 1 + test/postgres/dataset-catalog.test.ts | 1 + test/postgres/durable-backtest.test.ts | 1 + test/postgres/experiments.test.ts | 712 +++++++++++++++++ test/postgres/migration-runner.test.ts | 1 + test/postgres/research-retention.test.ts | 3 +- .../research-runtime-isolation.test.ts | 1 + test/postgres/research-workspace.test.ts | 1 + test/postgres/run-reproduction.test.ts | 2 +- 41 files changed, 4469 insertions(+), 34 deletions(-) create mode 100644 apps/stock/config/src/contracts/experiments.ts create mode 100644 apps/stock/web-api/src/routes/experiments.routes.ts create mode 100644 apps/stock/web-api/src/services/experiment-input.ts create mode 100644 apps/stock/web-api/src/services/experiments.service.ts create mode 100644 apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx create mode 100644 apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx create mode 100644 apps/stock/web-app/src/features/experiments/components/ExperimentCounts.tsx create mode 100644 apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx create mode 100644 apps/stock/web-app/src/features/experiments/components/ExperimentInputs.tsx create mode 100644 apps/stock/web-app/src/features/experiments/index.ts create mode 100644 apps/stock/web-app/src/features/experiments/services/experimentApi.ts create mode 100644 database/postgres/init/22-experiments.sql create mode 100644 test/integration/experiments-api.test.ts create mode 100644 test/integration/experiments-contracts.test.ts create mode 100644 test/integration/experiments-ui.test.tsx create mode 100644 test/postgres/experiments.test.ts diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index ddd145a0..881c32fa 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -28,6 +28,10 @@ "./research": { "types": "./dist/contracts/research.d.ts", "default": "./dist/contracts/research.js" + }, + "./experiments": { + "types": "./dist/contracts/experiments.d.ts", + "default": "./dist/contracts/experiments.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/experiments.ts b/apps/stock/config/src/contracts/experiments.ts new file mode 100644 index 00000000..957c4542 --- /dev/null +++ b/apps/stock/config/src/contracts/experiments.ts @@ -0,0 +1,97 @@ +/** Bounded retained-input experiments use the existing canonical runner and results. */ +import { z } from 'zod'; +import type { + CanonicalBacktestAnalytics, + HistoricalDatasetManifestV2, + StrategyParameterValue, +} from '@stock-bot/types'; +import type { CanonicalRunRequest } from './canonical-research'; + +/** Admission bound for atomic expansion, not a promise of concurrent execution. */ +export const MAX_EXPERIMENT_TRIALS = 100; +const value = z.union([z.string(), z.number().finite(), z.boolean()]); +// Zod's record parser drops __proto__; reject raw keys before parsing so an +// invalid sweep cannot silently become the empty-grid baseline trial. +const grid = z.preprocess( + (input, context) => { + if ( + input && + typeof input === 'object' && + Object.keys(input).some(key => ['__proto__', 'prototype', 'constructor'].includes(key)) + ) { + context.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Invalid parameter name', + fatal: true, + }); + return z.NEVER; + } + return input; + }, + z.record(z.array(value).min(1).max(MAX_EXPERIMENT_TRIALS)) +); +export const experimentInputSchema = z + .object({ + backtestId: z.string().uuid(), + name: z.string().trim().min(1), + grid, + }) + .strict(); +export const experimentSubmissionSchema = experimentInputSchema.extend({ + previewHash: z.string().regex(/^[a-f0-9]{64}$/), +}); +export type ExperimentInput = z.infer; +export type ExperimentSubmission = z.infer; +export interface ExperimentCandidate { + /** Zero-based deterministic position in the frozen grid. */ + index: number; + trialKey: string; + parameters: Record; +} +export interface ExperimentPreview { + version: 'research-experiment-preview/v1'; + previewHash: string; + input: ExperimentInput; + /** Template snapshot with a fixed preview run identity; never executed as-is. */ + request: CanonicalRunRequest; + dataset: HistoricalDatasetManifestV2; + candidates: ExperimentCandidate[]; +} +export type ExperimentRunStatus = + | 'pending' + | 'running' + | 'paused' + | 'completed' + | 'failed' + | 'cancelled'; +export type ExperimentCounts = Record; +export interface ExperimentSummary { + id: string; + name: string; + backtestId: string; + createdAt: string; + cancelRequested: boolean; + /** Frozen candidate count, not merely the number of successfully joined rows. */ + trialCount: number; + counts: ExperimentCounts; + datasetHash: string; + strategyVersionId: string; + previewHash: string; +} +export interface ExperimentTrial extends ExperimentCandidate { + runId: string | null; + status: ExperimentRunStatus | 'missing'; + progress: number; + cancelRequested: boolean; + error: string | null; + /** False prevents ranking a result whose retained inputs disagree with its experiment. */ + comparable: boolean; + diagnostic: string | null; + metrics: CanonicalBacktestAnalytics['metrics'] | null; + unavailable: CanonicalBacktestAnalytics['unavailable'] | null; + limitations: string[]; +} +export interface ExperimentDetail extends ExperimentSummary { + preview: ExperimentPreview; + trials: ExperimentTrial[]; +} diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 6cf0dc2c..7cfac425 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -61,7 +61,8 @@ export async function runMigrations(container: IServiceContainer): Promise f === '18-backtest-strategy-versions.sql' || f === '19-canonical-research.sql' || f === '20-research-workspace.sql' || - f === '21-run-reproduction.sql') + f === '21-run-reproduction.sql' || + f === '22-experiments.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index 30d0f251..5ee859f0 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -11,6 +11,7 @@ import { createBacktestRoutes } from './backtest.routes'; import { createBacktestV2Routes } from './backtests-v2.routes'; import { createDatasetRoutes } from './datasets.routes'; import { createExchangeRoutes } from './exchange.routes'; +import { createExperimentRoutes } from './experiments.routes'; import { createHealthRoutes } from './health.routes'; import { createMonitoringRoutes } from './monitoring.routes'; import { createPipelineRoutes } from './pipeline.routes'; @@ -53,6 +54,7 @@ export function createRoutes( app.route('/', createDatasetRoutes(container)); app.route('/', createStrategyRoutes(container)); app.route('/', createResearchRoutes(container)); + app.route('/', createExperimentRoutes(container)); return app; } diff --git a/apps/stock/web-api/src/routes/experiments.routes.ts b/apps/stock/web-api/src/routes/experiments.routes.ts new file mode 100644 index 00000000..0c3227d1 --- /dev/null +++ b/apps/stock/web-api/src/routes/experiments.routes.ts @@ -0,0 +1,81 @@ +import { Hono, type MiddlewareHandler } from 'hono'; +import { z } from 'zod'; +import { getCredentialHttpPrincipal } from '@stock-bot/di'; +import { getLogger } from '@stock-bot/logger'; +import type { IServiceContainer } from '@stock-bot/services'; +import { + ExperimentError, + experimentId, + experimentReceipt, + parseExperimentInput, + parseExperimentSubmission, +} from '../services/experiment-input'; +import { ExperimentsService } from '../services/experiments.service'; + +/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */ +export function createExperimentRoutes(container: IServiceContainer) { + const app = new Hono(); + const service = new ExperimentsService(container); + const logger = getLogger('experiments-api'); + const credentials: MiddlewareHandler = async (c, next) => { + c.header('Cache-Control', 'no-store'); + if (!['GET', 'HEAD'].includes(c.req.method) && !getCredentialHttpPrincipal(c.req.raw)) { + return c.json({ error: 'Verified credential principal required' }, 401); + } + await next(); + return undefined; + }; + app.use('/api/v2/experiments', credentials); + app.use('/api/v2/experiments/*', credentials); + app.onError((error, c) => { + if (error instanceof ExperimentError) { + return c.json({ error: error.message }, error.status); + } + logger.error('Experiment operation failed', error); + return c.json({ error: 'Experiment operation unavailable' }, 500); + }); + const body = async (request: Request): Promise => { + try { + return await request.json(); + } catch { + throw new ExperimentError(400, 'Invalid JSON request'); + } + }; + app.post('/api/v2/experiments/preview', async c => { + const input = parseExperimentInput(await body(c.req.raw)); + return c.json({ preview: await service.preview(input) }); + }); + app.post('/api/v2/experiments', async c => { + const input = parseExperimentSubmission(await body(c.req.raw)); + const receipt = experimentReceipt({ + principal: getCredentialHttpPrincipal(c.req.raw) ?? '', + key: c.req.header('Idempotency-Key') ?? '', + }); + const experiment = await service.submit(input, receipt); + c.header('Location', `/api/v2/experiments/${experiment.id}`); + return c.json({ experiment }, 202); + }); + app.get('/api/v2/experiments', async c => { + const filter = c.req.query('backtestId'); + if (filter !== undefined) { + experimentId(filter); + } + return c.json({ experiments: await service.list(filter) }); + }); + app.get('/api/v2/experiments/:id', async c => + c.json({ experiment: await service.get(experimentId(c.req.param('id'))) }) + ); + app.post('/api/v2/experiments/:id/cancel', async c => { + const id = experimentId(c.req.param('id')); + if ( + !z + .object({}) + .strict() + .safeParse(await body(c.req.raw)).success + ) { + throw new ExperimentError(400, 'Cancellation accepts an empty object only'); + } + return c.json({ experiment: await service.cancel(id) }); + }); + return app; +} diff --git a/apps/stock/web-api/src/services/experiment-input.ts b/apps/stock/web-api/src/services/experiment-input.ts new file mode 100644 index 00000000..0a16ae42 --- /dev/null +++ b/apps/stock/web-api/src/services/experiment-input.ts @@ -0,0 +1,180 @@ +import { createHash } from 'node:crypto'; +import { z } from 'zod'; +import { + canonicalRunRequestSchema, + type CanonicalRunRequest, +} from '@stock-bot/stock-config/canonical-research'; +import { + experimentInputSchema, + experimentSubmissionSchema, + MAX_EXPERIMENT_TRIALS, + type ExperimentCandidate, + type ExperimentInput, + type ExperimentPreview, + type ExperimentSubmission, +} from '@stock-bot/stock-config/experiments'; +import { + assertStrategyJsonText, + builtinStrategySelectionSchema, + canonicalStrategyJson, + validateStrategyParameters, +} from '@stock-bot/stock-config/strategy'; +import type { HistoricalDatasetManifestV2 } from '@stock-bot/types'; + +export class ExperimentError extends Error { + constructor( + public readonly status: 400 | 404 | 409, + message: string + ) { + super(message); + } +} +export const PREVIEW_RUN_ID = '00000000-0000-4000-8000-000000000001'; +export const experimentHash = (value: unknown) => + createHash('sha256').update(canonicalStrategyJson(value)).digest('hex'); +export function parseExperimentInput(input: unknown): ExperimentInput { + try { + assertStrategyJsonText(input); + return experimentInputSchema.parse(input); + } catch { + throw new ExperimentError(400, 'Invalid experiment input'); + } +} +export function parseExperimentSubmission(input: unknown): ExperimentSubmission { + try { + assertStrategyJsonText(input); + return experimentSubmissionSchema.parse(input); + } catch { + throw new ExperimentError(400, 'Invalid experiment submission'); + } +} +export function experimentId(input: unknown): string { + const parsed = z.string().uuid().safeParse(input); + if (!parsed.success) { + throw new ExperimentError(400, 'Invalid experiment or backtest ID'); + } + return parsed.data; +} +export function experimentReceipt(input: { principal: string; key: string }) { + const parsed = z + .object({ + principal: z.enum(['operator', 'service']), + key: z.string().regex(/^[\x21-\x7e]{1,200}$/), + }) + .strict() + .safeParse(input); + if (!parsed.success) { + throw new ExperimentError( + 400, + 'A verified principal and visible ASCII Idempotency-Key of 1–200 characters are required' + ); + } + return parsed.data; +} +/** Parameter grids never change data, accounting, execution or analysis policy. */ +export function experimentCandidates( + input: ExperimentInput, + request: CanonicalRunRequest +): ExperimentCandidate[] { + const axes = Object.keys(input.grid).sort(); + let count = 1; + for (const name of axes) { + if ( + !Object.hasOwn(request.strategy.package.parameterSchema.properties, name) || + ['__proto__', 'constructor', 'prototype'].includes(name) + ) { + throw new ExperimentError(400, `Unknown or reserved parameter: ${name}`); + } + const values = input.grid[name] ?? []; + if (new Set(values.map(canonicalStrategyJson)).size !== values.length) { + throw new ExperimentError(400, `Duplicate values for parameter: ${name}`); + } + count *= values.length; + if (count > MAX_EXPERIMENT_TRIALS) { + throw new ExperimentError( + 400, + `An experiment may contain at most ${MAX_EXPERIMENT_TRIALS} trials` + ); + } + } + let combinations = [{ ...request.strategy.selection.parameters }]; + for (const name of axes) { + combinations = combinations.flatMap(parameters => + (input.grid[name] ?? []).map(value => ({ ...parameters, [name]: value })) + ); + } + const keys = new Set(); + return combinations.map((parameters, index) => { + try { + const validated = validateStrategyParameters(request.strategy.package, parameters); + const selection = builtinStrategySelectionSchema.parse({ + ...request.strategy.selection, + parameters: validated, + }); + const trialKey = experimentHash({ version: 1, parameters: selection.parameters }); + if (keys.has(trialKey)) { + throw new Error('Duplicate normalized parameter combination'); + } + keys.add(trialKey); + return { index, parameters: selection.parameters, trialKey }; + } catch (cause) { + throw new ExperimentError( + 400, + `Invalid parameter combination ${index + 1}: ${cause instanceof Error ? cause.message : 'validation failed'}` + ); + } + }); +} +export function buildExperimentPreview( + input: ExperimentInput, + request: CanonicalRunRequest, + dataset: HistoricalDatasetManifestV2 +): ExperimentPreview { + const manifest = { + version: 'research-experiment-preview/v1' as const, + input, + request, + dataset, + candidates: experimentCandidates(input, request), + }; + return { ...manifest, previewHash: experimentHash(manifest) }; +} +export function experimentTrialRequest( + preview: ExperimentPreview, + candidate: ExperimentCandidate, + runId: string +): CanonicalRunRequest { + const request = structuredClone(preview.request); + request.runId = runId; + request.policy.matching.risk.ledger.sessionId = runId; + request.policy.matching.risk.ledger.accountId = `research:${runId}`; + return canonicalRunRequestSchema.parse({ + ...request, + strategy: { + ...request.strategy, + selection: { ...request.strategy.selection, parameters: candidate.parameters }, + }, + }); +} +/** Fail closed for corrupt saved manifests; do not relabel storage failures as user errors. */ +export function retainedExperimentPreview(value: unknown): ExperimentPreview { + const preview = value as ExperimentPreview; + const input = experimentInputSchema.parse(preview.input); + const request = canonicalRunRequestSchema.parse(preview.request); + if (request.runId !== PREVIEW_RUN_ID || request.backtestId !== input.backtestId) { + throw new Error('Retained experiment request identity mismatch'); + } + if (!preview.dataset || preview.dataset.hash !== request.datasetHash) { + throw new Error('Retained experiment dataset identity mismatch'); + } + let expected; + try { + expected = buildExperimentPreview(input, request, preview.dataset); + } catch { + throw new Error('Retained experiment candidates failed integrity validation'); + } + if (canonicalStrategyJson(preview) !== canonicalStrategyJson(expected)) { + throw new Error('Retained experiment preview integrity failure'); + } + return expected; +} diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts new file mode 100644 index 00000000..1209b3c2 --- /dev/null +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -0,0 +1,420 @@ +import { randomUUID } from 'node:crypto'; +import type { PoolClient, QueryResultRow } from 'pg'; +import { z } from 'zod'; +import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import type { + ExperimentCounts, + ExperimentDetail, + ExperimentInput, + ExperimentPreview, + ExperimentSummary, + ExperimentTrial, +} 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 { + buildExperimentPreview, + ExperimentError, + experimentHash, + experimentId, + experimentReceipt, + experimentTrialRequest, + parseExperimentInput, + parseExperimentSubmission, + PREVIEW_RUN_ID, + retainedExperimentPreview, +} from './experiment-input'; +import { StrategyCatalogError } from './strategy-catalog.service'; + +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 = `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, + 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): Promise { + const input = parseExperimentInput(raw); + return this.database.transaction(client => this.lockedPreview(client, input)); + } + private async lockedPreview( + client: PoolClient, + input: ExperimentInput + ): Promise { + 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 + ); + } 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; + } + return buildExperimentPreview( + input, + request, + (await readCanonicalDataset(client, request.datasetHash)).manifest + ); + } + async submit(raw: unknown, actor: { principal: string; key: string }): Promise { + const submission = parseExperimentSubmission(raw); + const receipt = experimentReceipt(actor); + const { previewHash, ...input } = submission; + const hash = experimentHash({ version: 1, operation: 'create-experiment', submission }); + return this.database.transaction(async client => { + 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 = await this.lockedPreview(client, input); + 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 = experimentTrialRequest(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 { + if (backtestId !== undefined) { + experimentId(backtestId); + } + const rows = await this.database.query( + `SELECT ${summaryColumns} FROM research_experiments e + ${backtestId === undefined ? '' : 'WHERE e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`, + backtestId === undefined ? [] : [backtestId] + ); + return rows.rows.map(summary); + } + async get(id: string): Promise { + experimentId(id); + return this.readDetail(this.database, id); + } + async cancel(id: string): Promise { + 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); + }); + } + private async readDetail(database: Query, id: string): Promise { + const row = ( + await database.query( + `SELECT ${summaryColumns},e.preview FROM research_experiments e WHERE e.id=$1`, + [id] + ) + ).rows[0]; + if (!row) { + throw new ExperimentError(404, 'Experiment not found'); + } + const preview = retainedExperimentPreview(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.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 = { + ...candidate, + runId: run?.id ?? null, + 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 = experimentTrialRequest(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 !== 'typescript-retained-builtin/v1' || + !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), counts, preview, trials }; + } +} diff --git a/apps/stock/web-app/src/app/App.tsx b/apps/stock/web-app/src/app/App.tsx index 7ebdc1c0..6531e49b 100644 --- a/apps/stock/web-app/src/app/App.tsx +++ b/apps/stock/web-app/src/app/App.tsx @@ -3,6 +3,7 @@ import { Layout } from '@/components/layout'; import { BacktestDetailPageV2, BacktestListPageV2 } from '@/features/backtest'; import { DashboardPage } from '@/features/dashboard'; import { ExchangesPage } from '@/features/exchanges'; +import { ExperimentDetailPage, ExperimentListPage } from '@/features/experiments'; import { MonitoringPage } from '@/features/monitoring'; import { PipelinePage } from '@/features/pipeline'; import { ResearchListPage, ResearchProjectPage } from '@/features/research'; @@ -48,6 +49,10 @@ export function App() { } /> } /> + + } /> + } /> + Settings Page - Coming Soon} diff --git a/apps/stock/web-app/src/components/layout/Layout.tsx b/apps/stock/web-app/src/components/layout/Layout.tsx index 66920f53..079e20e3 100644 --- a/apps/stock/web-app/src/components/layout/Layout.tsx +++ b/apps/stock/web-app/src/components/layout/Layout.tsx @@ -13,6 +13,9 @@ export function Layout() { if (path === 'research' || path.startsWith('research/')) { return 'Research'; } + if (path === 'experiments' || path.startsWith('experiments/')) { + return 'Experiments'; + } if (!path || path === 'dashboard') { return 'Dashboard'; } diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 7054532a..f92803eb 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -509,6 +509,14 @@ export function BacktestDetailPageV2() { {archived ? 'Restore backtest' : 'Archive backtest'} )} + {backtest && catalog && !archived && ( + + Create experiment + + )} {currentRun && (

Run current settings

diff --git a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx new file mode 100644 index 00000000..6dd18f70 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx @@ -0,0 +1,237 @@ +import { useEffect, useRef, useState } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import type { ExperimentTrial } from '@stock-bot/stock-config/experiments'; +import { Button } from '@/components/ui/Button'; +import { ExperimentCounts } from './components/ExperimentCounts'; +import { ExperimentInputs } from './components/ExperimentInputs'; +import { experimentApi, type ExperimentDetailView as Detail } from './services/experimentApi'; + +export function ExperimentDetailPage() { + const { experimentId = '' } = useParams<{ experimentId: string }>(); + return ; +} +function metricText(trial: ExperimentTrial, key: keyof NonNullable) { + const value = trial.metrics?.[key]; + return value === null || value === undefined + ? `Unavailable${trial.unavailable?.[key] ? `: ${trial.unavailable[key]}` : ''}` + : String(value); +} +function ExperimentDetailView({ experimentId }: { experimentId: string }) { + const alive = useRef(false); + const pending = useRef(false); + const [experiment, setExperiment] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [reload, setReload] = useState(0); + const [cancelling, setCancelling] = useState(false); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + }; + }, []); + useEffect(() => { + let current = true; + const controller = new AbortController(); + setLoading(true); + setError(''); + setExperiment(null); + void experimentApi + .get(experimentId, controller.signal) + .then(value => { + if (current) { + setExperiment(value); + } + }) + .catch(cause => { + if (current) { + setError(cause instanceof Error ? cause.message : 'Could not load experiment'); + } + }) + .finally(() => { + if (current) { + setLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [experimentId, reload]); + const cancel = async () => { + if (pending.current || !experiment || loading) { + return; + } + pending.current = true; + setCancelling(true); + setError(''); + try { + const value = await experimentApi.cancel(experimentId); + if (alive.current) { + setExperiment(value); + } + } catch (cause) { + if (alive.current) { + setError( + `${cause instanceof Error ? cause.message : 'Could not request cancellation'}. Refresh to verify the saved state, or retry cancellation.` + ); + } + } finally { + pending.current = false; + if (alive.current) { + setCancelling(false); + } + } + }; + const active = + experiment && + experiment.counts.pending + experiment.counts.running + experiment.counts.paused > 0; + return ( +
+ + All experiments + +
+

{experiment?.name ?? 'Experiment'}

+ +
+ {loading &&

Loading experiment...

} + {error && ( +

+ {error} +

+ )} + {experiment && ( + <> + +
+ + Open saved backtest + + {active && !experiment.cancelRequested && ( + + )} +
+ +
+

Every trial outcome

+

+ Rows retain grid order. Metrics come from saved results; unavailable, failed and + incomparable outcomes remain visible. Returns and drawdowns are fractions. No + cross-experiment ranking is applied. +

+
+ + + + {[ + 'Trial / parameters', + 'Status', + 'Comparability', + 'Total return', + 'Max drawdown', + 'Sharpe ratio', + 'Diagnostics / run', + ].map(label => ( + + ))} + + + + {experiment.trials.map(trial => ( + + + + + + + + + + ))} + +
+ {label} +
+ Trial {trial.index + 1} +
+                          {JSON.stringify(trial.parameters, null, 2)}
+                        
+
+ {trial.status} +

+ {trial.status === 'missing' + ? 'Child run missing' + : `${trial.progress}% complete`} +

+ {trial.cancelRequested &&

Cancellation requested

} +
+ {trial.comparable + ? 'Comparable' + : trial.status === 'completed' + ? 'Incomparable' + : 'Not evaluated'} + + {metricText(trial, 'totalReturn')} + + {metricText(trial, 'maxDrawdown')} + + {metricText(trial, 'sharpeRatio')} + + {trial.error &&

{trial.error}

} + {trial.diagnostic &&

{trial.diagnostic}

} + {trial.limitations.map((limitation, index) => ( +

{limitation}

+ ))} + {!trial.metrics &&

Metrics unavailable

} + {trial.metrics && ( +
+ All reported metrics +
+ {Object.keys(trial.metrics).map(key => ( +
+
{key}
+
+ {metricText( + trial, + key as keyof NonNullable + )} +
+
+ ))} +
+
+ )} + {trial.runId && ( + + Open trial {trial.index + 1} run + + )} +
+
+
+ + )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx new file mode 100644 index 00000000..1c5c2469 --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/ExperimentListPage.tsx @@ -0,0 +1,116 @@ +import { useEffect, useState } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import type { ExperimentSummary } from '@stock-bot/stock-config/experiments'; +import { Button } from '@/components/ui/Button'; +import { ExperimentCounts } from './components/ExperimentCounts'; +import { ExperimentEditor } from './components/ExperimentEditor'; +import { experimentApi } from './services/experimentApi'; + +export function ExperimentListPage() { + const [params] = useSearchParams(); + const backtestId = params.get('backtestId') || ''; + return ; +} +function ExperimentList({ backtestId }: { backtestId: string }) { + const [rows, setRows] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [reload, setReload] = useState(0); + const [dirty, setDirty] = useState(false); + useEffect(() => { + let current = true; + const controller = new AbortController(); + setLoading(true); + setError(''); + setRows([]); + void experimentApi + .list(backtestId || undefined, controller.signal) + .then(value => { + if (current) { + setRows(value); + } + }) + .catch(cause => { + if (current) { + setError(cause instanceof Error ? cause.message : 'Could not load experiments'); + } + }) + .finally(() => { + if (current) { + setLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [backtestId, reload]); + return ( +
{ + if ( + (event.target as HTMLElement).closest('a') && + dirty && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey && + !window.confirm( + 'Leave this experiment draft or unconfirmed submission? Its retry inputs and key will be discarded. You can inspect saved experiments in another tab.' + ) + ) { + event.preventDefault(); + event.stopPropagation(); + } + }} + > +
+

Experiments

+

+ Retained-input parameter sweeps and every trial outcome. +

+
+ +
+
+

Saved experiments

+ +
+ {backtestId && ( +

+ Showing experiments for the selected backtest.{' '} + + Show all experiments + +

+ )} + {loading &&

Loading experiments...

} + {error && ( +

+ {error} +

+ )} + {!loading && !error && rows.length === 0 &&

No experiments yet.

} + {rows.map(item => ( +
+ + {item.name} + +

Created {item.createdAt}

+ +
+ ))} +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentCounts.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentCounts.tsx new file mode 100644 index 00000000..be9d7c4c --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentCounts.tsx @@ -0,0 +1,22 @@ +import type { ExperimentSummary } from '@stock-bot/stock-config/experiments'; + +export function ExperimentCounts({ experiment }: { experiment: ExperimentSummary }) { + const missing = + experiment.trialCount - Object.values(experiment.counts).reduce((sum, count) => sum + count, 0); + return ( +
+

+ {experiment.trialCount} trials ·{' '} + {Object.entries(experiment.counts) + .map(([status, count]) => `${status}: ${count}`) + .join(' · ')}{' '} + · missing: {missing} +

+ {experiment.cancelRequested && ( +

+ Cancellation requested. Running trials may still finish before acknowledging cancellation. +

+ )} +
+ ); +} diff --git a/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx new file mode 100644 index 00000000..fefb84fa --- /dev/null +++ b/apps/stock/web-app/src/features/experiments/components/ExperimentEditor.tsx @@ -0,0 +1,333 @@ +import { useEffect, useRef, useState } from 'react'; +import { Link, useNavigate } from 'react-router-dom'; +import { z } from 'zod'; +import { + experimentInputSchema, + MAX_EXPERIMENT_TRIALS, + type ExperimentSubmission, +} from '@stock-bot/stock-config/experiments'; +import { Button } from '@/components/ui/Button'; +import { backtestApiV2, type Backtest } from '@/features/backtest/services/backtestApiV2'; +import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning'; +import { + experimentApi, + ExperimentApiError, + type ExperimentPreviewView, +} from '../services/experimentApi'; +import { ExperimentInputs } from './ExperimentInputs'; + +const fieldClass = + 'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60'; +const message = (cause: unknown) => + cause instanceof z.ZodError + ? cause.issues.map(issue => `${issue.path.join('.') || 'Input'}: ${issue.message}`).join('; ') + : cause instanceof Error + ? cause.message + : 'Could not prepare the experiment'; +const canonical = (value: Backtest) => + value && + typeof value.id === 'string' && + typeof value.name === 'string' && + !value.archivedAt && + value.strategyVersionId && + value.config && + typeof value.config.canonical === 'object' && + value.config.canonical !== null && + typeof value.config.datasetHash === 'string'; + +export function ExperimentEditor({ + initialBacktestId, + onDirty, +}: { + initialBacktestId: string; + onDirty: (dirty: boolean) => void; +}) { + const navigate = useNavigate(); + const alive = useRef(false); + const generation = useRef(0); + const previewRequest = useRef(null); + const pending = useRef(false); + const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null); + const [hasIntent, setHasIntent] = useState(false); + const [backtestId, setBacktestId] = useState(initialBacktestId); + const [name, setName] = useState(''); + const [grid, setGrid] = useState('{}'); + const [backtests, setBacktests] = useState([]); + const [templateLoading, setTemplateLoading] = useState(true); + const [templateError, setTemplateError] = useState(''); + const [templateReload, setTemplateReload] = useState(0); + const [limit, setLimit] = useState(50); + const [moreTemplates, setMoreTemplates] = useState(false); + const [preview, setPreview] = useState(null); + const [previewLoading, setPreviewLoading] = useState(false); + const [error, setError] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [ambiguous, setAmbiguous] = useState(false); + const dirty = hasIntent || Boolean(name || grid !== '{}' || backtestId !== initialBacktestId); + useUnsavedWarning(dirty); + useEffect(() => { + onDirty(dirty); + }, [dirty, onDirty]); + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + generation.current++; + previewRequest.current?.abort(); + }; + }, []); + useEffect(() => { + let current = true; + const controller = new AbortController(); + setTemplateLoading(true); + setTemplateError(''); + void (async () => { + const rows = await backtestApiV2.listBacktests(limit, 0, false, controller.signal); + if (!Array.isArray(rows)) { + throw new Error('The saved backtest list could not be read'); + } + const selected = + initialBacktestId && !rows.some(item => item?.id === initialBacktestId) + ? await backtestApiV2.getBacktest(initialBacktestId) + : null; + if (current) { + setMoreTemplates(rows.length === limit); + setBacktests((selected ? [...rows, selected] : rows).filter(canonical)); + } + })() + .catch(cause => { + if (current) { + setTemplateError(message(cause)); + } + }) + .finally(() => { + if (current) { + setTemplateLoading(false); + } + }); + return () => { + current = false; + controller.abort(); + }; + }, [initialBacktestId, templateReload, limit]); + + const invalidate = (change: () => void) => { + if (intent.current) { + return; + } + generation.current++; + previewRequest.current?.abort(); + setPreview(null); + setPreviewLoading(false); + setError(''); + change(); + }; + const prepare = async () => { + if (intent.current || previewLoading) { + return; + } + const current = ++generation.current; + previewRequest.current?.abort(); + const controller = new AbortController(); + previewRequest.current = controller; + setPreview(null); + setError(''); + setPreviewLoading(true); + try { + const input = experimentInputSchema.parse({ backtestId, name, grid: JSON.parse(grid) }); + const value = await experimentApi.preview(input, controller.signal); + if (alive.current && current === generation.current) { + setPreview(value); + } + } catch (cause) { + if (alive.current && current === generation.current) { + setError(message(cause)); + } + } finally { + if (alive.current && current === generation.current) { + setPreviewLoading(false); + } + } + }; + const submit = async () => { + if (pending.current || (!intent.current && !preview)) { + return; + } + if (!intent.current) { + if (!preview) { + return; + } + intent.current = { + key: crypto.randomUUID(), + body: { ...preview.input, previewHash: preview.previewHash }, + }; + } + const captured = intent.current; + pending.current = true; + setHasIntent(true); + setSubmitting(true); + setError(''); + try { + const accepted = await experimentApi.create(captured.body, captured.key); + if (alive.current) { + intent.current = null; + setHasIntent(false); + navigate(`/experiments/${encodeURIComponent(accepted.id)}`); + } + } catch (cause) { + if (alive.current) { + setError(message(cause)); + setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous); + } + } finally { + pending.current = false; + if (alive.current) { + setSubmitting(false); + } + } + }; + const newIntent = () => { + if ( + pending.current || + !window.confirm( + 'Release this submission? If its response was lost, it may already exist. Check the experiment list before creating another.' + ) + ) { + return; + } + intent.current = null; + setHasIntent(false); + setAmbiguous(false); + setPreview(null); + setError(''); + }; + return ( +
+

New parameter sweep

+

+ Choose a saved canonical backtest and vary its strategy parameters. Preview validates every + combination before any trials are submitted. +

+ {templateLoading &&

Loading saved backtests...

} + {templateError && ( +
+ {templateError}{' '} + +
+ )} + {!templateLoading && !templateError && backtests.length === 0 && ( +

+ No saved canonical backtests are available.{' '} + + Configure a backtest + {' '} + with a retained dataset and strategy version. +

+ )} +
+ + +
+ {moreTemplates && ( + + )} +