542 lines
21 KiB
TypeScript
542 lines
21 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { Link, useParams } from 'react-router-dom';
|
|
import type { ChronologicalValidationActionReceipt } from '@stock-bot/stock-config/chronological-validation';
|
|
import { Button } from '@/components/ui/Button';
|
|
import { chronologicalFindingSource } from '@/features/research/services/findingSources';
|
|
import { useUnsavedWarning } from '@/hooks/useUnsavedWarning';
|
|
import { ExperimentCounts } from './components/ExperimentCounts';
|
|
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
|
|
import { SourceFindingAction } from './components/SourceFindingAction';
|
|
import { ValidationEvidence } from './components/ValidationEvidence';
|
|
import {
|
|
chronologicalValidationDurableApi,
|
|
ValidationApiError,
|
|
type ValidationDetailView,
|
|
} from './services/chronologicalValidationDurableApi';
|
|
|
|
export function ChronologicalValidationDetailPage() {
|
|
const { validationId = '' } = useParams<{ validationId: string }>();
|
|
return <ValidationDetail key={validationId} validationId={validationId} />;
|
|
}
|
|
type Intent =
|
|
| { id: string; operation: 'select'; body: { previewHash: string }; key: string }
|
|
| {
|
|
id: string;
|
|
operation: 'finalize';
|
|
body: { previewHash: string; selectionHash: string };
|
|
key: string;
|
|
};
|
|
function ValidationDetail({ validationId }: { validationId: string }) {
|
|
const [findingDirty, setFindingDirty] = useState(false);
|
|
const alive = useRef(false),
|
|
pending = useRef(false),
|
|
reading = useRef(true),
|
|
generation = useRef(0),
|
|
read = useRef<AbortController | null>(null);
|
|
const captured = useRef<Intent | null>(null);
|
|
const [intent, setIntent] = useState<Intent | null>(null);
|
|
const [validation, setValidation] = useState<ValidationDetailView | null>(null);
|
|
const [loading, setLoading] = useState(true),
|
|
[busy, setBusy] = useState(false),
|
|
[reload, setReload] = useState(0);
|
|
const [readError, setReadError] = useState(''),
|
|
[actionError, setActionError] = useState('');
|
|
const [ambiguous, setAmbiguous] = useState(false),
|
|
[receipt, setReceipt] = useState<ChronologicalValidationActionReceipt | null>(null);
|
|
useUnsavedWarning(Boolean(intent));
|
|
useEffect(() => {
|
|
alive.current = true;
|
|
return () => {
|
|
alive.current = false;
|
|
generation.current++;
|
|
read.current?.abort();
|
|
};
|
|
}, []);
|
|
useEffect(() => {
|
|
if (pending.current) {
|
|
return;
|
|
}
|
|
let current = true;
|
|
const revision = ++generation.current,
|
|
controller = new AbortController();
|
|
read.current = controller;
|
|
reading.current = true;
|
|
setLoading(true);
|
|
setReadError('');
|
|
void chronologicalValidationDurableApi
|
|
.get(validationId, controller.signal)
|
|
.then(value => {
|
|
if (current && revision === generation.current) {
|
|
setValidation(value);
|
|
}
|
|
})
|
|
.catch(cause => {
|
|
if (current && revision === generation.current) {
|
|
setReadError(cause instanceof Error ? cause.message : 'Could not load validation');
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (current && revision === generation.current) {
|
|
reading.current = false;
|
|
setLoading(false);
|
|
}
|
|
});
|
|
return () => {
|
|
current = false;
|
|
controller.abort();
|
|
};
|
|
}, [validationId, reload]);
|
|
const begin = () => {
|
|
if (pending.current || reading.current) {
|
|
return false;
|
|
}
|
|
pending.current = true;
|
|
generation.current++;
|
|
read.current?.abort();
|
|
setLoading(false);
|
|
setBusy(true);
|
|
setActionError('');
|
|
return true;
|
|
};
|
|
const finish = () => {
|
|
pending.current = false;
|
|
if (alive.current) {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
const advance = async (operation: 'select' | 'finalize') => {
|
|
if (pending.current || reading.current || loading || !validation) {
|
|
return;
|
|
}
|
|
if (!captured.current) {
|
|
if (
|
|
!validation.actions[operation].available ||
|
|
(operation === 'finalize' && !validation.selection)
|
|
) {
|
|
return;
|
|
}
|
|
captured.current =
|
|
operation === 'select'
|
|
? {
|
|
id: validationId,
|
|
operation,
|
|
body: { previewHash: validation.previewHash },
|
|
key: crypto.randomUUID(),
|
|
}
|
|
: {
|
|
id: validationId,
|
|
operation,
|
|
body: {
|
|
previewHash: validation.previewHash,
|
|
selectionHash: validation.selection?.selectionHash ?? '',
|
|
},
|
|
key: crypto.randomUUID(),
|
|
};
|
|
setIntent(captured.current);
|
|
setReceipt(null);
|
|
}
|
|
const original = captured.current;
|
|
if (!begin()) {
|
|
return;
|
|
}
|
|
try {
|
|
const result = await chronologicalValidationDurableApi.advance(
|
|
original.id,
|
|
original.operation,
|
|
original.body,
|
|
original.key
|
|
);
|
|
if (alive.current) {
|
|
captured.current = null;
|
|
setIntent(null);
|
|
setAmbiguous(false);
|
|
setReceipt(result.receipt);
|
|
setValidation(result.validation);
|
|
}
|
|
} catch (cause) {
|
|
if (alive.current) {
|
|
setActionError(cause instanceof Error ? cause.message : 'Could not advance validation');
|
|
setAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous);
|
|
}
|
|
} finally {
|
|
finish();
|
|
}
|
|
};
|
|
const cancel = async () => {
|
|
if (loading || !validation || !begin()) {
|
|
return;
|
|
}
|
|
try {
|
|
const value = await chronologicalValidationDurableApi.cancel(validationId);
|
|
if (alive.current) {
|
|
setValidation(value);
|
|
}
|
|
} catch (cause) {
|
|
if (alive.current) {
|
|
setActionError(
|
|
`${cause instanceof Error ? cause.message : 'Cancellation failed'}. Refresh to verify cancellation or retry the request.`
|
|
);
|
|
}
|
|
} finally {
|
|
finish();
|
|
}
|
|
};
|
|
const discard = () => {
|
|
if (
|
|
pending.current ||
|
|
!window.confirm(
|
|
'Discard this action request? It may already have succeeded. Refresh the saved validation before preparing another action.'
|
|
)
|
|
) {
|
|
return;
|
|
}
|
|
captured.current = null;
|
|
setIntent(null);
|
|
setActionError('');
|
|
setAmbiguous(false);
|
|
};
|
|
return (
|
|
<div
|
|
className="h-full overflow-auto p-1 space-y-4"
|
|
onClickCapture={event => {
|
|
const findingLink = (event.target as HTMLElement).closest('a');
|
|
if (
|
|
findingLink &&
|
|
(!findingLink.target || findingLink.target === '_self') &&
|
|
findingDirty &&
|
|
!event.ctrlKey &&
|
|
!event.metaKey &&
|
|
!event.shiftKey &&
|
|
!window.confirm(
|
|
'Leave this finding draft? The previous request may already have saved if its response was lost. Inspect saved records before submitting again.'
|
|
)
|
|
) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
return;
|
|
}
|
|
if (
|
|
(event.target as HTMLElement).closest('a') &&
|
|
captured.current &&
|
|
!event.ctrlKey &&
|
|
!event.metaKey &&
|
|
!event.shiftKey &&
|
|
!window.confirm(
|
|
'Leave this unconfirmed validation action? Its exact body and key will be discarded. You can inspect evidence in another tab.'
|
|
)
|
|
) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
}
|
|
}}
|
|
>
|
|
<Link to="/experiments" className="text-primary-500 text-sm">
|
|
All experiments
|
|
</Link>
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<h1 className="text-lg font-bold">{validation?.name ?? 'Chronological validation'}</h1>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={loading || busy}
|
|
onClick={() => {
|
|
if (!pending.current && !reading.current) {
|
|
reading.current = true;
|
|
generation.current++;
|
|
read.current?.abort();
|
|
setReload(value => value + 1);
|
|
}
|
|
}}
|
|
>
|
|
Refresh validation
|
|
</Button>
|
|
</div>
|
|
{loading && <p role="status">Loading validation...</p>}
|
|
{readError && (
|
|
<p role="alert" className="text-error">
|
|
{readError}
|
|
{validation && ' Showing the last loaded state.'}
|
|
</p>
|
|
)}
|
|
{actionError && (
|
|
<p role="alert" className="text-error">
|
|
{actionError}
|
|
</p>
|
|
)}
|
|
{intent && (
|
|
<div className="space-y-2">
|
|
<p role="status">
|
|
{ambiguous ? 'Action acceptance is unconfirmed. ' : ''}This request still targets{' '}
|
|
{intent.operation === 'select'
|
|
? 'selection and holdout admission'
|
|
: 'report finalization'}{' '}
|
|
with its exact saved body and key.
|
|
</p>
|
|
<Button disabled={busy || loading} onClick={() => void advance(intent.operation)}>
|
|
{intent.operation === 'select' ? 'Retry selection request' : 'Retry report request'}
|
|
</Button>{' '}
|
|
<Button variant="outline" disabled={busy} onClick={discard}>
|
|
Discard action request
|
|
</Button>
|
|
</div>
|
|
)}
|
|
{receipt && (
|
|
<p role="status">
|
|
{receipt.operation === 'select-and-admit-holdouts'
|
|
? 'Selection and holdout admission accepted.'
|
|
: 'Report finalization accepted.'}{' '}
|
|
Receipt {receipt.id} · {receipt.createdAt}
|
|
</p>
|
|
)}
|
|
{validation && (
|
|
<>
|
|
<RegimeEvidenceUnavailable />
|
|
{!validation.report && (
|
|
<SourceFindingAction
|
|
source={null}
|
|
disabled
|
|
onDirtyChange={setFindingDirty}
|
|
unavailable="Save the complete report before linking its evidence to a research finding."
|
|
/>
|
|
)}
|
|
<p className="font-semibold">
|
|
{validation.report
|
|
? 'Execution complete · report saved'
|
|
: validation.selection
|
|
? 'Fixed selection saved · validation and test admitted'
|
|
: 'Training candidates admitted · selection not yet frozen'}
|
|
</p>
|
|
<p className="text-sm">
|
|
{validation.trainingCandidateCount} training candidates; one validation run and one test
|
|
run after selection. Each phase resets initial capital and positions. No combined
|
|
portfolio equity curve is produced.
|
|
</p>
|
|
{validation.cancelRequested && (
|
|
<p>
|
|
Cancellation requested. Completed evidence remains retained; active work may still
|
|
finish.
|
|
</p>
|
|
)}
|
|
{!intent && (
|
|
<div className="flex flex-wrap gap-2">
|
|
{!validation.selection && (
|
|
<Button
|
|
disabled={busy || loading || !validation.actions.select.available}
|
|
onClick={() => void advance('select')}
|
|
>
|
|
Freeze selection and run holdouts
|
|
</Button>
|
|
)}
|
|
{validation.selection && !validation.report && (
|
|
<Button
|
|
disabled={busy || loading || !validation.actions.finalize.available}
|
|
onClick={() => void advance('finalize')}
|
|
>
|
|
Save validation report
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{!validation.selection && validation.actions.select.reason && (
|
|
<p>{validation.actions.select.reason}</p>
|
|
)}
|
|
{validation.selection && !validation.report && validation.actions.finalize.reason && (
|
|
<p>{validation.actions.finalize.reason}</p>
|
|
)}
|
|
{!validation.cancelRequested && !validation.report && (
|
|
<Button
|
|
variant="danger"
|
|
size="sm"
|
|
disabled={busy || loading}
|
|
onClick={() => void cancel()}
|
|
>
|
|
Cancel remaining validation work
|
|
</Button>
|
|
)}
|
|
<section aria-label="Frozen chronological recipe" className="space-y-2 text-sm">
|
|
<h2 className="font-semibold">Frozen chronological recipe</h2>
|
|
<p>
|
|
Train selection maximizes total return; ties use the original candidate index. Every
|
|
candidate is required. Validation is diagnostic only; test is holdout only. Neither
|
|
retunes the fixed selection.
|
|
</p>
|
|
<p>
|
|
Initial capital (USD):{' '}
|
|
{validation.preview.source.request.policy.matching.risk.ledger.initialCapital} · Owner
|
|
budget: {validation.preview.source.request.strategy.selection.ownerBudget} · Seed:{' '}
|
|
{validation.preview.source.request.strategy.selection.seed}
|
|
</p>
|
|
<p>
|
|
Selection uses training results only in this workflow. These dates may have been
|
|
examined in other research.
|
|
</p>
|
|
<div className="grid gap-3 lg:grid-cols-3">
|
|
{validation.preview.partitions.map(part => (
|
|
<article
|
|
key={part.phase}
|
|
className="border border-border rounded p-3 break-all text-xs"
|
|
>
|
|
<h3 className="font-semibold">{part.phase} window</h3>
|
|
<p>Warmup: {new Date(part.dataset.bounds.warmupStart).toISOString()}</p>
|
|
<p>
|
|
Trading: {new Date(part.dataset.bounds.tradeStart).toISOString()} —{' '}
|
|
{new Date(part.dataset.bounds.tradeEnd).toISOString()} (end exclusive)
|
|
</p>
|
|
<p>Dataset: {part.dataset.hash}</p>
|
|
<p>
|
|
Admitted / required warmup: {part.counts.admittedWarmup} / {part.requiredWarmup}
|
|
</p>
|
|
{part.warnings.map((warning, index) => (
|
|
<p key={index}>{warning}</p>
|
|
))}
|
|
</article>
|
|
))}
|
|
</div>
|
|
<details>
|
|
<summary className="cursor-pointer">Exact retained recipe and policies</summary>
|
|
<pre className="max-h-80 overflow-auto whitespace-pre-wrap break-all text-xs">
|
|
{JSON.stringify(
|
|
{
|
|
previewHash: validation.previewHash,
|
|
input: validation.preview.input,
|
|
policy: validation.preview.policy,
|
|
sourceDataset: validation.preview.source.request.datasetHash,
|
|
strategyVersion: validation.preview.source.request.strategy.versionId,
|
|
sourceReview: validation.preview.source.request.strategy.reviewId,
|
|
artifactHash:
|
|
validation.preview.source.request.strategy.package.artifact.sha256,
|
|
build: validation.preview.source.request.build,
|
|
financialPolicy: validation.preview.source.request.policy,
|
|
analyticsPolicy: validation.preview.source.request.analyticsPolicy,
|
|
},
|
|
null,
|
|
2
|
|
)}
|
|
</pre>
|
|
</details>
|
|
</section>
|
|
<section aria-label="Validation phase outcomes" className="space-y-3">
|
|
<h2 className="font-semibold">Phase outcomes</h2>
|
|
{validation.phases.map(phase => (
|
|
<article
|
|
key={phase.phase}
|
|
aria-label={`${phase.phase} outcomes`}
|
|
className="border border-border rounded p-3 space-y-2"
|
|
>
|
|
<h3 className="font-semibold">{phase.phase}</h3>
|
|
{phase.status === 'not-admitted' && (
|
|
<p>
|
|
Not admitted. No {phase.phase} run exists before the fixed selection is saved.
|
|
</p>
|
|
)}
|
|
{phase.status === 'missing' && (
|
|
<p role="alert">
|
|
Expected {phase.phase} experiment is missing. Report finalization is blocked.
|
|
</p>
|
|
)}
|
|
{phase.experiment && (
|
|
<>
|
|
<ExperimentCounts experiment={phase.experiment} />
|
|
<ul className="space-y-2 text-sm">
|
|
{phase.experiment.trials.map(trial => (
|
|
<li key={trial.trialKey}>
|
|
Candidate{' '}
|
|
{phase.phase === 'train'
|
|
? trial.index + 1
|
|
: (validation.selection?.winner.index ?? 0) + 1}{' '}
|
|
· {trial.status} · {trial.progress}% ·{' '}
|
|
{trial.comparable
|
|
? 'Comparable'
|
|
: trial.status === 'completed'
|
|
? 'Incomparable'
|
|
: 'Not evaluated'}
|
|
<pre className="text-xs">{JSON.stringify(trial.parameters)}</pre>
|
|
{trial.error && <p className="text-error">{trial.error}</p>}
|
|
{trial.diagnostic && <p>{trial.diagnostic}</p>}
|
|
<p>
|
|
Total return (fraction):{' '}
|
|
{trial.metrics?.totalReturn === null ||
|
|
trial.metrics?.totalReturn === undefined
|
|
? `Unavailable${trial.unavailable?.totalReturn ? `: ${trial.unavailable.totalReturn}` : ''}`
|
|
: String(trial.metrics.totalReturn)}
|
|
</p>
|
|
{trial.runId && (
|
|
<Link
|
|
className="text-primary-500"
|
|
to={`/backtests/${encodeURIComponent(validation.backtestId)}/run/${encodeURIComponent(trial.runId)}`}
|
|
>
|
|
Open {phase.phase} run {trial.index + 1}
|
|
</Link>
|
|
)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</>
|
|
)}
|
|
{phase.experimentId && (
|
|
<Link
|
|
className="text-primary-500 text-sm"
|
|
to={`/experiments/${encodeURIComponent(phase.experimentId)}`}
|
|
>
|
|
Open {phase.phase} experiment
|
|
</Link>
|
|
)}
|
|
</article>
|
|
))}
|
|
</section>
|
|
{validation.selection && (
|
|
<section aria-label="Fixed training selection" className="space-y-2">
|
|
<h2 className="font-semibold">Fixed training selection</h2>
|
|
<p>Selected training candidate {validation.selection.winner.index + 1}</p>
|
|
<pre className="text-xs">
|
|
{JSON.stringify(validation.selection.winner.parameters, null, 2)}
|
|
</pre>
|
|
<p className="break-all text-xs">
|
|
Selection {validation.selection.id} · {validation.selection.selectionHash} ·{' '}
|
|
{validation.selection.createdAt} · {validation.selection.principal}
|
|
</p>
|
|
<p className="break-all text-xs">
|
|
Holdout admission approval: {validation.selection.reviewId}
|
|
</p>
|
|
</section>
|
|
)}
|
|
{validation.selection && (
|
|
<ValidationEvidence
|
|
title="All retained training evidence"
|
|
items={validation.report?.training ?? validation.selection.training}
|
|
backtestId={validation.backtestId}
|
|
/>
|
|
)}
|
|
{validation.report && (
|
|
<section aria-label="Saved validation report" className="space-y-3">
|
|
<h2 className="font-semibold">Saved validation report</h2>
|
|
<SourceFindingAction
|
|
key={validation.report.reportHash}
|
|
source={chronologicalFindingSource(validation)}
|
|
disabled={loading || busy || Boolean(intent)}
|
|
onDirtyChange={setFindingDirty}
|
|
unavailable="A sealed report is required to cite this source."
|
|
/>
|
|
<p className="break-all text-xs">
|
|
Report {validation.report.id} · {validation.report.reportHash} ·{' '}
|
|
{validation.report.createdAt} · {validation.report.principal}
|
|
</p>
|
|
<p>
|
|
Independent reset accounts. No return compounding, portfolio stitching or OOS
|
|
parameter ranking is applied.
|
|
</p>
|
|
{validation.report.limitations.map((value, index) => (
|
|
<p key={index}>{value}</p>
|
|
))}
|
|
<ValidationEvidence
|
|
title="Retained validation and test evidence"
|
|
items={[validation.report.validation, validation.report.test]}
|
|
backtestId={validation.backtestId}
|
|
/>
|
|
</section>
|
|
)}
|
|
</>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|