stock-bot/apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx

419 lines
15 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import type { WalkForwardReceipt } from '@stock-bot/stock-config/walk-forward';
import { Button } from '@/components/ui/Button';
import { walkForwardFindingSource } from '@/features/research/services/findingSources';
import { useUnsavedWarning } from '@/hooks/useUnsavedWarning';
import { RegimeEvidenceUnavailable } from './components/RegimeEvidenceUnavailable';
import { SourceFindingAction } from './components/SourceFindingAction';
import { ValidationEvidence } from './components/ValidationEvidence';
import {
walkForwardApi,
WalkForwardApiError,
type WalkForwardDetailView,
} from './services/walkForwardApi';
export function WalkForwardDetailPage() {
const { walkForwardId = '' } = useParams<{ walkForwardId: string }>();
return <WalkForwardDetail key={walkForwardId} walkForwardId={walkForwardId} />;
}
type Intent = { id: string; body: { previewHash: string }; key: string };
function WalkForwardDetail({ walkForwardId }: { walkForwardId: string }) {
const [findingDirty, setFindingDirty] = useState(false);
const alive = useRef(false),
pending = useRef(false),
reading = useRef(true),
generation = useRef(0),
read = useRef<AbortController | null>(null),
captured = useRef<Intent | null>(null);
const [value, setValue] = useState<WalkForwardDetailView | null>(null),
[intent, setIntent] = useState<Intent | null>(null),
[receipt, setReceipt] = useState<WalkForwardReceipt | null>(null);
const [loading, setLoading] = useState(true),
[busy, setBusy] = useState(false),
[reload, setReload] = useState(0),
[readError, setReadError] = useState(''),
[actionError, setActionError] = useState(''),
[ambiguous, setAmbiguous] = useState(false);
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 walkForwardApi
.get(walkForwardId, controller.signal)
.then(result => {
if (current && revision === generation.current) {
setValue(result);
}
})
.catch(cause => {
if (current && revision === generation.current) {
setReadError(
cause instanceof Error ? cause.message : 'Could not load walk-forward validation'
);
}
})
.finally(() => {
if (current && revision === generation.current) {
reading.current = false;
setLoading(false);
}
});
return () => {
current = false;
controller.abort();
};
}, [walkForwardId, reload]);
const begin = () => {
if (pending.current || reading.current) {
return false;
}
pending.current = true;
generation.current++;
read.current?.abort();
setBusy(true);
setActionError('');
return true;
};
const finish = () => {
pending.current = false;
if (alive.current) {
setBusy(false);
}
};
const finalize = async () => {
if (pending.current || reading.current || !value) {
return;
}
if (!captured.current) {
if (!value.actions.finalize.available) {
return;
}
captured.current = {
id: walkForwardId,
body: { previewHash: value.previewHash },
key: crypto.randomUUID(),
};
setIntent(captured.current);
setReceipt(null);
}
const original = captured.current;
if (!begin()) {
return;
}
try {
const result = await walkForwardApi.finalize(original.id, original.body, original.key);
if (alive.current) {
captured.current = null;
setIntent(null);
setReceipt(result.receipt);
setValue(result.walkForward);
setAmbiguous(false);
}
} catch (cause) {
if (alive.current) {
setActionError(
cause instanceof Error ? cause.message : 'Could not save walk-forward report'
);
setAmbiguous(!(cause instanceof WalkForwardApiError) || cause.ambiguous);
}
} finally {
finish();
}
};
const cancel = async () => {
if (!value || !begin()) {
return;
}
try {
const result = await walkForwardApi.cancel(walkForwardId);
if (alive.current) {
setValue(result);
}
} 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 report request? It may already have succeeded. Refresh the saved walk-forward 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 walk-forward report request? 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">{value?.name ?? 'Walk-forward 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(current => current + 1);
}
}}
>
Refresh walk-forward
</Button>
</div>
{loading && <p role="status">Loading walk-forward validation...</p>}
{readError && (
<p role="alert" className="text-error">
{readError}
{value && ' 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 ? 'Report acceptance is unconfirmed. ' : ''}This request retains its exact
walk-forward identity, preview and key.
</p>
<Button disabled={busy || loading} onClick={() => void finalize()}>
Retry walk-forward report request
</Button>{' '}
<Button variant="outline" disabled={busy} onClick={discard}>
Discard walk-forward report request
</Button>
</div>
)}
{receipt && (
<p role="status">
Walk-forward report accepted. Receipt {receipt.id} · {receipt.createdAt}
</p>
)}
{value && (
<>
<RegimeEvidenceUnavailable />
{!value.report && (
<SourceFindingAction
source={null}
disabled
onDirtyChange={setFindingDirty}
unavailable="Save the complete report before linking its evidence to a research finding."
/>
)}
<p className="font-semibold">
{value.report
? 'Execution complete · walk-forward report saved'
: 'Window validations admitted · walk-forward report not yet saved'}
</p>
<p>
{value.reportedWindowCount}/{value.windowCount} window reports saved ·{' '}
{value.trainingRunCount} training runs · {value.plannedRunCount} total planned runs,
including future holdouts.
</p>
<p>
Each phase and window resets initial capital and positions. These are ordered
independent reset segments, not a continuous portfolio equity curve. No returns are
compounded and no window metrics are averaged.
</p>
{value.cancelRequested && (
<p>
Cancellation requested for all windows. Completed evidence remains retained; active
work may still finish.
</p>
)}
<div className="flex flex-wrap gap-2">
{!intent && !value.report && (
<Button
disabled={loading || busy || !value.actions.finalize.available}
onClick={() => void finalize()}
>
Save walk-forward report
</Button>
)}
<Button
variant="outline"
disabled={loading || busy || value.cancelRequested}
onClick={() => void cancel()}
>
Cancel remaining walk-forward work
</Button>
</div>
{!value.report && value.actions.finalize.reason && <p>{value.actions.finalize.reason}</p>}
<section aria-label="Walk-forward windows" className="space-y-3">
<h2 className="font-semibold">Window progress and evidence</h2>
{value.windows.map(member => (
<article key={member.index} className="rounded border border-border p-3 space-y-2">
<h3 className="font-medium">Window {member.index + 1}</h3>
<Link
className="text-primary-500"
to={`/experiments/validation/${encodeURIComponent(member.validationId)}`}
>
Open window {member.index + 1} validation
</Link>
{member.status === 'missing' ? (
<p role="alert">
Window {member.index + 1} validation is missing. Its outcome has not been
omitted.
</p>
) : (
<>
<p>
{member.validation?.report
? 'Window report saved'
: member.validation?.selection
? 'Fixed winner selected · validation and test admitted'
: 'Training candidates admitted · selection not yet frozen'}
</p>
{member.validation?.cancelRequested && (
<p>Cancellation requested for this window.</p>
)}
{member.validation?.phases.map(phase => (
<div key={phase.phase}>
<p>
{phase.phase}:{' '}
{phase.status === 'not-admitted'
? 'Not admitted'
: phase.status === 'missing'
? 'Experiment missing'
: phase.experiment
? `${phase.experiment.counts.completed} completed, ${phase.experiment.counts.failed} failed, ${phase.experiment.counts.cancelled} cancelled, ${phase.experiment.counts.pending} pending, ${phase.experiment.counts.running} running, ${phase.experiment.counts.paused} paused`
: 'Unavailable'}
</p>
{phase.experiment &&
phase.experiment.trials
.filter(
trial =>
trial.status === 'missing' ||
trial.error ||
(trial.status === 'completed' && !trial.comparable)
)
.map(trial => (
<p key={trial.index}>
Candidate {trial.index + 1}: {trial.status};{' '}
{trial.error ?? trial.diagnostic ?? 'Evidence unavailable'}
</p>
))}
</div>
))}
</>
)}
</article>
))}
</section>
<details>
<summary className="cursor-pointer">Frozen walk-forward inputs</summary>
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
{JSON.stringify(value.preview, null, 2)}
</pre>
</details>
{value.report && (
<section aria-label="Saved walk-forward report" className="space-y-3">
<h2 className="font-semibold">Saved walk-forward report</h2>
<SourceFindingAction
key={value.report.reportHash}
source={walkForwardFindingSource(value)}
disabled={loading || busy || Boolean(intent)}
onDirtyChange={setFindingDirty}
unavailable="A sealed report is required to cite this source."
/>
<p className="break-all">
Report {value.report.id} · {value.report.createdAt} · Hash {value.report.reportHash}
</p>
{value.report.limitations.map((limitation, index) => (
<p key={index}>{limitation}</p>
))}
{value.report.segments.map(segment => (
<section key={segment.index} className="space-y-2">
<h3 className="font-medium">Window {segment.index + 1} reset segment</h3>
<p className="break-all">
Window report {segment.reportId} · {segment.reportHash}
</p>
<p className="break-all">Selection {segment.selectionHash}</p>
<ValidationEvidence
title={`Window ${segment.index + 1} validation and test evidence`}
items={[segment.validation, segment.test]}
backtestId={value.backtestId}
/>
</section>
))}
<details>
<summary className="cursor-pointer">Exact retained walk-forward report</summary>
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">
{JSON.stringify(value.report, null, 2)}
</pre>
</details>
</section>
)}
</>
)}
</div>
);
}