/** Bounded retained-input experiments use the existing canonical runner and results. */ import { z } from 'zod'; import type { CanonicalBacktestAnalytics, HistoricalDatasetManifestV2, ResearchActor, StrategyParameterValue, } from '@stock-bot/types'; import { candidateOverrideSchema } from './candidate-execution'; 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, candidate: candidateOverrideSchema.optional(), }) .strict(); export const experimentSubmissionSchema = experimentInputSchema.extend({ previewHash: z.string().regex(/^[a-f0-9]{64}$/), }); export type ExperimentInput = z.infer; export type ExperimentSubmission = z.infer; /** Both counters are required: a failure can occur before the worker claims an attempt. */ export const experimentRetrySchema = z .object({ expectedAttemptNumber: z.number().int().nonnegative().max(2147483647), expectedRetryCount: z.number().int().nonnegative().max(2147483647), }) .strict(); export type ExperimentRetryInput = z.infer; /** Snapshot of the failure preceding an accepted manual retry, not an automatic-attempt log. */ export interface ExperimentTrialRetry { id: string; experimentId: string; runId: string; trialKey: string; retryNumber: number; previousAttemptNumber: number; previousAttemptId: string | null; error: string | null; progress: number; currentDate: string | null; startedAt: string | null; completedAt: string | null; pausedAt: string | null; failureUpdatedAt: string; recordedAt: string; principal: ResearchActor; /** Current approval at retry admission; the original run snapshot stays immutable. */ reviewId: string | null; } export interface ExperimentRetryResult { retry: ExperimentTrialRetry; experiment: ExperimentDetail; } 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 { /** Optional for older clients/fixtures; absent means a parameter experiment. */ kind?: 'parameters' | 'cost-sensitivity'; 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; attemptNumber: number; retryCount: number; 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 { /** Server-derived role. Absent in older clients; only true admits a standalone source link. */ standalone?: boolean; preview: ExperimentPreview; trials: ExperimentTrial[]; }