345 lines
11 KiB
TypeScript
345 lines
11 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import type {
|
|
ExperimentRetryInput,
|
|
ExperimentTrial,
|
|
ExperimentTrialRetry,
|
|
} from '@stock-bot/stock-config/experiments';
|
|
import { Button } from '@/components/ui/Button';
|
|
import {
|
|
experimentApi,
|
|
ExperimentApiError,
|
|
type ExperimentRetryTarget,
|
|
type WorkbenchExperimentDetailView,
|
|
} from '../services/experimentApi';
|
|
|
|
interface Props {
|
|
experimentId: string;
|
|
backtestId: string;
|
|
previewHash: string;
|
|
strategyOrigin?: 'builtin' | 'candidate';
|
|
experimentCancelled: boolean;
|
|
trial: ExperimentTrial;
|
|
disabled: boolean;
|
|
beginMutation: () => boolean;
|
|
acceptMutation: (experiment: WorkbenchExperimentDetailView) => void;
|
|
endMutation: () => void;
|
|
onIntentChange: (trialKey: string, active: boolean) => void;
|
|
}
|
|
interface RetryIntent {
|
|
target: ExperimentRetryTarget;
|
|
input: ExperimentRetryInput;
|
|
key: string;
|
|
error: string | null;
|
|
progress: number;
|
|
}
|
|
const message = (cause: unknown) =>
|
|
cause instanceof Error ? cause.message : 'Could not complete the retry request';
|
|
|
|
/** The row stays mounted through detail refreshes so a receipt can be recovered after state changes. */
|
|
export function ExperimentTrialRecovery({
|
|
experimentId,
|
|
backtestId,
|
|
previewHash,
|
|
strategyOrigin = 'builtin',
|
|
experimentCancelled,
|
|
trial,
|
|
disabled,
|
|
beginMutation,
|
|
acceptMutation,
|
|
endMutation,
|
|
onIntentChange,
|
|
}: Props) {
|
|
const number = trial.index + 1;
|
|
const alive = useRef(false);
|
|
const pending = useRef(false);
|
|
const intentRef = useRef<RetryIntent | null>(null);
|
|
const [intent, setIntent] = useState<RetryIntent | null>(null);
|
|
const [sent, setSent] = useState(false);
|
|
const [submitting, setSubmitting] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const [ambiguous, setAmbiguous] = useState(false);
|
|
const [accepted, setAccepted] = useState<number | null>(null);
|
|
const [historyOpen, setHistoryOpen] = useState(false);
|
|
const [history, setHistory] = useState<ExperimentTrialRetry[] | null>(null);
|
|
const [historyLoading, setHistoryLoading] = useState(false);
|
|
const [historyError, setHistoryError] = useState('');
|
|
const [historyReload, setHistoryReload] = useState(0);
|
|
const freshAllowed =
|
|
Boolean(trial.runId) &&
|
|
trial.status === 'failed' &&
|
|
!trial.cancelRequested &&
|
|
!experimentCancelled;
|
|
const sameFailure =
|
|
intent &&
|
|
intent.target.runId === trial.runId &&
|
|
intent.input.expectedAttemptNumber === trial.attemptNumber &&
|
|
intent.input.expectedRetryCount === trial.retryCount;
|
|
useEffect(() => {
|
|
alive.current = true;
|
|
return () => {
|
|
alive.current = false;
|
|
};
|
|
}, []);
|
|
useEffect(() => {
|
|
onIntentChange(trial.trialKey, Boolean(intent));
|
|
return () => onIntentChange(trial.trialKey, false);
|
|
}, [intent, onIntentChange, trial.trialKey]);
|
|
useEffect(() => {
|
|
if (!historyOpen || !trial.runId) {
|
|
return;
|
|
}
|
|
let current = true;
|
|
const controller = new AbortController();
|
|
setHistory(null);
|
|
setHistoryLoading(true);
|
|
setHistoryError('');
|
|
void experimentApi
|
|
.retryHistory(experimentId, trial.runId, trial.trialKey, controller.signal, strategyOrigin)
|
|
.then(value => {
|
|
if (current) {
|
|
setHistory(value);
|
|
}
|
|
})
|
|
.catch(cause => {
|
|
if (current) {
|
|
setHistoryError(message(cause));
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (current) {
|
|
setHistoryLoading(false);
|
|
}
|
|
});
|
|
return () => {
|
|
current = false;
|
|
controller.abort();
|
|
};
|
|
}, [
|
|
experimentId,
|
|
trial.runId,
|
|
trial.trialKey,
|
|
trial.retryCount,
|
|
historyOpen,
|
|
historyReload,
|
|
strategyOrigin,
|
|
]);
|
|
const review = () => {
|
|
if (disabled || !freshAllowed || !trial.runId || intentRef.current) {
|
|
return;
|
|
}
|
|
const captured: RetryIntent = {
|
|
target: {
|
|
experimentId,
|
|
backtestId,
|
|
previewHash,
|
|
runId: trial.runId,
|
|
trialKey: trial.trialKey,
|
|
},
|
|
input: { expectedAttemptNumber: trial.attemptNumber, expectedRetryCount: trial.retryCount },
|
|
key: crypto.randomUUID(),
|
|
error: trial.error,
|
|
progress: trial.progress,
|
|
};
|
|
intentRef.current = captured;
|
|
setIntent(captured);
|
|
setSent(false);
|
|
setError('');
|
|
setAmbiguous(false);
|
|
setAccepted(null);
|
|
};
|
|
const submit = async () => {
|
|
const captured = intentRef.current;
|
|
if (
|
|
!captured ||
|
|
pending.current ||
|
|
disabled ||
|
|
(!sent && (!freshAllowed || !sameFailure)) ||
|
|
!beginMutation()
|
|
) {
|
|
return;
|
|
}
|
|
pending.current = true;
|
|
setSent(true);
|
|
setSubmitting(true);
|
|
setError('');
|
|
try {
|
|
const result = await experimentApi.retryTrial(captured.target, captured.input, captured.key);
|
|
if (alive.current) {
|
|
intentRef.current = null;
|
|
setIntent(null);
|
|
setSent(false);
|
|
setAmbiguous(false);
|
|
setAccepted(result.retry.retryNumber);
|
|
setHistoryReload(value => value + 1);
|
|
acceptMutation(result.experiment);
|
|
}
|
|
} catch (cause) {
|
|
if (alive.current) {
|
|
setError(message(cause));
|
|
setAmbiguous(!(cause instanceof ExperimentApiError) || cause.ambiguous);
|
|
}
|
|
} finally {
|
|
pending.current = false;
|
|
if (alive.current) {
|
|
setSubmitting(false);
|
|
}
|
|
endMutation();
|
|
}
|
|
};
|
|
const discard = () => {
|
|
if (
|
|
pending.current ||
|
|
(sent &&
|
|
!window.confirm(
|
|
'Discard this retry request? It may already have been accepted. Refresh the experiment and inspect retry history before preparing another retry.'
|
|
))
|
|
) {
|
|
return;
|
|
}
|
|
intentRef.current = null;
|
|
setIntent(null);
|
|
setSent(false);
|
|
setError('');
|
|
setAmbiguous(false);
|
|
};
|
|
return (
|
|
<section aria-label={`Recovery for trial ${number}`} className="space-y-2 text-xs">
|
|
{freshAllowed && !intent && (
|
|
<Button variant="outline" size="sm" disabled={disabled} onClick={review}>
|
|
Retry trial {number}
|
|
</Button>
|
|
)}
|
|
{accepted !== null && (
|
|
<p role="status">
|
|
Retry {accepted} accepted for trial {number}. The current outcome may have advanced since
|
|
acceptance.
|
|
</p>
|
|
)}
|
|
{intent && (
|
|
<div
|
|
aria-label={`Retry trial ${number} review`}
|
|
className="border border-border rounded p-2 space-y-2"
|
|
>
|
|
<p>
|
|
Reviewed failed attempt {intent.input.expectedAttemptNumber} · prior manual retries{' '}
|
|
{intent.input.expectedRetryCount} · progress {intent.progress}%
|
|
</p>
|
|
<p>{intent.error ?? 'No error was recorded for this failure.'}</p>
|
|
<p>
|
|
Retry keeps the same run, frozen dataset, strategy parameters, seed, costs and risk
|
|
policy. Current eligibility is verified by the server.
|
|
</p>
|
|
{(!sameFailure || !freshAllowed) && (
|
|
<p>
|
|
The current trial state has changed. This request still targets the reviewed failure;
|
|
it never starts a retry for a newer failure.
|
|
</p>
|
|
)}
|
|
{sent && (
|
|
<p role="status">
|
|
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}The exact failure counters and
|
|
submission key are retained. Retry the same request to recover its receipt.
|
|
</p>
|
|
)}
|
|
{error && (
|
|
<p role="alert" className="text-error">
|
|
{error}
|
|
</p>
|
|
)}
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button
|
|
size="sm"
|
|
disabled={disabled || submitting || (!sent && (!freshAllowed || !sameFailure))}
|
|
onClick={() => void submit()}
|
|
>
|
|
{submitting
|
|
? `Submitting retry for trial ${number}...`
|
|
: sent
|
|
? `Retry same request for trial ${number}`
|
|
: `Confirm retry trial ${number}`}
|
|
</Button>
|
|
<Button variant="outline" size="sm" disabled={submitting} onClick={discard}>
|
|
Discard retry request for trial {number}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
{trial.runId && (
|
|
<Button variant="outline" size="sm" onClick={() => setHistoryOpen(value => !value)}>
|
|
{historyOpen
|
|
? `Hide retry history for trial ${number}`
|
|
: `Show retry history for trial ${number}`}
|
|
</Button>
|
|
)}
|
|
{historyOpen && trial.runId && (
|
|
<section
|
|
aria-label={`Retry history for trial ${number}`}
|
|
className="border border-border rounded p-2 space-y-2"
|
|
>
|
|
<p>
|
|
Prior failures captured when manual retries were accepted. This is not a complete
|
|
history of automatic recovery attempts.
|
|
</p>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={historyLoading}
|
|
onClick={() => setHistoryReload(value => value + 1)}
|
|
>
|
|
Refresh retry history for trial {number}
|
|
</Button>
|
|
{historyLoading && <p role="status">Loading retry history for trial {number}...</p>}
|
|
{historyError && (
|
|
<p role="alert" className="text-error">
|
|
{historyError}
|
|
</p>
|
|
)}
|
|
{history && history.length === 0 && <p>No accepted manual retries for this trial.</p>}
|
|
{history?.map(item => (
|
|
<article key={item.id} className="space-y-1 border-t border-border pt-2 break-all">
|
|
<h3 className="font-semibold">
|
|
Retry {item.retryNumber} · previous attempt {item.previousAttemptNumber}
|
|
</h3>
|
|
<p>{item.error ?? 'No error was recorded for this failure.'}</p>
|
|
<dl>
|
|
<div>
|
|
<dt>Prior attempt ID</dt>
|
|
<dd>{item.previousAttemptId ?? 'No attempt ID was recorded.'}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Progress at failure</dt>
|
|
<dd>{item.progress}%</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Simulation date</dt>
|
|
<dd>{item.currentDate ?? 'Not recorded'}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Started / completed / paused</dt>
|
|
<dd>
|
|
{item.startedAt ?? 'Not recorded'} / {item.completedAt ?? 'Not recorded'} /{' '}
|
|
{item.pausedAt ?? 'Not recorded'}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Failure last updated</dt>
|
|
<dd>{item.failureUpdatedAt}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Retry accepted</dt>
|
|
<dd>
|
|
{item.recordedAt} · {item.principal}
|
|
</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Approval at retry admission</dt>
|
|
<dd>{item.reviewId ?? 'Unreviewed isolated candidate'}</dd>
|
|
</div>
|
|
</dl>
|
|
</article>
|
|
))}
|
|
</section>
|
|
)}
|
|
</section>
|
|
);
|
|
}
|