import { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { z } from 'zod'; import { MAX_WALK_FORWARD_RUNS, MAX_WALK_FORWARD_WINDOWS, walkForwardInputSchema, type WalkForwardSubmission, } from '@stock-bot/stock-config/walk-forward'; import { Button } from '@/components/ui/Button'; import { walkForwardApi, WalkForwardApiError, type WalkForwardPreviewView, } from '../services/walkForwardApi'; import { ExperimentInputs } from './ExperimentInputs'; import { emptyValidationWindows, parseValidationWindows, ValidationWindowFields, validationWindowsDirty, type ValidationWindows, } from './ValidationWindowFields'; type Owner = 'ordinary' | 'chronological' | 'walk-forward'; 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 walk-forward validation'; export function WalkForwardPreflight({ backtestId, name, grid, candidate, disabled, eligible, onDirty, claimSubmission, releaseSubmission, }: { backtestId: string; name: string; grid: string; candidate?: WalkForwardSubmission['candidate']; disabled: boolean; eligible: boolean; onDirty: (value: boolean) => void; claimSubmission: (owner: Owner) => boolean; releaseSubmission: (owner: Owner) => void; }) { const navigate = useNavigate(); const [windows, setWindows] = useState(() => [ emptyValidationWindows(), emptyValidationWindows(), ]); const [prepared, setPrepared] = useState<{ identity: string; preview: WalkForwardPreviewView; } | null>(null); const [hasIntent, setHasIntent] = useState(false), [loading, setLoading] = useState(false), [submitting, setSubmitting] = useState(false), [error, setError] = useState(''), [ambiguous, setAmbiguous] = useState(false); const captured = useRef<{ body: WalkForwardSubmission; key: string; preview: WalkForwardPreviewView; } | null>(null); const alive = useRef(false), pending = useRef(false), posting = useRef(false), generation = useRef(0), read = useRef(null); const identity = JSON.stringify({ backtestId, name, grid, candidate, windows, disabled, eligible, }), currentIdentity = useRef(identity); currentIdentity.current = identity; const preview = captured.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null); const dirty = hasIntent || windows.length !== 2 || windows.some(validationWindowsDirty); useEffect(() => { onDirty(dirty); }, [dirty, onDirty]); useEffect(() => { alive.current = true; return () => { alive.current = false; generation.current++; read.current?.abort(); }; }, []); useEffect(() => { generation.current++; read.current?.abort(); pending.current = false; setPrepared(null); setLoading(false); if (!captured.current) { setError(''); } }, [identity]); const edit = (change: (current: ValidationWindows[]) => ValidationWindows[]) => { if (disabled || captured.current) { return; } generation.current++; read.current?.abort(); setWindows(change); }; const prepare = async () => { if (disabled || !eligible || captured.current || pending.current) { return; } const revision = ++generation.current, original = identity, controller = new AbortController(); read.current?.abort(); read.current = controller; pending.current = true; setPrepared(null); setError(''); setLoading(true); try { const input = walkForwardInputSchema.parse({ backtestId, name, grid: JSON.parse(grid), ...(candidate ? { candidate } : {}), windows: windows.map((window, index) => parseValidationWindows(window, `Window ${index + 1} `) ), }); const value = await walkForwardApi.preview(input, controller.signal); if ( alive.current && revision === generation.current && original === currentIdentity.current ) { setPrepared({ identity: original, preview: value }); } } catch (cause) { if ( alive.current && revision === generation.current && original === currentIdentity.current ) { setError(message(cause)); } } finally { if ( alive.current && revision === generation.current && original === currentIdentity.current ) { pending.current = false; setLoading(false); } } }; const submit = async () => { if ( posting.current || pending.current || (!captured.current && (!preview || disabled || !eligible)) || !claimSubmission('walk-forward') ) { return; } if (!captured.current) { if (!preview) { return; } captured.current = { body: { ...preview.input, previewHash: preview.previewHash }, key: crypto.randomUUID(), preview, }; } const original = captured.current; posting.current = true; setHasIntent(true); setSubmitting(true); setError(''); try { const value = await walkForwardApi.submit(original.body, original.key); if (alive.current) { captured.current = null; setHasIntent(false); releaseSubmission('walk-forward'); navigate(`/experiments/walk-forward/${encodeURIComponent(value.id)}`); } } catch (cause) { if (alive.current) { setError(message(cause)); setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous); } } finally { posting.current = false; if (alive.current) { setSubmitting(false); } } }; const discard = () => { if ( posting.current || !window.confirm( 'Discard this walk-forward submission? It may already exist. Inspect saved walk-forward validations before creating another.' ) ) { return; } captured.current = null; setHasIntent(false); setPrepared(null); setError(''); setAmbiguous(false); releaseSubmission('walk-forward'); }; return (
Walk-forward validation

Uses the saved backtest, name and parameter grid above. Enter explicit UTC instants ending in Z. Preview saves nothing; submission freezes all windows and admits training together. Each window selects independently from training, with separate validation and test runs.

Every phase resets initial capital and positions. Warmup may overlap earlier windows; held-out trading windows cannot overlap. Up to {MAX_WALK_FORWARD_WINDOWS} windows and{' '} {MAX_WALK_FORWARD_RUNS} total planned runs, including both future holdouts per window.

{windows.map((window, index) => (

Window {index + 1}

edit(current => current.map((item, i) => i === index ? { ...item, [phase]: { ...item[phase], [field]: value } } : item ) ) } />
))} {' '} {disabled && (

Resolve or explicitly release the other submission before preparing walk-forward inputs.

)} {loading &&

Preparing walk-forward inputs...

} {error && (

{error}

)} {preview && (

{preview.counts.windows} windows · {preview.counts.trainingRuns} training runs ·{' '} {preview.counts.holdoutRuns} future holdout runs · {preview.counts.totalRuns} total planned runs

{preview.windows.map(item => (
Window {item.index + 1} prepared inputs

Preview {item.preview.previewHash}

{item.preview.partitions.map(part => (

{part.phase}: {new Date(part.dataset.bounds.tradeStart).toISOString()} to{' '} {new Date(part.dataset.bounds.tradeEnd).toISOString()} (end excluded)

Warmup starts {new Date(part.dataset.bounds.warmupStart).toISOString()}; admitted warmup {part.counts.admittedWarmup}, required {part.requiredWarmup}; evaluation observations {part.counts.availableEvaluation}; terminal-at-end observations {part.counts.terminalAtEnd}; completed observations unavailable at end {part.counts.unavailableAtEnd}.

Dataset {part.dataset.hash}

{part.warnings.map((warning, index) => (

{warning}

))}
))}
                  {JSON.stringify(item.preview, null, 2)}
                
))}

Walk-forward preview {preview.previewHash}

)} {hasIntent && (

{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission retains its exact windows, inputs and key. Retry to recover the same walk-forward validation.

)} {(preview || hasIntent) && (
{hasIntent && ( )}
)}
); }