feat(research): add retained-input parameter sweep workbench

This commit is contained in:
Boki 2026-10-24 10:33:05 -04:00
parent 30accfcf43
commit 6f64ef62ba
41 changed files with 4469 additions and 34 deletions

View file

@ -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": {

View file

@ -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<typeof experimentInputSchema>;
export type ExperimentSubmission = z.infer<typeof experimentSubmissionSchema>;
export interface ExperimentCandidate {
/** Zero-based deterministic position in the frozen grid. */
index: number;
trialKey: string;
parameters: Record<string, StrategyParameterValue>;
}
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<ExperimentRunStatus, number>;
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[];
}

View file

@ -61,7 +61,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
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();

View file

@ -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;
}

View file

@ -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<unknown> => {
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;
}

View file

@ -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<string>();
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;
}

View file

@ -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<ExperimentPreview> {
const input = parseExperimentInput(raw);
return this.database.transaction(client => this.lockedPreview(client, input));
}
private async lockedPreview(
client: PoolClient,
input: ExperimentInput
): 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
);
} 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<ExperimentDetail> {
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<ExperimentSummary[]> {
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<ExperimentDetail> {
experimentId(id);
return this.readDetail(this.database, id);
}
async cancel(id: string): Promise<ExperimentDetail> {
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<ExperimentDetail> {
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 };
}
}

View file

@ -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() {
<Route index element={<ResearchListPage />} />
<Route path=":projectId" element={<ResearchProjectPage />} />
</Route>
<Route path="experiments">
<Route index element={<ExperimentListPage />} />
<Route path=":experimentId" element={<ExperimentDetailPage />} />
</Route>
<Route
path="settings"
element={<div className="p-4">Settings Page - Coming Soon</div>}

View file

@ -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';
}

View file

@ -509,6 +509,14 @@ export function BacktestDetailPageV2() {
{archived ? 'Restore backtest' : 'Archive backtest'}
</button>
)}
{backtest && catalog && !archived && (
<Link
to={`/experiments?backtestId=${encodeURIComponent(backtest.id)}`}
className="px-3 py-2 text-sm text-primary-500 border border-border rounded-md"
>
Create experiment
</Link>
)}
{currentRun && (
<div className="px-4">
<p className="text-xs text-text-secondary">Run current settings</p>

View file

@ -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 <ExperimentDetailView key={experimentId} experimentId={experimentId} />;
}
function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTrial['metrics']>) {
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<Detail | null>(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 (
<div className="h-full overflow-auto space-y-5 p-1">
<Link className="text-primary-500 text-sm" to="/experiments">
All experiments
</Link>
<div className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-lg font-bold">{experiment?.name ?? 'Experiment'}</h1>
<Button
variant="outline"
size="sm"
disabled={loading || cancelling}
onClick={() => setReload(value => value + 1)}
>
Refresh experiment
</Button>
</div>
{loading && <p role="status">Loading experiment...</p>}
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{experiment && (
<>
<ExperimentCounts experiment={experiment} />
<div className="flex flex-wrap items-center gap-4">
<Link
className="text-primary-500 text-sm"
to={`/backtests/${encodeURIComponent(experiment.backtestId)}`}
>
Open saved backtest
</Link>
{active && !experiment.cancelRequested && (
<Button
variant="danger"
size="sm"
disabled={cancelling}
onClick={() => void cancel()}
>
{cancelling ? 'Requesting cancellation...' : 'Cancel remaining trials'}
</Button>
)}
</div>
<ExperimentInputs preview={experiment.preview} />
<section aria-label="Experiment trial outcomes" className="space-y-2">
<h2 className="font-semibold">Every trial outcome</h2>
<p className="text-sm text-text-secondary">
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.
</p>
<div className="overflow-x-auto">
<table className="w-full text-sm text-left">
<thead>
<tr>
{[
'Trial / parameters',
'Status',
'Comparability',
'Total return',
'Max drawdown',
'Sharpe ratio',
'Diagnostics / run',
].map(label => (
<th key={label} className="p-2 border-b border-border whitespace-nowrap">
{label}
</th>
))}
</tr>
</thead>
<tbody>
{experiment.trials.map(trial => (
<tr key={trial.trialKey} className="align-top">
<td className="p-2 border-b border-border">
<span>Trial {trial.index + 1}</span>
<pre className="whitespace-pre-wrap text-xs">
{JSON.stringify(trial.parameters, null, 2)}
</pre>
</td>
<td className="p-2 border-b border-border">
{trial.status}
<p className="text-xs">
{trial.status === 'missing'
? 'Child run missing'
: `${trial.progress}% complete`}
</p>
{trial.cancelRequested && <p className="text-xs">Cancellation requested</p>}
</td>
<td className="p-2 border-b border-border">
{trial.comparable
? 'Comparable'
: trial.status === 'completed'
? 'Incomparable'
: 'Not evaluated'}
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'totalReturn')}
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'maxDrawdown')}
</td>
<td className="p-2 border-b border-border">
{metricText(trial, 'sharpeRatio')}
</td>
<td className="p-2 border-b border-border min-w-56 space-y-2">
{trial.error && <p className="text-error">{trial.error}</p>}
{trial.diagnostic && <p>{trial.diagnostic}</p>}
{trial.limitations.map((limitation, index) => (
<p key={index}>{limitation}</p>
))}
{!trial.metrics && <p>Metrics unavailable</p>}
{trial.metrics && (
<details>
<summary className="cursor-pointer">All reported metrics</summary>
<dl>
{Object.keys(trial.metrics).map(key => (
<div key={key}>
<dt>{key}</dt>
<dd>
{metricText(
trial,
key as keyof NonNullable<ExperimentTrial['metrics']>
)}
</dd>
</div>
))}
</dl>
</details>
)}
{trial.runId && (
<Link
className="text-primary-500"
to={`/backtests/${encodeURIComponent(experiment.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
>
Open trial {trial.index + 1} run
</Link>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</>
)}
</div>
);
}

View file

@ -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 <ExperimentList key={backtestId} backtestId={backtestId} />;
}
function ExperimentList({ backtestId }: { backtestId: string }) {
const [rows, setRows] = useState<ExperimentSummary[]>([]);
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 (
<div
className="h-full overflow-auto space-y-6 p-1"
onClickCapture={event => {
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();
}
}}
>
<div>
<h1 className="text-lg font-bold text-text-primary">Experiments</h1>
<p className="text-sm text-text-secondary">
Retained-input parameter sweeps and every trial outcome.
</p>
</div>
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
<section aria-label="Saved experiments" className="space-y-3">
<div className="flex items-center justify-between gap-3">
<h2 className="font-semibold">Saved experiments</h2>
<Button
variant="outline"
size="sm"
disabled={loading}
onClick={() => setReload(value => value + 1)}
>
Refresh experiments
</Button>
</div>
{backtestId && (
<p className="text-sm">
Showing experiments for the selected backtest.{' '}
<Link className="text-primary-500" to="/experiments">
Show all experiments
</Link>
</p>
)}
{loading && <p role="status">Loading experiments...</p>}
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{!loading && !error && rows.length === 0 && <p>No experiments yet.</p>}
{rows.map(item => (
<article key={item.id} className="rounded-lg border border-border p-3 space-y-2">
<Link
className="font-medium text-primary-500"
to={`/experiments/${encodeURIComponent(item.id)}`}
>
{item.name}
</Link>
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
<ExperimentCounts experiment={item} />
</article>
))}
</section>
</div>
);
}

View file

@ -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 (
<div className="text-sm text-text-secondary space-y-1">
<p>
{experiment.trialCount} trials ·{' '}
{Object.entries(experiment.counts)
.map(([status, count]) => `${status}: ${count}`)
.join(' · ')}{' '}
· missing: {missing}
</p>
{experiment.cancelRequested && (
<p>
Cancellation requested. Running trials may still finish before acknowledging cancellation.
</p>
)}
</div>
);
}

View file

@ -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<AbortController | null>(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<Backtest[]>([]);
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<ExperimentPreviewView | null>(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 (
<section
aria-label="Create experiment"
className="rounded-lg border border-border bg-surface p-4 space-y-4"
>
<h2 className="font-semibold text-text-primary">New parameter sweep</h2>
<p className="text-sm text-text-secondary">
Choose a saved canonical backtest and vary its strategy parameters. Preview validates every
combination before any trials are submitted.
</p>
{templateLoading && <p role="status">Loading saved backtests...</p>}
{templateError && (
<div role="alert">
{templateError}{' '}
<Button variant="outline" size="sm" onClick={() => setTemplateReload(value => value + 1)}>
Retry saved backtests
</Button>
</div>
)}
{!templateLoading && !templateError && backtests.length === 0 && (
<p>
No saved canonical backtests are available.{' '}
<Link className="text-primary-500" to="/backtests">
Configure a backtest
</Link>{' '}
with a retained dataset and strategy version.
</p>
)}
<div className="grid gap-4 sm:grid-cols-2 text-sm">
<label>
Saved backtest
<select
className={fieldClass}
value={backtestId}
disabled={hasIntent || templateLoading}
onChange={event => invalidate(() => setBacktestId(event.target.value))}
>
<option value="">Select a saved canonical backtest</option>
{initialBacktestId && !backtests.some(item => item.id === initialBacktestId) && (
<option value={initialBacktestId}>Selected backtest is unavailable</option>
)}
{backtests.map(item => (
<option key={item.id} value={item.id}>
{item.name}
</option>
))}
</select>
</label>
<label>
Experiment name
<input
className={fieldClass}
value={name}
disabled={hasIntent}
onChange={event => invalidate(() => setName(event.target.value))}
/>
</label>
</div>
{moreTemplates && (
<Button
variant="outline"
size="sm"
disabled={templateLoading || hasIntent}
onClick={() => setLimit(value => value + 50)}
>
Load more backtests
</Button>
)}
<label className="block text-sm">
Parameter grid (JSON)
<textarea
className={`${fieldClass} font-mono`}
rows={4}
value={grid}
disabled={hasIntent}
onChange={event => invalidate(() => setGrid(event.target.value))}
aria-describedby="experiment-grid-help"
/>
</label>
<p id="experiment-grid-help" className="text-xs text-text-secondary">
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'} runs
the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per experiment; this
does not promise concurrent execution.
</p>
<Button
variant="outline"
disabled={
hasIntent ||
previewLoading ||
!backtests.some(item => item.id === backtestId) ||
!name.trim()
}
onClick={() => void prepare()}
>
Preview experiment
</Button>
{previewLoading && <p role="status">Validating experiment inputs...</p>}
{preview && <ExperimentInputs preview={preview} />}
{error && (
<p role="alert" className="text-error">
{error}
</p>
)}
{hasIntent && (
<p role="status" className="text-sm text-text-secondary">
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission keeps its exact inputs and
key. Retry to recover the same experiment; check saved experiments before starting
another.
</p>
)}
{(preview || hasIntent) && (
<div className="flex flex-wrap gap-2">
<Button disabled={submitting} onClick={() => void submit()}>
{submitting
? 'Submitting experiment...'
: hasIntent
? 'Retry experiment submission'
: 'Confirm experiment'}
</Button>
{hasIntent && (
<Button variant="outline" disabled={submitting} onClick={newIntent}>
Start new experiment
</Button>
)}
</div>
)}
</section>
);
}

View file

@ -0,0 +1,86 @@
import type { ExperimentPreviewView } from '../services/experimentApi';
export function ExperimentInputs({ preview }: { preview: ExperimentPreviewView }) {
const { request, dataset } = preview;
const series = dataset.series.find(item => item.id === request.strategy.selection.seriesId);
return (
<section
aria-label="Frozen experiment inputs"
className="space-y-2 text-sm text-text-secondary"
>
<p className="font-medium text-text-primary">
{preview.candidates.length} trials · {request.name}
</p>
<dl className="grid gap-2 sm:grid-cols-2 break-all">
<div>
<dt>Strategy version</dt>
<dd>{request.strategy.versionId}</dd>
</div>
<div>
<dt>Dataset</dt>
<dd>{request.datasetHash}</dd>
</div>
<div>
<dt>Asset / timeframe</dt>
<dd>
{request.strategy.selection.instrumentId} / {series?.interval}
</dd>
</div>
<div>
<dt>Trading window (UTC, end exclusive)</dt>
<dd>
{new Date(dataset.bounds.tradeStart).toISOString()} —{' '}
{new Date(dataset.bounds.tradeEnd).toISOString()}
</dd>
</div>
<div>
<dt>Warmup starts (UTC)</dt>
<dd>{new Date(dataset.bounds.warmupStart).toISOString()}</dd>
</div>
<div>
<dt>Initial capital / owner budget (USD)</dt>
<dd>
{request.policy.matching.risk.ledger.initialCapital} /{' '}
{request.strategy.selection.ownerBudget}
</dd>
</div>
<div>
<dt>Seed</dt>
<dd>{request.strategy.selection.seed}</dd>
</div>
</dl>
<p>
Only strategy parameters vary. Every trial retains this dataset, strategy version, capital,
costs and risk policy.
</p>
<details>
<summary className="cursor-pointer text-primary-500">
Exact parameters, policies and provenance
</summary>
<pre className="mt-2 max-h-80 overflow-auto whitespace-pre-wrap text-xs">
{JSON.stringify(
{
previewHash: preview.previewHash,
input: preview.input,
candidates: preview.candidates,
strategy: {
versionId: request.strategy.versionId,
reviewId: request.strategy.reviewId,
selection: request.strategy.selection,
artifactHash: request.strategy.package.artifact.sha256,
dependencyLockHash: request.strategy.package.dependencyLock.sha256,
},
dataset,
policy: request.policy,
analyticsPolicy: request.analyticsPolicy,
build: request.build,
modelArtifacts: request.modelArtifacts,
},
null,
2
)}
</pre>
</details>
</section>
);
}

View file

@ -0,0 +1,2 @@
export { ExperimentListPage } from './ExperimentListPage';
export { ExperimentDetailPage } from './ExperimentDetailPage';

View file

@ -0,0 +1,298 @@
import { z } from 'zod';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import {
experimentInputSchema,
MAX_EXPERIMENT_TRIALS,
type ExperimentDetail,
type ExperimentInput,
type ExperimentPreview,
type ExperimentSubmission,
type ExperimentSummary,
} from '@stock-bot/stock-config/experiments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
export class ExperimentApiError extends Error {
constructor(
message: string,
public readonly status: number | null
) {
super(message);
}
get ambiguous() {
return this.status === null || this.status >= 500;
}
}
const hash = z.string().regex(/^[a-f0-9]{64}$/);
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
const candidate = z.object({
index: count,
trialKey: hash,
parameters: z.record(scalar),
});
const statuses = ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'] as const;
const counts = z.object({
pending: count,
running: count,
paused: count,
completed: count,
failed: count,
cancelled: count,
});
const summary = z.object({
id: z.string().uuid(),
name: z.string().min(1),
backtestId: z.string().uuid(),
createdAt: z.string().min(1),
cancelRequested: z.boolean(),
trialCount: count.min(1),
counts,
datasetHash: hash,
strategyVersionId: z.string().uuid(),
previewHash: hash,
});
const timestamp = z.number().int().min(-8640000000000000).max(8640000000000000);
const dataset = z
.object({
version: z.literal(2),
hash,
bounds: z.object({
warmupStart: timestamp,
tradeStart: timestamp,
tradeEnd: timestamp,
}),
series: z.array(
z.object({ id: z.string(), instrumentId: z.string(), interval: z.string() }).passthrough()
),
})
.passthrough();
/** Only the manifest fields consumed by this UI are structurally decoded here. */
export type ExperimentPreviewView = Omit<ExperimentPreview, 'dataset'> & {
dataset: z.infer<typeof dataset>;
};
export type ExperimentDetailView = Omit<ExperimentDetail, 'preview'> & {
preview: ExperimentPreviewView;
};
const preview = z.object({
version: z.literal('research-experiment-preview/v1'),
previewHash: hash,
input: experimentInputSchema,
request: canonicalRunRequestSchema,
dataset,
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
});
const metric = z.number().finite().nullable();
const metrics = z.object({
totalReturn: metric,
cagr: metric,
maxDrawdown: metric,
exposureTime: metric,
volatility: metric,
downsideDeviation: metric,
sharpeRatio: metric,
sortinoRatio: metric,
var95: metric,
cvar95: metric,
var99: metric,
alpha: z.null(),
beta: z.null(),
informationRatio: z.null(),
roundTripCount: z.null(),
winRate: z.null(),
profitFactor: z.null(),
avgWin: z.null(),
avgLoss: z.null(),
});
const trial = candidate.extend({
runId: z.string().uuid().nullable(),
status: z.enum([...statuses, 'missing']),
progress: z.number().finite().min(0).max(100),
cancelRequested: z.boolean(),
error: z.string().nullable(),
comparable: z.boolean(),
diagnostic: z.string().nullable(),
metrics: metrics.nullable(),
unavailable: z.record(z.string()).nullable(),
limitations: z.array(z.string()),
});
const detail = summary.extend({ preview, trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS) });
const same = (left: unknown, right: unknown) =>
canonicalStrategyJson(left) === canonicalStrategyJson(right);
const invalid = () =>
new ExperimentApiError(
'The experiment response could not be verified. Refresh or retry the same submission.',
null
);
function parseSummary(value: unknown): ExperimentSummary {
const parsed = summary.parse(value);
if (Object.values(parsed.counts).reduce((sum, value) => sum + value, 0) > parsed.trialCount) {
throw invalid();
}
return parsed;
}
function parsePreview(value: unknown): ExperimentPreviewView {
const parsed = preview.parse(value);
if (
parsed.input.backtestId !== parsed.request.backtestId ||
parsed.dataset.hash !== parsed.request.datasetHash ||
parsed.dataset.bounds.warmupStart > parsed.dataset.bounds.tradeStart ||
parsed.dataset.bounds.tradeStart >= parsed.dataset.bounds.tradeEnd ||
!parsed.dataset.series.some(
series =>
series.id === parsed.request.strategy.selection.seriesId &&
series.instrumentId === parsed.request.strategy.selection.instrumentId
) ||
parsed.candidates.some((item, index) => item.index !== index) ||
new Set(parsed.candidates.map(item => item.trialKey)).size !== parsed.candidates.length
) {
throw invalid();
}
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
return parsed;
}
function parseDetail(value: unknown): ExperimentDetailView {
const parsed = detail.parse(value);
parseSummary(parsed);
const retained = parsePreview(parsed.preview);
if (
parsed.backtestId !== retained.input.backtestId ||
parsed.name !== retained.input.name ||
parsed.previewHash !== retained.previewHash ||
parsed.datasetHash !== retained.request.datasetHash ||
parsed.strategyVersionId !== retained.request.strategy.versionId ||
parsed.trialCount !== retained.candidates.length ||
parsed.trials.length !== parsed.trialCount
) {
throw invalid();
}
const runIds = new Set<string>();
for (const [index, item] of parsed.trials.entries()) {
const expected = retained.candidates[index];
if (
!expected ||
item.index !== expected.index ||
item.trialKey !== expected.trialKey ||
!same(item.parameters, expected.parameters) ||
(item.status === 'missing') !== (item.runId === null) ||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
(item.runId !== null && runIds.has(item.runId))
) {
throw invalid();
}
if (item.runId) {
runIds.add(item.runId);
}
}
if (
statuses.some(
status =>
parsed.counts[status] !== parsed.trials.filter(item => item.status === status).length
)
) {
throw invalid();
}
return { ...parsed, preview: retained } as ExperimentDetailView;
}
async function request<T>(
path: string,
init: RequestInit,
expectedStatus: number,
parse: (body: unknown) => T
): Promise<T> {
let response: Response;
try {
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments${path}`, init);
} catch (cause) {
if (init.signal?.aborted) {
throw cause;
}
throw new ExperimentApiError(
'The experiment response was lost. Retry the same submission to check whether it was accepted.',
null
);
}
const body: unknown = await response.json().catch(() => null);
if (!response.ok) {
const parsed = z.object({ error: z.string() }).safeParse(body);
throw new ExperimentApiError(
parsed.success ? parsed.data.error : `Experiment request failed (${response.status})`,
response.status
);
}
try {
if (response.status !== expectedStatus) {
throw invalid();
}
return parse(body);
} catch {
throw invalid();
}
}
const envelope = (body: unknown, field: string): unknown =>
z.record(z.unknown()).parse(body)[field];
const json = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
export const experimentApi = {
list: (backtestId?: string, signal?: AbortSignal) =>
request(
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
{ signal },
200,
body => {
const rows = z.array(z.unknown()).parse(envelope(body, 'experiments')).map(parseSummary);
if (
new Set(rows.map(row => row.id)).size !== rows.length ||
(backtestId && rows.some(row => row.backtestId !== backtestId))
) {
throw invalid();
}
return rows;
}
),
preview: (input: ExperimentInput, signal?: AbortSignal) =>
request('/preview', { ...json(input), signal }, 200, body => {
const value = parsePreview(envelope(body, 'preview'));
if (!same(value.input, input)) {
throw invalid();
}
return value;
}),
create: (input: ExperimentSubmission, key: string) =>
request(
'',
{
...json(input),
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
},
202,
body => {
const value = parseDetail(envelope(body, 'experiment'));
const { previewHash, ...original } = input;
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
throw invalid();
}
return value;
}
),
get: (id: string, signal?: AbortSignal) =>
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
const value = parseDetail(envelope(body, 'experiment'));
if (value.id !== id) {
throw invalid();
}
return value;
}),
cancel: (id: string) =>
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
const value = parseDetail(envelope(body, 'experiment'));
if (value.id !== id || !value.cancelRequested) {
throw invalid();
}
return value;
}),
};

View file

@ -34,6 +34,7 @@ export const navigation: NavigationItem[] = [
{ name: 'Analytics', href: '/analytics', icon: PresentationChartLineIcon },
{ name: 'Backtests', href: '/backtests', icon: BeakerIcon },
{ name: 'Research', href: '/research', icon: BeakerIcon },
{ name: 'Experiments', href: '/experiments', icon: BeakerIcon },
{
name: 'System',
icon: ServerStackIcon,