feat(research): retry failed experiment trials with retained history
This commit is contained in:
parent
6f64ef62ba
commit
b373410320
32 changed files with 3336 additions and 61 deletions
|
|
@ -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)}` : '',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue