import { useEffect, useRef, useState } from 'react'; import type { CanonicalDatasetPreparation } from '@stock-bot/stock-config/canonical-research'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import { actionClass, fieldClass } from '@/features/strategies/components/StrategyParameterForm'; import { backtestApiV2, DatasetPreparationRequestError, storedSourceSessionScope, } from '../services/backtestApiV2'; import { StoredSourceInspector } from './StoredSourceInspector'; export interface DatasetPreparationState { busy: boolean; blocking: boolean; } interface Props { disabled: boolean; begin: () => boolean; onStateChange: (state: DatasetPreparationState) => void; onRetained: (hash: string, available: boolean) => void; } interface Retention { input: unknown; preview: CanonicalDatasetPreparation; } type InputMode = 'export' | 'stored-eod' | 'stored-eod-sessions'; const instant = (value: number) => new Date(value).toISOString(); export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) { const [mode, setMode] = useState('export'); const modeRef = useRef('export'); const [input, setInput] = useState<{ value: unknown; filename: string } | null>(null); const [preview, setPreview] = useState(null); const [retained, setRetained] = useState(false), [error, setError] = useState(''), [phase, setPhase] = useState<'reading' | 'previewing' | 'retaining' | null>(null); const [intent, setIntent] = useState(null); const source = useRef<{ value: unknown; filename: string } | null>(null); const prepared = useRef(null); const generation = useRef(0), active = useRef(false), pending = useRef(false), captured = useRef(null), controller = useRef(null), fileInput = useRef(null); const callbacks = useRef({ begin, onStateChange, onRetained }); callbacks.current = { begin, onStateChange, onRetained }; useEffect(() => { active.current = true; return () => { active.current = false; generation.current++; controller.current?.abort(); callbacks.current.onStateChange({ busy: false, blocking: false }); }; }, []); const state = (busy: boolean, blocking: boolean) => callbacks.current.onStateChange({ busy, blocking }); const reset = () => { generation.current++; controller.current?.abort(); pending.current = false; captured.current = null; source.current = null; prepared.current = null; setIntent(null); setInput(null); setPreview(null); setRetained(false); setPhase(null); setError(''); if (fileInput.current) { fileInput.current.value = ''; } state(false, false); }; const changeMode = (next: string) => { if ( (next !== 'export' && next !== 'stored-eod' && next !== 'stored-eod-sessions') || next === modeRef.current || disabled || captured.current || !callbacks.current.begin() ) { return; } reset(); modeRef.current = next; setMode(next); }; const loadFile = async (file: File | undefined) => { if (disabled || captured.current || !callbacks.current.begin()) { return; } generation.current++; const revision = generation.current; controller.current?.abort(); pending.current = true; prepared.current = null; source.current = null; setPreview(null); setRetained(false); setInput(null); setError(''); if (!file) { reset(); return; } setPhase('reading'); state(true, true); try { const value: unknown = JSON.parse(await file.text()); if (active.current && revision === generation.current) { source.current = { value, filename: file.name }; setInput(source.current); } } catch (cause) { if (active.current && revision === generation.current) { setError( `Could not read source JSON: ${cause instanceof Error ? cause.message : 'Invalid file'}` ); } } finally { if (active.current && revision === generation.current) { pending.current = false; setPhase(null); state(false, true); } } }; const inspect = async () => { const selectedSource = source.current; const selectedMode = modeRef.current; if ( disabled || pending.current || captured.current || !selectedSource || !callbacks.current.begin() ) { return; } pending.current = true; const revision = ++generation.current; const abort = new AbortController(); controller.current = abort; prepared.current = null; setPhase('previewing'); setPreview(null); setError(''); setRetained(false); state(true, true); try { const result = selectedMode !== 'export' ? await backtestApiV2.previewStoredDataset( selectedSource.value, abort.signal, selectedMode === 'stored-eod-sessions' ? 'declared-sessions' : undefined ) : { input: selectedSource.value, preparation: await backtestApiV2.previewDataset(selectedSource.value, abort.signal), }; if (active.current && revision === generation.current) { prepared.current = { input: result.input, preview: result.preparation }; setPreview(result.preparation); } } catch (cause) { if (active.current && revision === generation.current) { setError(cause instanceof Error ? cause.message : 'Could not preview dataset'); } } finally { if (active.current && revision === generation.current) { pending.current = false; setPhase(null); state(false, true); } } }; const retain = async () => { if ( disabled || pending.current || (!captured.current && !prepared.current) || !callbacks.current.begin() ) { return; } const target = captured.current ?? (prepared.current ? structuredClone(prepared.current) : null); if (!target) { return; } captured.current = target; setIntent(target); pending.current = true; const revision = ++generation.current, abort = new AbortController(); controller.current = abort; setPhase('retaining'); setError(''); state(true, true); const reportRetained = callbacks.current.onRetained; let accepted = false; try { const result = await backtestApiV2.retainDataset( target.input, target.preview.hash, abort.signal ); if (canonicalStrategyJson(result) !== canonicalStrategyJson(target.preview)) { throw new Error('Retained dataset descriptor differs from its captured preview.'); } if (active.current && revision === generation.current) { accepted = result.available; prepared.current = null; setRetained(true); setPreview(result); captured.current = null; setIntent(null); reportRetained(result.hash, result.available); } } catch (cause) { if (active.current && revision === generation.current) { if ( cause instanceof DatasetPreparationRequestError && (cause.status === 400 || cause.status === 409) ) { captured.current = null; prepared.current = null; setIntent(null); setPreview(null); setError( `${cause.message} Preview again or choose a corrected ${modeRef.current === 'export' ? 'source export' : 'metadata file'}.` ); } else { setError( `${cause instanceof Error ? cause.message : 'Dataset retention response was lost'} Retry the exact same input and hash; retention may already have succeeded.` ); } } } finally { if (active.current && revision === generation.current) { pending.current = false; setPhase(null); state(false, !accepted); } } }; const sessionWindows = mode === 'stored-eod-sessions' && input ? storedSourceSessionScope(input.value) : null; return (

Supply complete metadata with exported bars or explicitly selected stored EOD intraday bars. Sessions, source revisions, universe, corporate actions and publication availability must be explicit. Declared provenance is not independent provider certification. Preview writes nothing; retention does not save settings or start a run.

{mode !== 'export' && (

Load one EOD instrument from existing storage using raw 1m, 5m or 1h interval-start bars. Supply complete metadata with interval-end-assumption availability. Source sequence is a deterministic sorted row ordinal, not a vendor sequence. The current store, history and declared revision are not independently certified. Preview reads a new snapshot; retention uses that captured snapshot without querying storage again.

)} {mode !== 'export' && ( )} {!input && !phase && !error && (

{mode === 'export' ? 'No source export selected.' : 'No source metadata selected.'}

)} {input && (

Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename}

)} {mode === 'stored-eod-sessions' && (

Reads only the declared calendar sessions intersecting warmup start through trading end. Rows outside those explicit windows are not requested. Invalid or empty selected sessions fail preparation; bars are never shortened to fit. This does not verify the calendar or establish gap-free coverage.

{sessionWindows === null ? (

Supply complete single-series metadata to view the declared UTC query windows.

) : sessionWindows.length === 0 ? (

No declared sessions intersect the requested bounds.

) : (
    {sessionWindows.map(window => (
  • {window.date}: {instant(window.start)} — {instant(window.end)} (end exclusive)
  • ))}
)}
)} {phase && (

{phase === 'reading' ? 'Reading source JSON...' : phase === 'previewing' ? 'Previewing dataset...' : 'Retaining dataset...'}

)}
{error &&

{error}

} {intent && !phase && (

Retention is unconfirmed. The exact original input and hash are preserved for retry.

)} {retained && (

Dataset retained.{' '} {preview?.available ? 'The canonical selection will be verified before settings can be saved.' : 'This data cannot be chosen for canonical execution. The existing selection is unchanged; clear preparation to continue editing.'}

)} {preview && (
{mode !== 'export' && (

Stored source: EOD ·{' '} {mode === 'stored-eod-sessions' ? 'Declared sessions within bounds' : 'Query bounds'}{' '} (UTC, end exclusive): {instant(preview.manifest.bounds.warmupStart)} —{' '} {instant(preview.manifest.bounds.tradeEnd)}

)}

Dataset hash: {preview.hash}

{preview.manifest.barCount} bars · Eligibility: {preview.manifest.eligibility} ·{' '} {preview.available ? 'Available for single-asset canonical setup' : 'Unavailable for canonical setup'}

{preview.reason &&

{preview.reason}

}

Warmup start (UTC): {instant(preview.manifest.bounds.warmupStart)}

Trading bounds (UTC, end exclusive): {instant(preview.manifest.bounds.tradeStart)} —{' '} {instant(preview.manifest.bounds.tradeEnd)}

{preview.manifest.series.map(series => (

{series.instrumentId} / {series.interval} · Series: {series.id} · Adjustment:{' '} {series.adjustment}

Timestamp: {series.timestamp} · Availability: {series.availability}

Source: {series.source.provider} · Revision: {series.source.revision}

{series.availability === 'interval-end-assumption' && (

Availability is explicitly assumed at interval end; actual publication delay is not verified.

)}
))} {preview.manifest.calendars.map(calendar => (

Calendar: {calendar.id} · Source: {calendar.source} · Revision: {calendar.revision} · Time zone: {calendar.timeZone} · Sessions: {calendar.sessions.length} · Coverage:{' '} {calendar.startDate} — {calendar.endDate}

))}

Universe: {preview.manifest.universe.selection} · As of:{' '} {preview.manifest.universe.asOf === null ? 'Unknown' : instant(preview.manifest.universe.asOf)}{' '} · Revision: {preview.manifest.universe.revision} · Instruments:{' '} {preview.manifest.universe.instrumentIds.join(', ')}

{preview.manifest.corporateActions.map(coverage => (

Corporate actions: {coverage.instrumentId} · {coverage.status} · Revision:{' '} {coverage.revision} · Coverage: {instant(coverage.start)} — {instant(coverage.end)}{' '} · Actions: {coverage.actions.length}

{coverage.actions.map((action, index) => (

{action.kind} · {instant(action.effectiveAt)} · {action.reference}

))}
))} {preview.manifest.limitations.map((limitation, index) => (

{limitation}

))}
Exact prepared manifest
              {JSON.stringify(preview.manifest, null, 2)}
            
)}
); }