stock-bot/apps/stock/web-app/src/features/backtest/components/DatasetPreparation.tsx

473 lines
17 KiB
TypeScript

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<InputMode>('export');
const modeRef = useRef<InputMode>('export');
const [input, setInput] = useState<{ value: unknown; filename: string } | null>(null);
const [preview, setPreview] = useState<CanonicalDatasetPreparation | null>(null);
const [retained, setRetained] = useState(false),
[error, setError] = useState(''),
[phase, setPhase] = useState<'reading' | 'previewing' | 'retaining' | null>(null);
const [intent, setIntent] = useState<Retention | null>(null);
const source = useRef<{ value: unknown; filename: string } | null>(null);
const prepared = useRef<Retention | null>(null);
const generation = useRef(0),
active = useRef(false),
pending = useRef(false),
captured = useRef<Retention | null>(null),
controller = useRef<AbortController | null>(null),
fileInput = useRef<HTMLInputElement>(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 (
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
<p>
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.
</p>
<label className="block">
Dataset input
<select
aria-label="Dataset input"
className={fieldClass}
value={mode}
disabled={disabled || Boolean(intent)}
onChange={event => changeMode(event.target.value)}
>
<option value="export">Source export</option>
<option value="stored-eod">Stored EOD intraday bars</option>
<option value="stored-eod-sessions">Stored EOD — declared sessions only</option>
</select>
</label>
{mode !== 'export' && (
<p>
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.
</p>
)}
{mode !== 'export' && (
<StoredSourceInspector disabled={disabled || Boolean(intent) || Boolean(phase)} />
)}
<label className="block">
{mode === 'export' ? 'Source dataset JSON' : 'Source metadata JSON'}
<input
ref={fileInput}
className={fieldClass}
type="file"
accept="application/json,.json"
aria-label={mode === 'export' ? 'Source dataset JSON' : 'Source metadata JSON'}
disabled={disabled || Boolean(intent)}
onChange={event => void loadFile(event.target.files?.[0])}
/>
</label>
{!input && !phase && !error && (
<p>{mode === 'export' ? 'No source export selected.' : 'No source metadata selected.'}</p>
)}
{input && (
<p>
Selected {mode === 'export' ? 'export' : 'metadata'}: {input.filename}
</p>
)}
{mode === 'stored-eod-sessions' && (
<section aria-label="Declared session selection" className="space-y-2">
<p>
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.
</p>
{sessionWindows === null ? (
<p>Supply complete single-series metadata to view the declared UTC query windows.</p>
) : sessionWindows.length === 0 ? (
<p>No declared sessions intersect the requested bounds.</p>
) : (
<ul aria-label="Declared UTC query windows">
{sessionWindows.map(window => (
<li key={window.date}>
{window.date}: {instant(window.start)} — {instant(window.end)} (end exclusive)
</li>
))}
</ul>
)}
</section>
)}
{phase && (
<p role="status">
{phase === 'reading'
? 'Reading source JSON...'
: phase === 'previewing'
? 'Previewing dataset...'
: 'Retaining dataset...'}
</p>
)}
<div className="flex flex-wrap gap-2">
<button
type="button"
className={actionClass}
disabled={disabled || Boolean(phase) || Boolean(intent) || !input}
onClick={() => void inspect()}
>
Preview dataset
</button>
<button
type="button"
className={actionClass}
disabled={disabled || Boolean(phase) || retained || (!preview && !intent)}
onClick={() => void retain()}
>
{intent ? 'Retry retaining same dataset' : 'Retain dataset'}
</button>
<button
type="button"
className={actionClass}
disabled={disabled || phase === 'retaining'}
onClick={() => {
if (disabled || (pending.current && captured.current) || !callbacks.current.begin()) {
return;
}
if (
!captured.current ||
window.confirm(
'This dataset may already be retained. Clear this preparation and discard its exact retry input and hash?'
)
) {
reset();
}
}}
>
Clear source preparation
</button>
</div>
{error && <p role="alert">{error}</p>}
{intent && !phase && (
<p>Retention is unconfirmed. The exact original input and hash are preserved for retry.</p>
)}
{retained && (
<p role="status">
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.'}
</p>
)}
{preview && (
<section aria-label="Prepared dataset metadata" className="space-y-2 break-words">
{mode !== 'export' && (
<p>
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)}
</p>
)}
<p className="break-all">Dataset hash: {preview.hash}</p>
<p>
{preview.manifest.barCount} bars · Eligibility: {preview.manifest.eligibility} ·{' '}
{preview.available
? 'Available for single-asset canonical setup'
: 'Unavailable for canonical setup'}
</p>
{preview.reason && <p>{preview.reason}</p>}
<p>Warmup start (UTC): {instant(preview.manifest.bounds.warmupStart)}</p>
<p>
Trading bounds (UTC, end exclusive): {instant(preview.manifest.bounds.tradeStart)} —{' '}
{instant(preview.manifest.bounds.tradeEnd)}
</p>
{preview.manifest.series.map(series => (
<div key={series.id} className="space-y-1">
<p>
{series.instrumentId} / {series.interval} · Series: {series.id} · Adjustment:{' '}
{series.adjustment}
</p>
<p>
Timestamp: {series.timestamp} · Availability: {series.availability}
</p>
<p>
Source: {series.source.provider} · Revision: {series.source.revision}
</p>
{series.availability === 'interval-end-assumption' && (
<p>
Availability is explicitly assumed at interval end; actual publication delay is
not verified.
</p>
)}
</div>
))}
{preview.manifest.calendars.map(calendar => (
<p key={calendar.id}>
Calendar: {calendar.id} · Source: {calendar.source} · Revision: {calendar.revision} ·
Time zone: {calendar.timeZone} · Sessions: {calendar.sessions.length} · Coverage:{' '}
{calendar.startDate} — {calendar.endDate}
</p>
))}
<p>
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(', ')}
</p>
{preview.manifest.corporateActions.map(coverage => (
<div key={coverage.instrumentId}>
<p>
Corporate actions: {coverage.instrumentId} · {coverage.status} · Revision:{' '}
{coverage.revision} · Coverage: {instant(coverage.start)} — {instant(coverage.end)}{' '}
· Actions: {coverage.actions.length}
</p>
{coverage.actions.map((action, index) => (
<p key={index}>
{action.kind} · {instant(action.effectiveAt)} · {action.reference}
</p>
))}
</div>
))}
{preview.manifest.limitations.map((limitation, index) => (
<p key={index}>{limitation}</p>
))}
<details>
<summary className="cursor-pointer">Exact prepared manifest</summary>
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
{JSON.stringify(preview.manifest, null, 2)}
</pre>
</details>
</section>
)}
</section>
);
}