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

@ -42,6 +42,39 @@ export const experimentSubmissionSchema = experimentInputSchema.extend({
});
export type ExperimentInput = z.infer<typeof experimentInputSchema>;
export type ExperimentSubmission = z.infer<typeof experimentSubmissionSchema>;
/** Both counters are required: a failure can occur before the worker claims an attempt. */
export const experimentRetrySchema = z
.object({
expectedAttemptNumber: z.number().int().nonnegative().max(2147483647),
expectedRetryCount: z.number().int().nonnegative().max(2147483647),
})
.strict();
export type ExperimentRetryInput = z.infer<typeof experimentRetrySchema>;
/** Snapshot of the failure preceding an accepted manual retry, not an automatic-attempt log. */
export interface ExperimentTrialRetry {
id: string;
experimentId: string;
runId: string;
trialKey: string;
retryNumber: number;
previousAttemptNumber: number;
previousAttemptId: string | null;
error: string | null;
progress: number;
currentDate: string | null;
startedAt: string | null;
completedAt: string | null;
pausedAt: string | null;
failureUpdatedAt: string;
recordedAt: string;
principal: 'operator' | 'service';
/** Current approval at retry admission; the original run snapshot stays immutable. */
reviewId: string;
}
export interface ExperimentRetryResult {
retry: ExperimentTrialRetry;
experiment: ExperimentDetail;
}
export interface ExperimentCandidate {
/** Zero-based deterministic position in the frozen grid. */
index: number;
@ -80,6 +113,8 @@ export interface ExperimentSummary {
}
export interface ExperimentTrial extends ExperimentCandidate {
runId: string | null;
attemptNumber: number;
retryCount: number;
status: ExperimentRunStatus | 'missing';
progress: number;
cancelRequested: boolean;

View file

@ -62,7 +62,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '19-canonical-research.sql' ||
f === '20-research-workspace.sql' ||
f === '21-run-reproduction.sql' ||
f === '22-experiments.sql')
f === '22-experiments.sql' ||
f === '23-experiment-retries.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -10,6 +10,7 @@ import {
parseExperimentInput,
parseExperimentSubmission,
} from '../services/experiment-input';
import { parseExperimentRetry } from '../services/experiment-retry';
import { ExperimentsService } from '../services/experiments.service';
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
@ -77,5 +78,25 @@ export function createExperimentRoutes(container: IServiceContainer) {
}
return c.json({ experiment: await service.cancel(id) });
});
app.get('/api/v2/experiments/:id/trials/:runId/retries', async c =>
c.json({
retries: await service.listTrialRetries(
experimentId(c.req.param('id')),
experimentId(c.req.param('runId'))
),
})
);
app.post('/api/v2/experiments/:id/trials/:runId/retry', async c => {
const id = experimentId(c.req.param('id')),
runId = experimentId(c.req.param('runId'));
const input = parseExperimentRetry(await body(c.req.raw));
const receipt = experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
});
const result = await service.retryTrial(id, runId, input, receipt);
c.header('Location', `/api/v2/experiments/${id}`);
return c.json(result, 202);
});
return app;
}

View file

@ -0,0 +1,45 @@
import type { QueryResultRow } from 'pg';
import {
experimentRetrySchema,
type ExperimentRetryInput,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { ExperimentError } from './experiment-input';
export function parseExperimentRetry(input: unknown): ExperimentRetryInput {
const parsed = experimentRetrySchema.safeParse(input);
if (!parsed.success) {
throw new ExperimentError(
400,
'Retry requires the observed nonnegative attempt number and retry count only'
);
}
return parsed.data;
}
/** Format in SQL to preserve PostgreSQL microseconds, including pre-JavaScript failure timestamps. */
const timestamp = (column: string) =>
`to_char(h.${column} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS ${column}`;
export const retryColumns = `h.id,h.experiment_id,h.run_id,h.trial_key,h.retry_number,h.previous_attempt_number,h.previous_attempt_id,
h.error,h.progress,h.principal,h.review_id,h.submission_key,h.submission_hash,
${['current_simulation_date', 'started_at', 'completed_at', 'paused_at', 'failure_updated_at', 'recorded_at'].map(timestamp).join(',')}`;
export function mapExperimentRetry(row: QueryResultRow): ExperimentTrialRetry {
return {
id: row.id,
experimentId: row.experiment_id,
runId: row.run_id,
trialKey: row.trial_key,
retryNumber: row.retry_number,
previousAttemptNumber: row.previous_attempt_number,
previousAttemptId: row.previous_attempt_id,
error: row.error,
progress: Number(row.progress),
currentDate: row.current_simulation_date,
startedAt: row.started_at,
completedAt: row.completed_at,
pausedAt: row.paused_at,
failureUpdatedAt: row.failure_updated_at,
recordedAt: row.recorded_at,
principal: row.principal,
reviewId: row.review_id,
};
}

View file

@ -7,8 +7,10 @@ import type {
ExperimentDetail,
ExperimentInput,
ExperimentPreview,
ExperimentRetryResult,
ExperimentSummary,
ExperimentTrial,
ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
@ -25,6 +27,8 @@ import {
PREVIEW_RUN_ID,
retainedExperimentPreview,
} from './experiment-input';
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
import { StrategyCatalogError } from './strategy-catalog.service';
interface Query {
@ -289,6 +293,185 @@ export class ExperimentsService {
return this.readDetail(client, id);
});
}
async listTrialRetries(id: string, runId: string): Promise<ExperimentTrialRetry[]> {
experimentId(id);
experimentId(runId);
const experiment = (
await this.database.query('SELECT id FROM research_experiments WHERE id=$1', [id])
).rows[0];
if (!experiment) {
throw new ExperimentError(404, 'Experiment not found');
}
const run = (await this.database.query('SELECT experiment_id FROM runs WHERE id=$1', [runId]))
.rows[0];
if (!run) {
throw new ExperimentError(404, 'Trial run not found');
}
if (run.experiment_id !== id) {
throw new ExperimentError(409, 'Run does not belong to this experiment');
}
return (
await this.database.query(
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.run_id=$1 ORDER BY h.retry_number`,
[runId]
)
).rows.map(mapExperimentRetry);
}
async retryTrial(
id: string,
runId: string,
raw: unknown,
actor: { principal: string; key: string }
): Promise<ExperimentRetryResult> {
experimentId(id);
experimentId(runId);
const input = parseExperimentRetry(raw);
const receipt = experimentReceipt(actor);
const hash = experimentHash({
version: 1,
operation: 'retry-experiment-trial',
experimentId: id,
runId,
...input,
});
return this.database.transaction(async client => {
const replay = async (): Promise<ExperimentRetryResult | null> => {
const saved = (
await client.query(
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.principal=$1 AND h.submission_key=$2`,
[receipt.principal, receipt.key]
)
).rows[0];
if (!saved) {
return null;
}
if (saved.submission_hash !== hash) {
throw new ExperimentError(
409,
'Idempotency-Key already belongs to a different trial retry intent'
);
}
return {
retry: mapExperimentRetry(saved),
experiment: await this.readDetail(client, saved.experiment_id),
};
};
const previous = await replay();
if (previous) {
return previous;
}
// Same ordering as admission, followed by the existing original-family verification lock.
const parent = (
await client.query(
'SELECT id,archived_at FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=$1) FOR UPDATE',
[id]
)
).rows[0];
const concurrent = await replay();
if (concurrent) {
return concurrent;
}
if (!parent) {
throw new ExperimentError(404, 'Experiment not found');
}
const experiment = (
await client.query('SELECT * FROM research_experiments WHERE id=$1 FOR UPDATE', [id])
).rows[0];
const run = (
await client.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2 FOR UPDATE', [
runId,
id,
])
).rows[0];
if (!run) {
const exists = (await client.query('SELECT id FROM runs WHERE id=$1', [runId])).rows.length;
throw new ExperimentError(
exists ? 409 : 404,
exists ? 'Run does not belong to this experiment' : 'Trial run not found'
);
}
if (
parent.archived_at !== null ||
experiment.cancel_requested ||
run.cancel_requested ||
run.status !== 'failed'
) {
throw new ExperimentError(
409,
'Retry requires an active backtest and a failed, uncancelled experiment trial'
);
}
if (
run.attempt_number !== input.expectedAttemptNumber ||
run.manual_retry_count !== input.expectedRetryCount
) {
throw new ExperimentError(
409,
'The trial failure changed; refresh before requesting a new retry'
);
}
if (run.manual_retry_count === 2147483647 || run.attempt_number === 2147483647) {
throw new ExperimentError(409, 'Trial attempt or retry counter is exhausted');
}
if (
(await client.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [runId])).rows.length
) {
throw new ExperimentError(409, 'A run with a retained result cannot be retried');
}
const preview = retainedExperimentPreview(experiment.preview);
const candidate = preview.candidates[run.trial_index];
if (!candidate || candidate.trialKey !== run.trial_key || run.backtest_id !== parent.id) {
throw new ExperimentError(409, 'Trial does not match its retained experiment candidate');
}
const request = experimentTrialRequest(preview, candidate, runId);
if (!equal(request, run.request_snapshot) || request.datasetHash !== run.dataset_hash) {
throw new ExperimentError(409, 'Trial frozen request does not match its experiment');
}
let reviewId;
try {
reviewId = await verifyReproductionInputs(client, this.container, request);
} catch (error) {
if (error instanceof RunReproductionError) {
throw new ExperimentError(409, error.message);
}
throw error;
}
const retryId = randomUUID();
const inserted = await client.query(
`INSERT INTO experiment_trial_retries
(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,
started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
SELECT $1,experiment_id,id,trial_key,manual_retry_count+1,attempt_number,attempt_id,error,progress,current_simulation_date,
started_at,completed_at,paused_at,updated_at,$3,$4,$5,$6 FROM runs WHERE id=$2
ON CONFLICT (principal,submission_key) DO NOTHING RETURNING id`,
[retryId, runId, receipt.principal, reviewId, receipt.key, hash]
);
if (!inserted.rows.length) {
const winner = await replay();
if (!winner) {
throw new Error('Concurrent retry receipt disappeared');
}
return winner;
}
await client.query(
`UPDATE runs SET status='pending',manual_retry_count=manual_retry_count+1,
attempt_id=NULL,lease_expires_at=NULL,error=NULL,current_simulation_date=NULL,started_at=NULL,completed_at=NULL,paused_at=NULL,
progress=0,updated_at=NOW() WHERE id=$1`,
[runId]
);
await client.query(
`INSERT INTO backtest_dispatch (run_id,next_publish_at) VALUES ($1,NOW())
ON CONFLICT (run_id) DO UPDATE SET next_publish_at=NOW()`,
[runId]
);
const saved = (
await client.query(`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.id=$1`, [
retryId,
])
).rows[0];
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
});
}
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
const row = (
await database.query(
@ -303,7 +486,7 @@ export class ExperimentsService {
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
const runs = (
await database.query(
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.attempt_number,r.manual_retry_count,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
br.canonical_result->>'kind' AS result_kind,br.canonical_result->>'status' AS result_status,
br.canonical_result->>'runId' AS result_run_id,br.canonical_result->>'backtestId' AS result_backtest_id,
br.canonical_result->>'financialEngine' AS financial_engine,br.canonical_result->>'strategyExecution' AS strategy_execution,
@ -321,6 +504,8 @@ export class ExperimentsService {
const trial: ExperimentTrial = {
...candidate,
runId: run?.id ?? null,
attemptNumber: run ? Number(run.attempt_number) : 0,
retryCount: run ? Number(run.manual_retry_count) : 0,
status: run?.status ?? 'missing',
progress: Number(run?.progress ?? 0),
cancelRequested: run?.cancel_requested ?? false,

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)}` : '',