feat(research): run durable chronological validation and retain reports
This commit is contained in:
parent
67ab30cb7a
commit
abd1c5b83d
42 changed files with 5345 additions and 74 deletions
|
|
@ -0,0 +1,506 @@
|
|||
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 { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
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 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 => {
|
||||
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 && (
|
||||
<>
|
||||
<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>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import type { ExperimentSummary } from '@stock-bot/stock-config/experiments';
|
|||
import { Button } from '@/components/ui/Button';
|
||||
import { ExperimentCounts } from './components/ExperimentCounts';
|
||||
import { ExperimentEditor } from './components/ExperimentEditor';
|
||||
import { SavedChronologicalValidations } from './components/SavedChronologicalValidations';
|
||||
import { experimentApi } from './services/experimentApi';
|
||||
|
||||
export function ExperimentListPage() {
|
||||
|
|
@ -71,6 +72,7 @@ function ExperimentList({ backtestId }: { backtestId: string }) {
|
|||
</p>
|
||||
</div>
|
||||
<ExperimentEditor initialBacktestId={backtestId} onDirty={setDirty} />
|
||||
<SavedChronologicalValidations backtestId={backtestId} />
|
||||
<section aria-label="Saved experiments" className="space-y-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved experiments</h2>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ValidationPhase,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
|
|
@ -9,6 +11,10 @@ import {
|
|||
chronologicalValidationApi,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from '../services/chronologicalValidationApi';
|
||||
import {
|
||||
chronologicalValidationDurableApi,
|
||||
ValidationApiError,
|
||||
} from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
const phases = ['train', 'validation', 'test'] as const;
|
||||
const fields = ['warmupStart', 'tradeStart', 'tradeEnd'] as const;
|
||||
|
|
@ -55,6 +61,8 @@ export function ChronologicalValidationPreflight({
|
|||
disabled,
|
||||
eligible,
|
||||
onDirty,
|
||||
claimSubmission,
|
||||
releaseSubmission,
|
||||
}: {
|
||||
backtestId: string;
|
||||
name: string;
|
||||
|
|
@ -62,7 +70,20 @@ export function ChronologicalValidationPreflight({
|
|||
disabled: boolean;
|
||||
eligible: boolean;
|
||||
onDirty: (dirty: boolean) => void;
|
||||
claimSubmission: (owner: 'ordinary' | 'chronological') => boolean;
|
||||
releaseSubmission: (owner: 'ordinary' | 'chronological') => void;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const trainingIntent = useRef<{
|
||||
body: ChronologicalValidationSubmission;
|
||||
key: string;
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
} | null>(null);
|
||||
const trainingPending = useRef(false);
|
||||
const [hasTrainingIntent, setHasTrainingIntent] = useState(false);
|
||||
const [submittingTraining, setSubmittingTraining] = useState(false);
|
||||
const [trainingError, setTrainingError] = useState('');
|
||||
const [trainingAmbiguous, setTrainingAmbiguous] = useState(false);
|
||||
const [windows, setWindows] = useState<Windows>(empty);
|
||||
const [prepared, setPrepared] = useState<{
|
||||
identity: string;
|
||||
|
|
@ -77,8 +98,10 @@ export function ChronologicalValidationPreflight({
|
|||
const identity = JSON.stringify({ backtestId, name, grid, windows, disabled, eligible });
|
||||
const currentIdentity = useRef(identity);
|
||||
currentIdentity.current = identity;
|
||||
const preview = prepared?.identity === identity ? prepared.preview : null;
|
||||
const dirty = phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
const preview =
|
||||
trainingIntent.current?.preview ?? (prepared?.identity === identity ? prepared.preview : null);
|
||||
const dirty =
|
||||
hasTrainingIntent || phases.some(phase => fields.some(field => windows[phase][field] !== ''));
|
||||
useEffect(() => {
|
||||
onDirty(dirty);
|
||||
}, [dirty, onDirty]);
|
||||
|
|
@ -99,7 +122,7 @@ export function ChronologicalValidationPreflight({
|
|||
setError('');
|
||||
}, [identity]);
|
||||
const edit = (phase: ValidationPhase, field: (typeof fields)[number], value: string) => {
|
||||
if (disabled) {
|
||||
if (disabled || trainingIntent.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -107,7 +130,7 @@ export function ChronologicalValidationPreflight({
|
|||
setWindows(previous => ({ ...previous, [phase]: { ...previous[phase], [field]: value } }));
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || !eligible || pending.current) {
|
||||
if (disabled || trainingIntent.current || !eligible || pending.current) {
|
||||
return;
|
||||
}
|
||||
const captured = identity;
|
||||
|
|
@ -166,6 +189,66 @@ export function ChronologicalValidationPreflight({
|
|||
}
|
||||
}
|
||||
};
|
||||
const submitTraining = async () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
pending.current ||
|
||||
(!trainingIntent.current && (!preview || disabled || !eligible)) ||
|
||||
!claimSubmission('chronological')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (!trainingIntent.current) {
|
||||
if (!preview) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = {
|
||||
body: { ...preview.input, previewHash: preview.previewHash },
|
||||
key: crypto.randomUUID(),
|
||||
preview,
|
||||
};
|
||||
}
|
||||
const captured = trainingIntent.current;
|
||||
trainingPending.current = true;
|
||||
setHasTrainingIntent(true);
|
||||
setSubmittingTraining(true);
|
||||
setTrainingError('');
|
||||
try {
|
||||
const accepted = await chronologicalValidationDurableApi.submit(captured.body, captured.key);
|
||||
if (alive.current) {
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
releaseSubmission('chronological');
|
||||
navigate(`/experiments/validation/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setTrainingError(message(cause));
|
||||
setTrainingAmbiguous(!(cause instanceof ValidationApiError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
trainingPending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmittingTraining(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const discardTraining = () => {
|
||||
if (
|
||||
trainingPending.current ||
|
||||
!window.confirm(
|
||||
'Discard this training submission? It may already exist. Inspect saved chronological validations before creating another.'
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
trainingIntent.current = null;
|
||||
setHasTrainingIntent(false);
|
||||
setTrainingError('');
|
||||
setTrainingAmbiguous(false);
|
||||
setPrepared(null);
|
||||
releaseSubmission('chronological');
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Chronological validation preflight"
|
||||
|
|
@ -173,8 +256,8 @@ export function ChronologicalValidationPreflight({
|
|||
>
|
||||
<h3 className="font-semibold text-text-primary">Chronological validation preflight</h3>
|
||||
<p>
|
||||
Preview only. No datasets, experiments or runs are saved. Staged execution and immutable
|
||||
reports are not available yet.
|
||||
Previewing does not save datasets, experiments or runs. Submit training runs explicitly to
|
||||
start a durable validation; selection and report finalization require separate actions.
|
||||
</p>
|
||||
<p className="text-text-secondary">
|
||||
Uses the saved backtest, experiment name and parameter grid above. Enter explicit UTC
|
||||
|
|
@ -185,7 +268,7 @@ export function ChronologicalValidationPreflight({
|
|||
{phases.map(phase => (
|
||||
<fieldset
|
||||
key={phase}
|
||||
disabled={disabled}
|
||||
disabled={disabled || hasTrainingIntent}
|
||||
className="space-y-2 rounded border border-border p-3"
|
||||
>
|
||||
<legend className="px-1 font-medium">{phaseLabels[phase]} window</legend>
|
||||
|
|
@ -212,7 +295,7 @@ export function ChronologicalValidationPreflight({
|
|||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled || !eligible || !name.trim() || loading}
|
||||
disabled={disabled || hasTrainingIntent || !eligible || !name.trim() || loading}
|
||||
onClick={() => void prepare()}
|
||||
>
|
||||
Preview chronological validation
|
||||
|
|
@ -223,6 +306,36 @@ export function ChronologicalValidationPreflight({
|
|||
{error}
|
||||
</p>
|
||||
)}
|
||||
{trainingError && (
|
||||
<p role="alert" className="text-error">
|
||||
{trainingError}
|
||||
</p>
|
||||
)}
|
||||
{hasTrainingIntent && (
|
||||
<p role="status">
|
||||
{trainingAmbiguous ? 'Training admission is unconfirmed. ' : ''}The exact training input
|
||||
and submission key are retained. Retry this submission to recover the same validation.
|
||||
</p>
|
||||
)}
|
||||
{(preview || hasTrainingIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
disabled={submittingTraining || (!hasTrainingIntent && (disabled || loading))}
|
||||
onClick={() => void submitTraining()}
|
||||
>
|
||||
{submittingTraining
|
||||
? 'Submitting training runs...'
|
||||
: hasTrainingIntent
|
||||
? 'Retry training submission'
|
||||
: 'Submit training runs'}
|
||||
</Button>
|
||||
{hasTrainingIntent && (
|
||||
<Button variant="outline" disabled={submittingTraining} onClick={discardTraining}>
|
||||
Discard training submission
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!preview && !loading && !error && (
|
||||
<p className="text-text-secondary">
|
||||
No chronological preview prepared for the current inputs.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
|
|
@ -49,6 +49,28 @@ export function ExperimentEditor({
|
|||
const previewRequest = useRef<AbortController | null>(null);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ body: ExperimentSubmission; key: string } | null>(null);
|
||||
const submissionOwner = useRef<'ordinary' | 'chronological' | null>(null);
|
||||
const [lockedBy, setLockedBy] = useState<'ordinary' | 'chronological' | null>(null);
|
||||
const claimSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
if (submissionOwner.current && submissionOwner.current !== owner) {
|
||||
return false;
|
||||
}
|
||||
submissionOwner.current = owner;
|
||||
setLockedBy(owner);
|
||||
if (owner === 'chronological') {
|
||||
generation.current++;
|
||||
previewRequest.current?.abort();
|
||||
setPreview(null);
|
||||
setPreviewLoading(false);
|
||||
}
|
||||
return true;
|
||||
}, []);
|
||||
const releaseSubmission = useCallback((owner: 'ordinary' | 'chronological') => {
|
||||
if (submissionOwner.current === owner) {
|
||||
submissionOwner.current = null;
|
||||
setLockedBy(null);
|
||||
}
|
||||
}, []);
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
||||
const [name, setName] = useState('');
|
||||
|
|
@ -117,7 +139,7 @@ export function ExperimentEditor({
|
|||
}, [initialBacktestId, templateReload, limit]);
|
||||
|
||||
const invalidate = (change: () => void) => {
|
||||
if (intent.current) {
|
||||
if (submissionOwner.current) {
|
||||
return;
|
||||
}
|
||||
generation.current++;
|
||||
|
|
@ -128,7 +150,7 @@ export function ExperimentEditor({
|
|||
change();
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (intent.current || previewLoading) {
|
||||
if (submissionOwner.current || previewLoading) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
|
|
@ -155,7 +177,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !preview)) {
|
||||
if (pending.current || (!intent.current && !preview) || !claimSubmission('ordinary')) {
|
||||
return;
|
||||
}
|
||||
if (!intent.current) {
|
||||
|
|
@ -177,6 +199,7 @@ export function ExperimentEditor({
|
|||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
navigate(`/experiments/${encodeURIComponent(accepted.id)}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
|
|
@ -202,6 +225,7 @@ export function ExperimentEditor({
|
|||
}
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
releaseSubmission('ordinary');
|
||||
setAmbiguous(false);
|
||||
setPreview(null);
|
||||
setError('');
|
||||
|
|
@ -240,7 +264,7 @@ export function ExperimentEditor({
|
|||
<select
|
||||
className={fieldClass}
|
||||
value={backtestId}
|
||||
disabled={hasIntent || templateLoading}
|
||||
disabled={Boolean(lockedBy) || templateLoading}
|
||||
onChange={event => invalidate(() => setBacktestId(event.target.value))}
|
||||
>
|
||||
<option value="">Select a saved canonical backtest</option>
|
||||
|
|
@ -259,7 +283,7 @@ export function ExperimentEditor({
|
|||
<input
|
||||
className={fieldClass}
|
||||
value={name}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setName(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
|
|
@ -268,7 +292,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={templateLoading || hasIntent}
|
||||
disabled={templateLoading || Boolean(lockedBy)}
|
||||
onClick={() => setLimit(value => value + 50)}
|
||||
>
|
||||
Load more backtests
|
||||
|
|
@ -280,7 +304,7 @@ export function ExperimentEditor({
|
|||
className={`${fieldClass} font-mono`}
|
||||
rows={4}
|
||||
value={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={Boolean(lockedBy)}
|
||||
onChange={event => invalidate(() => setGrid(event.target.value))}
|
||||
aria-describedby="experiment-grid-help"
|
||||
/>
|
||||
|
|
@ -299,7 +323,7 @@ export function ExperimentEditor({
|
|||
<Button
|
||||
variant="outline"
|
||||
disabled={
|
||||
hasIntent ||
|
||||
Boolean(lockedBy) ||
|
||||
previewLoading ||
|
||||
!backtests.some(item => item.id === backtestId) ||
|
||||
!name.trim()
|
||||
|
|
@ -324,7 +348,10 @@ export function ExperimentEditor({
|
|||
)}
|
||||
{(preview || hasIntent) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button disabled={submitting} onClick={() => void submit()}>
|
||||
<Button
|
||||
disabled={submitting || lockedBy === 'chronological'}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
? 'Submitting experiment...'
|
||||
: hasIntent
|
||||
|
|
@ -342,9 +369,11 @@ export function ExperimentEditor({
|
|||
backtestId={backtestId}
|
||||
name={name}
|
||||
grid={grid}
|
||||
disabled={hasIntent}
|
||||
disabled={lockedBy === 'ordinary'}
|
||||
eligible={!templateLoading && backtests.some(item => item.id === backtestId)}
|
||||
onDirty={setValidationDirty}
|
||||
claimSubmission={claimSubmission}
|
||||
releaseSubmission={releaseSubmission}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { ChronologicalValidationSummary } from '@stock-bot/stock-config/chronological-validation';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { chronologicalValidationDurableApi } from '../services/chronologicalValidationDurableApi';
|
||||
|
||||
export function SavedChronologicalValidations({ backtestId }: { backtestId: string }) {
|
||||
const [rows, setRows] = useState<ChronologicalValidationSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
void chronologicalValidationDurableApi
|
||||
.list(backtestId || undefined, controller.signal)
|
||||
.then(value => {
|
||||
if (current) {
|
||||
setRows(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setError(
|
||||
cause instanceof Error ? cause.message : 'Could not load chronological validations'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [backtestId, reload]);
|
||||
return (
|
||||
<section aria-label="Saved chronological validations" className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2 className="font-semibold">Saved chronological validations</h2>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh chronological validations
|
||||
</Button>
|
||||
</div>
|
||||
{loading && <p role="status">Loading chronological validations...</p>}
|
||||
{error && (
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && rows.length === 0 && <p>No saved chronological validations.</p>}
|
||||
{rows.map(item => (
|
||||
<article key={item.id} className="rounded-lg border border-border p-3 space-y-1">
|
||||
<Link
|
||||
className="font-medium text-primary-500"
|
||||
to={`/experiments/validation/${encodeURIComponent(item.id)}`}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{item.stage === 'reported'
|
||||
? 'Execution complete · report saved'
|
||||
: item.stage === 'holdouts'
|
||||
? 'Validation and test admitted'
|
||||
: 'Training candidates admitted'}{' '}
|
||||
· {item.trainingCandidateCount} training candidates
|
||||
</p>
|
||||
{item.cancelRequested && <p className="text-sm">Cancellation requested</p>}
|
||||
<p className="text-xs text-text-secondary">Created {item.createdAt}</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import { Link } from 'react-router-dom';
|
||||
import type { ValidationResultEvidence } from '@stock-bot/stock-config/chronological-validation';
|
||||
|
||||
export function ValidationEvidence({
|
||||
title,
|
||||
items,
|
||||
backtestId,
|
||||
}: {
|
||||
title: string;
|
||||
items: ValidationResultEvidence[];
|
||||
backtestId: string;
|
||||
}) {
|
||||
const metric = (
|
||||
item: ValidationResultEvidence,
|
||||
key: keyof ValidationResultEvidence['metrics']
|
||||
) =>
|
||||
item.metrics[key] === null
|
||||
? `Unavailable${item.unavailable[key] ? `: ${item.unavailable[key]}` : ''}`
|
||||
: String(item.metrics[key]);
|
||||
return (
|
||||
<section aria-label={title} className="space-y-2">
|
||||
<h3 className="font-semibold">{title}</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Phase / source candidate',
|
||||
'Parameters',
|
||||
'Total return (fraction)',
|
||||
'Max drawdown (fraction)',
|
||||
'Sharpe ratio',
|
||||
'Samples / evidence',
|
||||
].map(label => (
|
||||
<th className="p-2 border-b border-border" key={label}>
|
||||
{label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map(item => (
|
||||
<tr key={`${item.phase}:${item.runId}`} className="align-top">
|
||||
<td className="p-2 border-b border-border">
|
||||
{item.phase} · candidate {item.sourceCandidateIndex + 1}
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">
|
||||
<pre className="whitespace-pre-wrap text-xs">
|
||||
{JSON.stringify(item.parameters, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'totalReturn')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'maxDrawdown')}</td>
|
||||
<td className="p-2 border-b border-border">{metric(item, 'sharpeRatio')}</td>
|
||||
<td className="p-2 border-b border-border space-y-1 min-w-64">
|
||||
<p>
|
||||
Complete periods: {item.completePeriodCount} · Periodic samples:{' '}
|
||||
{item.periodicSampleCount} · Fills: {item.fillCount}
|
||||
</p>
|
||||
{item.periodicSampleCount < 2 && (
|
||||
<p>Insufficient periodic samples for variance-based statistics.</p>
|
||||
)}
|
||||
{item.limitations.map((value, index) => (
|
||||
<p key={index}>{value}</p>
|
||||
))}
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/backtests/${encodeURIComponent(backtestId)}/run/${encodeURIComponent(item.runId)}`}
|
||||
>
|
||||
Open {item.phase} candidate {item.sourceCandidateIndex + 1} run
|
||||
</Link>
|
||||
<details>
|
||||
<summary className="cursor-pointer">Exact retained evidence</summary>
|
||||
<pre className="max-h-72 overflow-auto whitespace-pre-wrap break-all text-xs">
|
||||
{JSON.stringify(item, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
export { ExperimentListPage } from './ExperimentListPage';
|
||||
export { ExperimentDetailPage } from './ExperimentDetailPage';
|
||||
export { ChronologicalValidationDetailPage } from './ChronologicalValidationDetailPage';
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ const invalid = () =>
|
|||
'The chronological validation preview could not be verified. Preview the current inputs again.'
|
||||
);
|
||||
|
||||
function parsePreview(
|
||||
export function parseChronologicalValidationPreview(
|
||||
body: unknown,
|
||||
input: ChronologicalValidationInput
|
||||
): ChronologicalValidationPreviewView {
|
||||
|
|
@ -150,7 +150,7 @@ export const chronologicalValidationApi = {
|
|||
if (response.status !== 200) {
|
||||
throw invalid();
|
||||
}
|
||||
return parsePreview(body, input);
|
||||
return parseChronologicalValidationPreview(body, input);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,388 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
chronologicalValidationInputSchema,
|
||||
type ChronologicalValidationActionReceipt,
|
||||
type ChronologicalValidationDetail,
|
||||
type ChronologicalValidationFinalizationInput,
|
||||
type ChronologicalValidationSelectionInput,
|
||||
type ChronologicalValidationSubmission,
|
||||
type ChronologicalValidationSummary,
|
||||
type ValidationResultEvidence,
|
||||
} from '@stock-bot/stock-config/chronological-validation';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
import {
|
||||
parseChronologicalValidationPreview,
|
||||
type ChronologicalValidationPreviewView,
|
||||
} from './chronologicalValidationApi';
|
||||
import {
|
||||
experimentMetricsSchema,
|
||||
parseExperimentDetail,
|
||||
type ExperimentDetailView,
|
||||
} from './experimentApi';
|
||||
|
||||
export type ValidationDetailView = Omit<ChronologicalValidationDetail, 'preview' | 'phases'> & {
|
||||
preview: ChronologicalValidationPreviewView;
|
||||
phases: Array<{
|
||||
phase: 'train' | 'validation' | 'test';
|
||||
status: 'not-admitted' | 'admitted' | 'missing';
|
||||
experimentId: string | null;
|
||||
experiment: ExperimentDetailView | null;
|
||||
}>;
|
||||
};
|
||||
export class ValidationApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const hash = z.string().regex(/^[a-f0-9]{64}$/),
|
||||
uuid = z.string().uuid(),
|
||||
count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const candidate = z.object({
|
||||
index: count,
|
||||
trialKey: hash,
|
||||
parameters: z.record(z.union([z.string(), z.number().finite(), z.boolean()])),
|
||||
});
|
||||
const actor = z.enum(['operator', 'service']);
|
||||
const summary = z.object({
|
||||
id: uuid,
|
||||
name: z.string().min(1),
|
||||
backtestId: uuid,
|
||||
createdAt: z.string().min(1),
|
||||
cancelRequested: z.boolean(),
|
||||
previewHash: hash,
|
||||
trainingCandidateCount: count.min(1).max(100),
|
||||
stage: z.enum(['training', 'holdouts', 'reported']),
|
||||
});
|
||||
const evidence = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
experimentId: uuid,
|
||||
runId: uuid,
|
||||
sourceCandidateIndex: count,
|
||||
trialKey: hash,
|
||||
parameters: candidate.shape.parameters,
|
||||
datasetHash: hash,
|
||||
requestHash: hash,
|
||||
economicHash: hash,
|
||||
metrics: experimentMetricsSchema,
|
||||
unavailable: z.record(z.string()),
|
||||
completePeriodCount: count,
|
||||
periodicSampleCount: count,
|
||||
fillCount: count,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const selection = z.object({
|
||||
version: z.literal('chronological-validation-selection/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reviewId: uuid,
|
||||
winner: candidate,
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
holdoutExperimentIds: z.object({ validation: uuid, test: uuid }),
|
||||
});
|
||||
const report = z.object({
|
||||
version: z.literal('chronological-validation-report/v1'),
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
reportHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
reset: z.literal('initial-capital-empty-positions'),
|
||||
training: z.array(evidence).min(1).max(100),
|
||||
validation: evidence,
|
||||
test: evidence,
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
const capability = z.object({ available: z.boolean(), reason: z.string().nullable() });
|
||||
const phase = z.object({
|
||||
phase: z.enum(['train', 'validation', 'test']),
|
||||
status: z.enum(['not-admitted', 'admitted', 'missing']),
|
||||
experimentId: uuid.nullable(),
|
||||
experiment: z.unknown(),
|
||||
});
|
||||
const detail = summary.extend({
|
||||
preview: z.unknown(),
|
||||
phases: z.tuple([phase, phase, phase]),
|
||||
selection: selection.nullable(),
|
||||
report: report.nullable(),
|
||||
actions: z.object({ select: capability, finalize: capability }),
|
||||
});
|
||||
const receipt = z.object({
|
||||
id: uuid,
|
||||
validationId: uuid,
|
||||
operation: z.enum(['select-and-admit-holdouts', 'finalize-report']),
|
||||
previewHash: hash,
|
||||
selectionHash: hash,
|
||||
createdAt: z.string().min(1),
|
||||
principal: actor,
|
||||
});
|
||||
const same = (a: unknown, b: unknown) => canonicalStrategyJson(a) === canonicalStrategyJson(b);
|
||||
const invalid = () =>
|
||||
new ValidationApiError(
|
||||
'The saved validation response could not be verified. Refresh or retry the same request.',
|
||||
null
|
||||
);
|
||||
function parseDetail(raw: unknown): ValidationDetailView {
|
||||
const value = detail.parse(raw);
|
||||
const rawPreview = z.object({ input: chronologicalValidationInputSchema }).parse(value.preview);
|
||||
const preview = parseChronologicalValidationPreview({ preview: value.preview }, rawPreview.input);
|
||||
if (
|
||||
value.backtestId !== preview.input.backtestId ||
|
||||
value.name !== preview.input.name ||
|
||||
value.previewHash !== preview.previewHash ||
|
||||
value.trainingCandidateCount !== preview.source.candidates.length ||
|
||||
(value.stage === 'training') !== (value.selection === null) ||
|
||||
(value.stage === 'reported') !== (value.report !== null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const phases = value.phases.map((item, index) => {
|
||||
const name = (['train', 'validation', 'test'] as const)[index];
|
||||
if (item.phase !== name || (item.status === 'admitted') !== (item.experiment !== null)) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedId =
|
||||
name === 'train'
|
||||
? value.id
|
||||
: (value.selection?.holdoutExperimentIds[name ?? 'validation'] ?? null);
|
||||
if (
|
||||
item.experimentId !== expectedId ||
|
||||
(item.status === 'not-admitted') !== (expectedId === null)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
const experiment = item.experiment === null ? null : parseExperimentDetail(item.experiment);
|
||||
if (experiment) {
|
||||
const prototype = preview.partitions[index];
|
||||
const parameters =
|
||||
name === 'train'
|
||||
? prototype?.request.strategy.selection.parameters
|
||||
: value.selection?.winner.parameters;
|
||||
if (!prototype || !parameters) {
|
||||
throw invalid();
|
||||
}
|
||||
const expectedRequest = {
|
||||
...prototype.request,
|
||||
strategy: {
|
||||
...prototype.request.strategy,
|
||||
reviewId:
|
||||
name === 'train' ? prototype.request.strategy.reviewId : value.selection?.reviewId,
|
||||
selection: { ...prototype.request.strategy.selection, parameters },
|
||||
},
|
||||
};
|
||||
const expectedCandidates =
|
||||
name === 'train' ? preview.source.candidates : [{ ...value.selection?.winner, index: 0 }];
|
||||
if (
|
||||
experiment.id !== expectedId ||
|
||||
experiment.backtestId !== value.backtestId ||
|
||||
!same(experiment.preview.request, expectedRequest) ||
|
||||
!same(experiment.preview.dataset, prototype.dataset) ||
|
||||
!same(experiment.preview.candidates, expectedCandidates) ||
|
||||
!same(experiment.preview.input.grid, name === 'train' ? preview.input.grid : {})
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
return { ...item, experiment };
|
||||
});
|
||||
const validateEvidence = (
|
||||
item: z.infer<typeof evidence>,
|
||||
expectedPhase: 'train' | 'validation' | 'test'
|
||||
) => {
|
||||
const index = ['train', 'validation', 'test'].indexOf(expectedPhase);
|
||||
const candidateValue = preview.source.candidates[item.sourceCandidateIndex];
|
||||
const phaseValue = phases[index];
|
||||
const trial = phaseValue?.experiment?.trials.find(
|
||||
trial => trial.runId === item.runId && trial.trialKey === item.trialKey
|
||||
);
|
||||
if (
|
||||
!candidateValue ||
|
||||
!phaseValue ||
|
||||
item.phase !== expectedPhase ||
|
||||
item.experimentId !== phaseValue.experimentId ||
|
||||
item.trialKey !== candidateValue.trialKey ||
|
||||
!same(item.parameters, candidateValue.parameters) ||
|
||||
item.datasetHash !== preview.partitions[index]?.dataset.hash ||
|
||||
(expectedPhase !== 'train' && item.sourceCandidateIndex !== value.selection?.winner.index) ||
|
||||
(phaseValue.experiment &&
|
||||
(!trial ||
|
||||
trial.status !== 'completed' ||
|
||||
!trial.comparable ||
|
||||
!same(trial.metrics, item.metrics) ||
|
||||
!same(trial.unavailable, item.unavailable) ||
|
||||
!same(trial.limitations, item.limitations)))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
};
|
||||
if (value.selection) {
|
||||
const chosen = value.selection;
|
||||
if (
|
||||
chosen.validationId !== value.id ||
|
||||
chosen.previewHash !== value.previewHash ||
|
||||
!same(chosen.winner, preview.source.candidates[chosen.winner.index]) ||
|
||||
chosen.training.length !== value.trainingCandidateCount ||
|
||||
chosen.training.some((item, index) => item.sourceCandidateIndex !== index) ||
|
||||
new Set([value.id, chosen.holdoutExperimentIds.validation, chosen.holdoutExperimentIds.test])
|
||||
.size !== 3
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
for (const item of chosen.training) {
|
||||
validateEvidence(item, 'train');
|
||||
if (item.metrics.totalReturn === null) {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (value.report) {
|
||||
const saved = value.report;
|
||||
if (
|
||||
!value.selection ||
|
||||
saved.validationId !== value.id ||
|
||||
saved.previewHash !== value.previewHash ||
|
||||
saved.selectionHash !== value.selection.selectionHash ||
|
||||
!same(saved.training, value.selection.training)
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
validateEvidence(saved.validation, 'validation');
|
||||
validateEvidence(saved.test, 'test');
|
||||
}
|
||||
if (
|
||||
(value.actions.select.available && (value.selection || value.cancelRequested)) ||
|
||||
(value.actions.finalize.available &&
|
||||
(!value.selection || value.report || value.cancelRequested))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { ...value, preview, phases } as ValidationDetailView;
|
||||
}
|
||||
const envelope = (body: unknown, key: string) => z.record(z.unknown()).parse(body)[key];
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init: RequestInit,
|
||||
status: number,
|
||||
parse: (body: unknown) => T
|
||||
): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetch(`${API_BASE_URL}/api/v2/experiments/validation${path}`, init);
|
||||
} catch (cause) {
|
||||
if (init.signal?.aborted) {
|
||||
throw cause;
|
||||
}
|
||||
throw new ValidationApiError(
|
||||
'The validation response was lost. Retry the same request to recover its receipt.',
|
||||
null
|
||||
);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
const error = z.object({ error: z.string() }).safeParse(body);
|
||||
throw new ValidationApiError(
|
||||
error.success ? error.data.error : `Validation request failed (${response.status})`,
|
||||
response.status
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (response.status !== status) {
|
||||
throw invalid();
|
||||
}
|
||||
return parse(body);
|
||||
} catch {
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
const post = (body: unknown, key?: string): RequestInit => ({
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
});
|
||||
export const chronologicalValidationDurableApi = {
|
||||
list: (backtestId?: string, signal?: AbortSignal) =>
|
||||
request(
|
||||
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',
|
||||
{ signal },
|
||||
200,
|
||||
body => {
|
||||
const rows = z.array(summary).parse(envelope(body, 'validations'));
|
||||
if (
|
||||
new Set(rows.map(row => row.id)).size !== rows.length ||
|
||||
(backtestId && rows.some(row => row.backtestId !== backtestId))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return rows as ChronologicalValidationSummary[];
|
||||
}
|
||||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
submit: (input: ChronologicalValidationSubmission, key: string) =>
|
||||
request('', post(input, key), 202, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
advance: (
|
||||
id: string,
|
||||
operation: 'select' | 'finalize',
|
||||
input: ChronologicalValidationSelectionInput | ChronologicalValidationFinalizationInput,
|
||||
key: string
|
||||
) =>
|
||||
request(`/${encodeURIComponent(id)}/${operation}`, post(input, key), 202, body => {
|
||||
const accepted = receipt.parse(envelope(body, 'receipt'));
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
const record = operation === 'select' ? value.selection : value.report;
|
||||
if (
|
||||
accepted.validationId !== id ||
|
||||
value.id !== id ||
|
||||
accepted.previewHash !== input.previewHash ||
|
||||
value.previewHash !== input.previewHash ||
|
||||
accepted.operation !==
|
||||
(operation === 'select' ? 'select-and-admit-holdouts' : 'finalize-report') ||
|
||||
accepted.selectionHash !== value.selection?.selectionHash ||
|
||||
!record ||
|
||||
accepted.id !== record.id ||
|
||||
accepted.createdAt !== record.createdAt ||
|
||||
accepted.principal !== record.principal ||
|
||||
(operation === 'finalize' &&
|
||||
(!('selectionHash' in input) ||
|
||||
accepted.selectionHash !== input.selectionHash ||
|
||||
!value.report))
|
||||
) {
|
||||
throw invalid();
|
||||
}
|
||||
return { receipt: accepted as ChronologicalValidationActionReceipt, validation: value };
|
||||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, post({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'validation'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
return value;
|
||||
}),
|
||||
};
|
||||
export type { ValidationResultEvidence };
|
||||
|
|
@ -87,7 +87,7 @@ const preview = z.object({
|
|||
candidates: z.array(candidate).min(1).max(MAX_EXPERIMENT_TRIALS),
|
||||
});
|
||||
const metric = z.number().finite().nullable();
|
||||
const metrics = z.object({
|
||||
export const experimentMetricsSchema = z.object({
|
||||
totalReturn: metric,
|
||||
cagr: metric,
|
||||
maxDrawdown: metric,
|
||||
|
|
@ -118,7 +118,7 @@ const trial = candidate.extend({
|
|||
error: z.string().nullable(),
|
||||
comparable: z.boolean(),
|
||||
diagnostic: z.string().nullable(),
|
||||
metrics: metrics.nullable(),
|
||||
metrics: experimentMetricsSchema.nullable(),
|
||||
unavailable: z.record(z.string()).nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
|
@ -185,7 +185,7 @@ export function parseExperimentPreview(value: unknown): ExperimentPreviewView {
|
|||
// The server retains and verifies the complete manifest; the browser only renders its identity/window.
|
||||
return parsed;
|
||||
}
|
||||
function parseDetail(value: unknown): ExperimentDetailView {
|
||||
export function parseExperimentDetail(value: unknown): ExperimentDetailView {
|
||||
const parsed = detail.parse(value);
|
||||
parseSummary(parsed);
|
||||
const retained = parseExperimentPreview(parsed.preview);
|
||||
|
|
@ -282,7 +282,7 @@ export const experimentApi = {
|
|||
202,
|
||||
body => {
|
||||
const receipt = retryReceipt.parse(envelope(body, 'retry'));
|
||||
const experiment = parseDetail(envelope(body, 'experiment'));
|
||||
const experiment = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const current = experiment.trials.find(
|
||||
item => item.trialKey === target.trialKey && item.runId === target.runId
|
||||
);
|
||||
|
|
@ -360,7 +360,7 @@ export const experimentApi = {
|
|||
},
|
||||
202,
|
||||
body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
const { previewHash, ...original } = input;
|
||||
if (value.previewHash !== previewHash || !same(value.preview.input, original)) {
|
||||
throw invalid();
|
||||
|
|
@ -370,7 +370,7 @@ export const experimentApi = {
|
|||
),
|
||||
get: (id: string, signal?: AbortSignal) =>
|
||||
request(`/${encodeURIComponent(id)}`, { signal }, 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
@ -378,7 +378,7 @@ export const experimentApi = {
|
|||
}),
|
||||
cancel: (id: string) =>
|
||||
request(`/${encodeURIComponent(id)}/cancel`, json({}), 200, body => {
|
||||
const value = parseDetail(envelope(body, 'experiment'));
|
||||
const value = parseExperimentDetail(envelope(body, 'experiment'));
|
||||
if (value.id !== id || !value.cancelRequested) {
|
||||
throw invalid();
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue