feat(research): retry failed experiment trials with retained history

This commit is contained in:
Boki 2026-10-24 10:56:58 -04:00
parent 6f64ef62ba
commit b373410320
32 changed files with 3336 additions and 61 deletions

View file

@ -1,9 +1,11 @@
import { useEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import type { ExperimentTrial } from '@stock-bot/stock-config/experiments';
import { Button } from '@/components/ui/Button';
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
import { ExperimentCounts } from './components/ExperimentCounts';
import { ExperimentInputs } from './components/ExperimentInputs';
import { ExperimentTrialRecovery } from './components/ExperimentTrialRecovery';
import { experimentApi, type ExperimentDetailView as Detail } from './services/experimentApi';
export function ExperimentDetailPage() {
@ -19,37 +21,59 @@ function metricText(trial: ExperimentTrial, key: keyof NonNullable<ExperimentTri
function ExperimentDetailView({ experimentId }: { experimentId: string }) {
const alive = useRef(false);
const pending = useRef(false);
const generation = useRef(0);
const readRequest = useRef<AbortController | null>(null);
const [experiment, setExperiment] = useState<Detail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [reload, setReload] = useState(0);
const [cancelling, setCancelling] = useState(false);
const [mutating, setMutating] = useState(false);
const [retryIntents, setRetryIntents] = useState<string[]>([]);
useUnsavedWarning(retryIntents.length > 0);
const onIntentChange = useCallback((trialKey: string, active: boolean) => {
setRetryIntents(previous =>
active
? previous.includes(trialKey)
? previous
: [...previous, trialKey]
: previous.includes(trialKey)
? previous.filter(key => key !== trialKey)
: previous
);
}, []);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
generation.current++;
readRequest.current?.abort();
};
}, []);
useEffect(() => {
if (pending.current) {
return;
}
let current = true;
const revision = ++generation.current;
const controller = new AbortController();
readRequest.current = controller;
setLoading(true);
setError('');
setExperiment(null);
void experimentApi
.get(experimentId, controller.signal)
.then(value => {
if (current) {
if (current && revision === generation.current) {
setExperiment(value);
}
})
.catch(cause => {
if (current) {
if (current && revision === generation.current) {
setError(cause instanceof Error ? cause.message : 'Could not load experiment');
}
})
.finally(() => {
if (current) {
if (current && revision === generation.current) {
setLoading(false);
}
});
@ -58,18 +82,38 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
controller.abort();
};
}, [experimentId, reload]);
const cancel = async () => {
if (pending.current || !experiment || loading) {
return;
const beginMutation = () => {
if (pending.current) {
return false;
}
pending.current = true;
generation.current++;
readRequest.current?.abort();
setLoading(false);
setMutating(true);
setError('');
return true;
};
const acceptMutation = (value: Detail) => {
if (alive.current && value.id === experimentId) {
setExperiment(value);
}
};
const endMutation = () => {
pending.current = false;
if (alive.current) {
setMutating(false);
}
};
const cancel = async () => {
if (!experiment || loading || !beginMutation()) {
return;
}
setCancelling(true);
setError('');
try {
const value = await experimentApi.cancel(experimentId);
if (alive.current) {
setExperiment(value);
}
acceptMutation(value);
} catch (cause) {
if (alive.current) {
setError(
@ -77,7 +121,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
);
}
} finally {
pending.current = false;
endMutation();
if (alive.current) {
setCancelling(false);
}
@ -87,7 +131,24 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
experiment &&
experiment.counts.pending + experiment.counts.running + experiment.counts.paused > 0;
return (
<div className="h-full overflow-auto space-y-5 p-1">
<div
className="h-full overflow-auto space-y-5 p-1"
onClickCapture={event => {
if (
(event.target as HTMLElement).closest('a') &&
retryIntents.length > 0 &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey &&
!window.confirm(
'Leave this retry review or unconfirmed retry? Its exact inputs and key will be discarded. You can inspect runs in another tab.'
)
) {
event.preventDefault();
event.stopPropagation();
}
}}
>
<Link className="text-primary-500 text-sm" to="/experiments">
All experiments
</Link>
@ -96,8 +157,14 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
<Button
variant="outline"
size="sm"
disabled={loading || cancelling}
onClick={() => setReload(value => value + 1)}
disabled={loading || mutating}
onClick={() => {
if (!pending.current) {
generation.current++;
readRequest.current?.abort();
setReload(value => value + 1);
}
}}
>
Refresh experiment
</Button>
@ -106,6 +173,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
{error && (
<p role="alert" className="text-error">
{error}
{experiment && ' Showing the last loaded state; refresh to verify current status.'}
</p>
)}
{experiment && (
@ -122,7 +190,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
<Button
variant="danger"
size="sm"
disabled={cancelling}
disabled={mutating || loading}
onClick={() => void cancel()}
>
{cancelling ? 'Requesting cancellation...' : 'Cancel remaining trials'}
@ -173,6 +241,11 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
: `${trial.progress}% complete`}
</p>
{trial.cancelRequested && <p className="text-xs">Cancellation requested</p>}
{trial.runId && (
<p className="text-xs">
Attempt {trial.attemptNumber} · Manual retries {trial.retryCount}
</p>
)}
</td>
<td className="p-2 border-b border-border">
{trial.comparable
@ -223,6 +296,18 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) {
Open trial {trial.index + 1} run
</Link>
)}
<ExperimentTrialRecovery
experimentId={experiment.id}
backtestId={experiment.backtestId}
previewHash={experiment.previewHash}
experimentCancelled={experiment.cancelRequested}
trial={trial}
disabled={mutating || loading}
beginMutation={beginMutation}
acceptMutation={acceptMutation}
endMutation={endMutation}
onIntentChange={onIntentChange}
/>
</td>
</tr>
))}

View file

@ -0,0 +1,335 @@
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 ExperimentDetailView,
type ExperimentRetryTarget,
} from '../services/experimentApi';
interface Props {
experimentId: string;
backtestId: string;
previewHash: string;
experimentCancelled: boolean;
trial: ExperimentTrial;
disabled: boolean;
beginMutation: () => boolean;
acceptMutation: (experiment: ExperimentDetailView) => 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,
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)
.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]);
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}</dd>
</div>
</dl>
</article>
))}
</section>
)}
</section>
);
}

View file

@ -2,12 +2,15 @@ import { z } from 'zod';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import {
experimentInputSchema,
experimentRetrySchema,
MAX_EXPERIMENT_TRIALS,
type ExperimentDetail,
type ExperimentInput,
type ExperimentPreview,
type ExperimentRetryInput,
type ExperimentSubmission,
type ExperimentSummary,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { API_BASE_URL, apiFetch } from '@/lib/api';
@ -25,6 +28,7 @@ export class ExperimentApiError extends Error {
}
const hash = z.string().regex(/^[a-f0-9]{64}$/);
const count = z.number().int().nonnegative().max(MAX_EXPERIMENT_TRIALS);
const counter = z.number().int().nonnegative().max(2147483647);
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
const candidate = z.object({
index: count,
@ -106,6 +110,8 @@ const metrics = z.object({
});
const trial = candidate.extend({
runId: z.string().uuid().nullable(),
attemptNumber: counter,
retryCount: counter,
status: z.enum([...statuses, 'missing']),
progress: z.number().finite().min(0).max(100),
cancelRequested: z.boolean(),
@ -117,6 +123,33 @@ const trial = candidate.extend({
limitations: z.array(z.string()),
});
const detail = summary.extend({ preview, trials: z.array(trial).max(MAX_EXPERIMENT_TRIALS) });
const retryReceipt = z.object({
id: z.string().uuid(),
experimentId: z.string().uuid(),
runId: z.string().uuid(),
trialKey: hash,
retryNumber: counter.min(1),
previousAttemptNumber: counter,
previousAttemptId: z.string().uuid().nullable(),
error: z.string().nullable(),
progress: z.number().finite().min(0).max(100),
currentDate: z.string().nullable(),
startedAt: z.string().nullable(),
completedAt: z.string().nullable(),
pausedAt: z.string().nullable(),
failureUpdatedAt: z.string().min(1),
recordedAt: z.string().min(1),
principal: z.enum(['operator', 'service']),
reviewId: z.string().uuid(),
});
/** Immutable source identity captured when the operator reviews a failed trial. */
export interface ExperimentRetryTarget {
experimentId: string;
backtestId: string;
previewHash: string;
runId: string;
trialKey: string;
}
const same = (left: unknown, right: unknown) =>
canonicalStrategyJson(left) === canonicalStrategyJson(right);
const invalid = () =>
@ -176,6 +209,7 @@ function parseDetail(value: unknown): ExperimentDetailView {
item.trialKey !== expected.trialKey ||
!same(item.parameters, expected.parameters) ||
(item.status === 'missing') !== (item.runId === null) ||
(item.status === 'missing' && (item.attemptNumber !== 0 || item.retryCount !== 0)) ||
(item.comparable && (item.status !== 'completed' || !item.metrics || !item.unavailable)) ||
(item.runId !== null && runIds.has(item.runId))
) {
@ -238,6 +272,61 @@ const json = (body: unknown): RequestInit => ({
body: JSON.stringify(body),
});
export const experimentApi = {
retryTrial: (target: ExperimentRetryTarget, input: ExperimentRetryInput, key: string) =>
request(
`/${encodeURIComponent(target.experimentId)}/trials/${encodeURIComponent(target.runId)}/retry`,
{
...json(experimentRetrySchema.parse(input)),
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
},
202,
body => {
const receipt = retryReceipt.parse(envelope(body, 'retry'));
const experiment = parseDetail(envelope(body, 'experiment'));
const current = experiment.trials.find(
item => item.trialKey === target.trialKey && item.runId === target.runId
);
if (
receipt.experimentId !== target.experimentId ||
receipt.runId !== target.runId ||
receipt.trialKey !== target.trialKey ||
receipt.retryNumber !== input.expectedRetryCount + 1 ||
receipt.previousAttemptNumber !== input.expectedAttemptNumber ||
experiment.id !== target.experimentId ||
experiment.backtestId !== target.backtestId ||
experiment.previewHash !== target.previewHash ||
!current ||
current.retryCount < receipt.retryNumber ||
current.attemptNumber < receipt.previousAttemptNumber
) {
throw invalid();
}
// Receipt replay may return a newer failed/completed/cancelled state. The original receipt remains success.
return { retry: receipt as ExperimentTrialRetry, experiment };
}
),
retryHistory: (experimentId: string, runId: string, trialKey: string, signal?: AbortSignal) =>
request(
`/${encodeURIComponent(experimentId)}/trials/${encodeURIComponent(runId)}/retries`,
{ signal },
200,
body => {
const rows = z.array(retryReceipt).parse(envelope(body, 'retries'));
if (
new Set(rows.map(item => item.id)).size !== rows.length ||
rows.some(
(item, index) =>
item.experimentId !== experimentId ||
item.runId !== runId ||
item.trialKey !== trialKey ||
item.retryNumber !== index + 1
)
) {
throw invalid();
}
return rows as ExperimentTrialRetry[];
}
),
list: (backtestId?: string, signal?: AbortSignal) =>
request(
backtestId ? `?backtestId=${encodeURIComponent(backtestId)}` : '',