feat(research): prepare and retain explicit source datasets in the web workbench
This commit is contained in:
parent
06039d17ba
commit
366bee810b
21 changed files with 2677 additions and 76 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
type CanonicalDatasetCatalogEntry,
|
||||
|
|
@ -19,6 +19,7 @@ import {
|
|||
type Backtest,
|
||||
type CreateBacktestRequest,
|
||||
} from '../services/backtestApiV2';
|
||||
import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation';
|
||||
|
||||
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
|
||||
const policyFields: {
|
||||
|
|
@ -280,6 +281,17 @@ export function CanonicalSetup({
|
|||
const [error, setError] = useState<string | null>(null);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const authoritative = useRef(backtest);
|
||||
const currentBacktest = useRef(backtest);
|
||||
currentBacktest.current = backtest;
|
||||
const preparationRef = useRef<DatasetPreparationState>({ busy: false, blocking: false });
|
||||
const [preparation, setPreparation] = useState(preparationRef.current);
|
||||
const preparationChanged = useCallback((value: DatasetPreparationState) => {
|
||||
preparationRef.current = value;
|
||||
setPreparation(value);
|
||||
if (value.blocking) {
|
||||
setDirty(true);
|
||||
}
|
||||
}, []);
|
||||
const pending = useRef(false);
|
||||
const active = useRef(true);
|
||||
useUnsavedWarning(dirty);
|
||||
|
|
@ -309,6 +321,8 @@ export function CanonicalSetup({
|
|||
});
|
||||
setStrategyValid(false);
|
||||
setEpoch(value => value + 1);
|
||||
preparationRef.current = { busy: false, blocking: false };
|
||||
setPreparation(preparationRef.current);
|
||||
setDirty(false);
|
||||
setError(null);
|
||||
}, [backtest]);
|
||||
|
|
@ -387,7 +401,15 @@ export function CanonicalSetup({
|
|||
);
|
||||
const save = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (locked || pending.current || !valid || !selectedFields || !parsed.settings) {
|
||||
if (
|
||||
locked ||
|
||||
pending.current ||
|
||||
preparationRef.current.busy ||
|
||||
preparationRef.current.blocking ||
|
||||
!valid ||
|
||||
!selectedFields ||
|
||||
!parsed.settings
|
||||
) {
|
||||
return;
|
||||
}
|
||||
pending.current = true;
|
||||
|
|
@ -543,6 +565,32 @@ export function CanonicalSetup({
|
|||
</div>
|
||||
</dl>
|
||||
)}
|
||||
<details className="space-y-3 rounded-md border border-border p-3">
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Prepare dataset from source export
|
||||
</summary>
|
||||
<DatasetPreparation
|
||||
key={`${backtest.id}:${epoch}`}
|
||||
disabled={locked}
|
||||
begin={() =>
|
||||
!disabled &&
|
||||
!pending.current &&
|
||||
active.current &&
|
||||
currentBacktest.current === backtest
|
||||
}
|
||||
onStateChange={preparationChanged}
|
||||
onRetained={(retainedHash, available) => {
|
||||
if (!active.current || currentBacktest.current !== backtest) {
|
||||
return;
|
||||
}
|
||||
if (available) {
|
||||
setHash(retainedHash);
|
||||
}
|
||||
setRetry(value => value + 1);
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
</details>
|
||||
<StrategySelection
|
||||
key={epoch}
|
||||
allowArchivedSelection
|
||||
|
|
@ -588,16 +636,28 @@ export function CanonicalSetup({
|
|||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button type="submit" className={actionClass} disabled={locked || !valid}>
|
||||
{preparation.blocking && (
|
||||
<p role="status">
|
||||
Retain an available dataset or clear source preparation before saving this setup.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={locked || preparation.busy || preparation.blocking || !valid}
|
||||
>
|
||||
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
|
||||
</button>{' '}
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
disabled={saving || preparation.busy}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
if (pending.current || preparationRef.current.busy) {
|
||||
return;
|
||||
}
|
||||
if (confirmDiscard(dirty || preparationRef.current.blocking)) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,373 @@
|
|||
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 } from '../services/backtestApiV2';
|
||||
|
||||
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;
|
||||
}
|
||||
const instant = (value: number) => new Date(value).toISOString();
|
||||
export function DatasetPreparation({ disabled, begin, onStateChange, onRetained }: Props) {
|
||||
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 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;
|
||||
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 = await backtestApiV2.previewDataset(selectedSource.value, abort.signal);
|
||||
if (active.current && revision === generation.current) {
|
||||
prepared.current = { input: selectedSource.value, preview: result };
|
||||
setPreview(result);
|
||||
}
|
||||
} 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 source export.`);
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section aria-label="Source dataset preparation" className="space-y-3 text-sm">
|
||||
<p>
|
||||
Supply a complete source export with metadata and 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">
|
||||
Source dataset JSON
|
||||
<input
|
||||
ref={fileInput}
|
||||
className={fieldClass}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
aria-label="Source dataset JSON"
|
||||
disabled={disabled || Boolean(intent)}
|
||||
onChange={event => void loadFile(event.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
{!input && !phase && !error && <p>No source export selected.</p>}
|
||||
{input && <p>Selected export: {input.filename}</p>}
|
||||
{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">
|
||||
<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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue