diff --git a/apps/stock/config/src/contracts/experiments.ts b/apps/stock/config/src/contracts/experiments.ts index 957c4542..6f0ee3b6 100644 --- a/apps/stock/config/src/contracts/experiments.ts +++ b/apps/stock/config/src/contracts/experiments.ts @@ -42,6 +42,39 @@ export const experimentSubmissionSchema = experimentInputSchema.extend({ }); export type ExperimentInput = z.infer; export type ExperimentSubmission = z.infer; +/** 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; +/** 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; diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 7cfac425..20199ae8 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -62,7 +62,8 @@ export async function runMigrations(container: IServiceContainer): Promise 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(); diff --git a/apps/stock/web-api/src/routes/experiments.routes.ts b/apps/stock/web-api/src/routes/experiments.routes.ts index 0c3227d1..ec7065ec 100644 --- a/apps/stock/web-api/src/routes/experiments.routes.ts +++ b/apps/stock/web-api/src/routes/experiments.routes.ts @@ -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; } diff --git a/apps/stock/web-api/src/services/experiment-retry.ts b/apps/stock/web-api/src/services/experiment-retry.ts new file mode 100644 index 00000000..f9f7025e --- /dev/null +++ b/apps/stock/web-api/src/services/experiment-retry.ts @@ -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, + }; +} diff --git a/apps/stock/web-api/src/services/experiments.service.ts b/apps/stock/web-api/src/services/experiments.service.ts index 1209b3c2..18f87d58 100644 --- a/apps/stock/web-api/src/services/experiments.service.ts +++ b/apps/stock/web-api/src/services/experiments.service.ts @@ -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 { + 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 { + 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 => { + 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 { 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, diff --git a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx index 6dd18f70..2d276930 100644 --- a/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx +++ b/apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx @@ -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(null); const [experiment, setExperiment] = useState(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([]); + 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 ( -
+
{ + 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(); + } + }} + > All experiments @@ -96,8 +157,14 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) { @@ -106,6 +173,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) { {error && (

{error} + {experiment && ' Showing the last loaded state; refresh to verify current status.'}

)} {experiment && ( @@ -122,7 +190,7 @@ function ExperimentDetailView({ experimentId }: { experimentId: string }) { + )} + {accepted !== null && ( +

+ Retry {accepted} accepted for trial {number}. The current outcome may have advanced since + acceptance. +

+ )} + {intent && ( +
+

+ Reviewed failed attempt {intent.input.expectedAttemptNumber} · prior manual retries{' '} + {intent.input.expectedRetryCount} · progress {intent.progress}% +

+

{intent.error ?? 'No error was recorded for this failure.'}

+

+ Retry keeps the same run, frozen dataset, strategy parameters, seed, costs and risk + policy. Current eligibility is verified by the server. +

+ {(!sameFailure || !freshAllowed) && ( +

+ The current trial state has changed. This request still targets the reviewed failure; + it never starts a retry for a newer failure. +

+ )} + {sent && ( +

+ {ambiguous ? 'Acceptance is unconfirmed. ' : ''}The exact failure counters and + submission key are retained. Retry the same request to recover its receipt. +

+ )} + {error && ( +

+ {error} +

+ )} +
+ + +
+
+ )} + {trial.runId && ( + + )} + {historyOpen && trial.runId && ( +
+

+ Prior failures captured when manual retries were accepted. This is not a complete + history of automatic recovery attempts. +

+ + {historyLoading &&

Loading retry history for trial {number}...

} + {historyError && ( +

+ {historyError} +

+ )} + {history && history.length === 0 &&

No accepted manual retries for this trial.

} + {history?.map(item => ( +
+

+ Retry {item.retryNumber} · previous attempt {item.previousAttemptNumber} +

+

{item.error ?? 'No error was recorded for this failure.'}

+
+
+
Prior attempt ID
+
{item.previousAttemptId ?? 'No attempt ID was recorded.'}
+
+
+
Progress at failure
+
{item.progress}%
+
+
+
Simulation date
+
{item.currentDate ?? 'Not recorded'}
+
+
+
Started / completed / paused
+
+ {item.startedAt ?? 'Not recorded'} / {item.completedAt ?? 'Not recorded'} /{' '} + {item.pausedAt ?? 'Not recorded'} +
+
+
+
Failure last updated
+
{item.failureUpdatedAt}
+
+
+
Retry accepted
+
+ {item.recordedAt} · {item.principal} +
+
+
+
Approval at retry admission
+
{item.reviewId}
+
+
+
+ ))} +
+ )} + + ); +} diff --git a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts index 1036bf76..c505bb46 100644 --- a/apps/stock/web-app/src/features/experiments/services/experimentApi.ts +++ b/apps/stock/web-app/src/features/experiments/services/experimentApi.ts @@ -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)}` : '', diff --git a/database/postgres/init/23-experiment-retries.sql b/database/postgres/init/23-experiment-retries.sql new file mode 100644 index 00000000..15131db9 --- /dev/null +++ b/database/postgres/init/23-experiment-retries.sql @@ -0,0 +1,136 @@ +-- Manual retries retain one immutable logical trial and append the observed failure. +ALTER TABLE runs ADD COLUMN IF NOT EXISTS manual_retry_count INTEGER NOT NULL DEFAULT 0; +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='runs_manual_retry_count_nonnegative' AND conrelid='runs'::regclass) THEN + ALTER TABLE runs ADD CONSTRAINT runs_manual_retry_count_nonnegative CHECK (manual_retry_count>=0); + END IF; +END $$; +CREATE TABLE IF NOT EXISTS experiment_trial_retries ( + id UUID PRIMARY KEY, + experiment_id UUID NOT NULL REFERENCES research_experiments(id) ON DELETE RESTRICT, + run_id UUID NOT NULL REFERENCES runs(id) ON DELETE RESTRICT, + trial_key TEXT NOT NULL CHECK (trial_key ~ '^[a-f0-9]{64}$'), + retry_number INTEGER NOT NULL CHECK (retry_number>0), + previous_attempt_number INTEGER NOT NULL CHECK (previous_attempt_number>=0), + previous_attempt_id UUID, + error TEXT, + progress NUMERIC NOT NULL CHECK (progress>=0 AND progress<=100), + current_simulation_date TIMESTAMPTZ, + started_at TIMESTAMPTZ, + completed_at TIMESTAMPTZ, + paused_at TIMESTAMPTZ, + failure_updated_at TIMESTAMPTZ NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + principal TEXT NOT NULL CHECK (principal IN ('operator','service')), + review_id UUID NOT NULL REFERENCES strategy_review_events(id) ON DELETE RESTRICT, + submission_key TEXT NOT NULL CHECK (submission_key ~ '^[!-~]{1,200}$'), + submission_hash TEXT NOT NULL CHECK (submission_hash ~ '^[a-f0-9]{64}$'), + UNIQUE(principal,submission_key), + UNIQUE(run_id,retry_number) +); + +CREATE OR REPLACE FUNCTION require_experiment_retry_failure() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE parent RECORD; experiment RECORD; original RECORD; selected RECORD; approval RECORD; expected JSONB; candidate JSONB; retained JSONB; +BEGIN + -- Match the API lock order; worker-owned updates only need the run lock. + SELECT * INTO parent FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=NEW.experiment_id) FOR UPDATE; + SELECT * INTO experiment FROM research_experiments WHERE id=NEW.experiment_id FOR UPDATE; + SELECT * INTO original FROM runs WHERE id=NEW.run_id AND experiment_id=NEW.experiment_id FOR UPDATE; + IF (parent.id IS NOT NULL AND parent.archived_at IS NULL AND experiment.id IS NOT NULL AND NOT experiment.cancel_requested + AND original.id IS NOT NULL AND original.backtest_id=parent.id AND original.status='failed' AND NOT original.cancel_requested + AND NEW.recorded_at=NOW() AND original.trial_key=NEW.trial_key AND original.manual_retry_count<2147483647 AND original.attempt_number<2147483647 + AND NEW.retry_number=original.manual_retry_count+1 AND NEW.previous_attempt_number=original.attempt_number + AND NEW.previous_attempt_id IS NOT DISTINCT FROM original.attempt_id + AND NEW.error IS NOT DISTINCT FROM original.error AND NEW.progress IS NOT DISTINCT FROM original.progress + AND NEW.current_simulation_date IS NOT DISTINCT FROM original.current_simulation_date + AND NEW.started_at IS NOT DISTINCT FROM original.started_at AND NEW.completed_at IS NOT DISTINCT FROM original.completed_at + AND NEW.paused_at IS NOT DISTINCT FROM original.paused_at AND NEW.failure_updated_at=original.updated_at + AND NOT EXISTS (SELECT 1 FROM backtest_results WHERE run_id=original.id)) IS NOT TRUE THEN + RAISE EXCEPTION 'Retry requires the exact current failed experiment trial without cancellation or retained result' USING ERRCODE='23514'; + END IF; + candidate := experiment.preview->'candidates'->original.trial_index; + expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(original.id::text)); + expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(original.id::text)); + expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||original.id::text)); + expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters'); + IF (candidate->>'index'=original.trial_index::text AND candidate->>'trialKey'=original.trial_key + AND expected=original.request_snapshot AND expected->>'kind'='canonical-research/v1' + AND expected->>'backtestId'=original.backtest_id::text AND expected->>'datasetHash'=original.dataset_hash + AND original.original_run_id IS NULL AND original.speed_multiplier IS NULL) IS NOT TRUE THEN + RAISE EXCEPTION 'Retry must preserve its exact immutable experiment request and candidate' USING ERRCODE='23514'; + END IF; + SELECT v.*,s.archived_at AS family_archived INTO selected FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id + WHERE v.id::text=expected#>>'{strategy,versionId}' FOR UPDATE OF s; + SELECT id,decision INTO approval FROM strategy_review_events WHERE version_id=selected.id ORDER BY ordinal DESC LIMIT 1; + IF (selected.origin='builtin' AND selected.family_archived IS NULL AND approval.decision='approve' + AND NEW.review_id=approval.id AND expected#>>'{strategy,origin}'='builtin' + AND expected#>>'{strategy,familyId}'=selected.strategy_id::text + AND expected#>'{strategy,package}'=selected.envelope) IS NOT TRUE THEN + RAISE EXCEPTION 'Retry requires current approval of the original retained built-in version' USING ERRCODE='23514'; + END IF; + SELECT payload INTO retained FROM backtest_datasets WHERE hash=original.dataset_hash; + IF (retained#>>'{manifest,version}'='2' AND retained#>>'{manifest,eligibility}'='eligible' + AND retained->'manifest'=experiment.preview->'dataset' + AND jsonb_array_length(retained#>'{manifest,executionSeries}')=1 + AND jsonb_array_length(retained#>'{manifest,series}')=1 + AND expected#>>'{strategy,selection,instrumentId}'=retained#>>'{manifest,executionSeries,0,instrumentId}' + AND expected#>>'{strategy,selection,seriesId}'=retained#>>'{manifest,executionSeries,0,seriesId}') IS NOT TRUE THEN + RAISE EXCEPTION 'Retry requires its retained eligible original dataset' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END $$; +DROP TRIGGER IF EXISTS experiment_retry_admission ON experiment_trial_retries; +CREATE TRIGGER experiment_retry_admission BEFORE INSERT ON experiment_trial_retries FOR EACH ROW EXECUTE FUNCTION require_experiment_retry_failure(); +DROP TRIGGER IF EXISTS experiment_retry_retained ON experiment_trial_retries; +CREATE TRIGGER experiment_retry_retained BEFORE UPDATE OR DELETE ON experiment_trial_retries FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); +DROP TRIGGER IF EXISTS experiment_retry_no_truncate ON experiment_trial_retries; +CREATE TRIGGER experiment_retry_no_truncate BEFORE TRUNCATE ON experiment_trial_retries FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); + +CREATE OR REPLACE FUNCTION guard_manual_trial_retry() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE receipt RECORD; +BEGIN + IF TG_OP='INSERT' THEN + IF NEW.manual_retry_count<>0 THEN RAISE EXCEPTION 'New runs cannot invent retry history' USING ERRCODE='23514'; END IF; + RETURN NEW; + END IF; + IF OLD.experiment_id IS NOT NULL AND NEW.attempt_number=NEW.retry_number + AND d.next_publish_at<=clock_timestamp()) THEN + RAISE EXCEPTION 'Accepted retry requires its reset run and due durable dispatch in the same transaction' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END $$; +DROP TRIGGER IF EXISTS experiment_retry_consumed ON experiment_trial_retries; +CREATE CONSTRAINT TRIGGER experiment_retry_consumed AFTER INSERT ON experiment_trial_retries + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION require_consumed_trial_retry(); diff --git a/docs/development/ROADMAP.md b/docs/development/ROADMAP.md index 06c3a64e..0898b129 100644 --- a/docs/development/ROADMAP.md +++ b/docs/development/ROADMAP.md @@ -1,8 +1,8 @@ # Revised development roadmap -Baseline `b7aeca4` · execution 2026-10-24 · **R12 committed; retained-input R06/R07 experiment components validated and uncommitted** +**First twenty-seven waves committed; failed-trial retries are validated and await commit.** The experiment workbench is committed as `6f64ef6`. **34 of 45 scheduled tasks are fully committed (76% by count)**; R06 now satisfies its retained-input acceptance and is in review. R07 retry/history controls are validated, while broader comparison work and full R05 remain partial. Next after acceptance: R08 chronological validation. Performance work remains paused. -Authorization update: the owner requested “comit and continue”. R12 is committed as `30accfc`; **34/45 scheduled tasks are committed**. R06/R07 components use the accepted retained-input R05 runner with pinned preview, atomic admission and same-experiment UI contracts. Full R05 remains partial; this slice excludes failed-trial retry, cross-experiment comparisons and all performance work. New-wave commits, pushes, PRs and trading/default-engine operations remain outside this continuation's scope. +Authorization update: the owner requested “commit and start”. The first R06/R07 experiment workbench is committed as `6f64ef6`; **34/45 scheduled tasks are fully committed**, plus these partial components. This continuation adds failed-trial retry receipts, diagnostic preservation, fencing and UI history using existing durable runs/outbox. Full R05 and broader R07 work remain partial. Performance stays paused; new-wave commits, pushes, PRs and trading/default-engine operations are outside this continuation's scope. ## Strategy and review outcome @@ -599,3 +599,17 @@ R12 is accepted and committed as `30accfc`. R06/R07 retained-input components ar Full R06 remains incomplete until failed-trial retry preserves prior diagnostics and passes stale-attempt fencing tests. R07 broader comparisons/table measurement remain outstanding; all performance work stays paused. R05 provider preparation and broader cutover remain partial; R08/A01/S06 are not silently released. No candidate/multi-asset/default/paper/live/AI execution, new-wave commit, push or PR occurred. Editor retry state lives in the current page; saved experiments and accepted receipts are durable. Hash/provenance agreement does not establish strategy merit. **Next after acceptance/commit: complete R06 failed-trial retry** using the same immutable logical run and existing attempts/outbox. Append prior diagnostics before clearing active errors; reject retries with stored results or completed/cancelled state, retain old-attempt fencing and add a focused UI action only after the backend contract passes. Performance remains paused. + +## Twenty-eighth-wave handoff — 2026-10-24 + +The previous experiment workbench is committed as `6f64ef6`. R06 failed-trial retries and focused R07 controls are implemented, independently reviewed and validated; these new changes are uncommitted. R06 is now in review with its retained-input acceptance satisfied. R05 and full R07 remain partial. + +- **Durable retry:** A manual retry preserves the logical run, immutable request, dataset, strategy parameters and original approval snapshot. Current original-version approval/build eligibility is checked separately. One atomic SQL transaction captures the exact failure, advances the manual retry counter, clears active execution state and makes the existing dispatch outbox due. Lifetime attempt counters never decrease; recovery budgets are not reset. Existing workers supply the next fresh attempt UUID. +- **Recovery evidence:** Append-only receipts preserve PostgreSQL timestamp precision. Repeated acceptance returns the same receipt, including after completion or later eligibility changes. Cancellation, retained results, stale failure counters, direct SQL tampering and late old-worker callbacks cannot create an unauthorized retry or overwrite results. No financial engine, runner or dispatcher source changed. +- **Workbench:** Per-trial review/retry/history controls retain the exact unresolved request through refresh and uncertain responses. Saved history survives reopening. This records failures captured by manual retries, not invented historical automatic-attempt logs. + +Validation passed: `bun run check` (93 tooling, 43 utility, 44 calculation, 738 integration and 150 Rust tests; four existing manual Rust tests ignored), full PostgreSQL/Redis (190 tests / 1609 assertions), and Chromium (11 workflows / 285 assertions). Strict test types, scoped lint, changed-file formatting and whitespace checks passed. Independent review accepted all 12 agent-owned hashes and the root browser fixture/test delta. All 27 source/test files are archived and hashed in `manifest.json` → `twenty_eighth_wave_validation`. + +The release addon remains `ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103`. Both disposable fixture containers were stopped; development services were untouched. Worktrees and logs remain under `/tmp/stock-bot-wave28.AqRnN8/`. + +Next after acceptance/commit: **R08 bounded chronological selection and reset-segment validation**. Freeze train/validation/test windows and selection rules before execution, retain all tried candidates and distinguish reset segments from continuous portfolio performance. No performance work, standalone/bulk retries, candidate execution, multi-asset/default/paper/live activation, AI execution, new-wave commit, push or PR occurred. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index b4ff24aa..e270a530 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**First twenty-six waves committed; R06/R07 retained-input experiment components are validated and uncommitted.** R12 is accepted as `30accfc`. **34 of 45 scheduled tasks are committed (76% by count).** The web workbench now previews/submits bounded grids, compares every trial outcome and reopens evidence through existing durable canonical runs. Full R05 remains partial; failed-trial retry and broader comparisons are excluded from this component. Performance work remains paused. +**First twenty-seven waves committed; failed-trial retries are validated and await commit.** The experiment workbench is committed as `6f64ef6`. **34 of 45 scheduled tasks are fully committed (76% by count)**; R06 now satisfies its retained-input acceptance and is in review. R07 retry/history controls are validated, while broader comparison work and full R05 remain partial. Next after acceptance: R08 chronological validation. Performance work remains paused. ## One source of truth @@ -77,7 +77,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr | [R03 Add projects, hypotheses and evidence-linked findings APIs](tasks/R03.md) | P1 / done | R01, R10, ADR-006 | — | Full-stack research product / M | | [R04 Deliver research workspace and save-findings flow](tasks/R04.md) | P1 / done | R03, W02, ADR-006 | W04 | Full-stack research product / M | | [R05 Freeze complete provenance and cut over durable canonical runs](tasks/R05.md) | P0 / in_progress | F08, S02, R01, R10, D01, W03, C06, ADR-006 | Multi-asset default mark-policy disposition | Full-stack research product / M | -| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / in_progress (component) | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M | +| [R06 Create immutable experiments and bounded sweep expansion](tasks/R06.md) | P1 / review (validated, uncommitted) | Accepted R05 retained-input component; R01/R10/F08/S02/D01/W03/C06/R12, ADR-006 | — | Full-stack research product / M | | [R07 Deliver sweep configuration and comparable-result views](tasks/R07.md) | P1 / in_progress (component) | R06 component API pinned; release after integration, ADR-006 | W04 | Full-stack research product / M | | [R08 Add bounded chronological and reset-segment validation](tasks/R08.md) | P1 / blocked | R06, ADR-006 | — | Quantitative research integrity / M | | [R09 Expose validation, cost and regime evidence in the workbench](tasks/R09.md) | P1 / blocked | R07, R08, ADR-006 | S05 when Regime comparison is enabled; R03 when Saving or linking a research finding is enabled | Full-stack research product / M | @@ -118,4 +118,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation. -R12 is committed. R06/R07 retained-input components passed independent review and full repository/PostgreSQL/browser gates; they await acceptance/commit. See the [current handoff](../ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24). Next implement R06 failed-trial retry with preserved diagnostics and attempt fencing. Full R05 remains partial, R06 failed retry remains outstanding, and R08/A01/S06 dependencies are not released by this component. Provider preparation is independent of sweeps over already eligible retained data. Performance and multi-asset/default/paper activation remain excluded. +The R06/R07 retained-input components are committed as `6f64ef6`. Current work completes failed-trial retry with preserved diagnostics and attempt fencing plus focused UI controls. Full R05 stays partial; R08/A01/S06 are not released before accepted integration and their own approval gates. Provider preparation is independent of sweeps over retained data. Performance and multi-asset/default/paper activation remain excluded. diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 9b242666..d73e4e7c 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -1,14 +1,14 @@ { "schema_version": 1, - "plan_revision": "2026-10-24.58", + "plan_revision": "2026-10-24.60", "repository_base": "b7aeca4", - "plan_status": "twenty_seventh_wave_validated_uncommitted", + "plan_status": "twenty_eighth_wave_validated_awaiting_commit", "execution_authorized": true, "execution_scope": { - "authorized_by": "User: comit and continue after R12 handoff recommending bounded experiments and sweep UI", + "authorized_by": "User: commit and start after wave27 named safe failed-trial retries; prior slice committed6f64ef6", "tasks": ["R06", "R07"], "permissions": [ - "Retained-input single-asset experiment and sweep UI components under pinned existing ADR-006; isolated implementation/review and full validation" + "Failed canonical experiment trial retry with immutable diagnostic receipts, SQL fencing and focused history/retry controls; isolated implementation/review and full validation" ], "excluded": [ "performance_profiling_or_optimization", @@ -23,7 +23,6 @@ "multi_asset_activation", "AI_execution_or_credentials", "historical_binary_provisioning", - "failed_run_retry", "cross_experiment_ranking" ], "pending_policy_decisions": [ @@ -1335,7 +1334,7 @@ "epic": "E6", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "review", "dependencies": ["R01", "R10", "F08", "S02", "D01", "W03", "C06", "R12"], "decision_dependencies": ["ADR-006"], "task_file": "backlog/tasks/R06.md", @@ -1350,11 +1349,11 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "partial_validated_uncommitted", - "integration_base": "30accfcf4370e96e58f771dff67639ea2a278188", + "integration_state": "validated_uncommitted", + "integration_base": "6f64ef62ba233b293ea1374c753bd0b467703792", "worktree": "/home/boki/repos/stock-bot", - "execution_component": "Retained-input atomic bounded experiments", - "component_exclusions": ["failed retry and broader R05 cutover"], + "execution_component": "Failed-trial retry with immutable diagnostic history", + "component_exclusions": ["broader R05 source/default cutover, standalone or batch retry"], "satisfied_component_dependencies": [ { "task": "R05", @@ -1363,19 +1362,20 @@ } ], "reviewed_by": "/root/r04_review", - "verification_reference": "ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24", - "review_notes": "Retained-input component independently reviewed and fully integrated. Full task stays in progress for its recorded exclusions; no downstream task is silently released.", + "verification_reference": "ROADMAP.md#twenty-eighth-wave-handoff--2026-10-24", + "review_notes": "Retained-input experiment and retry acceptance complete; independently reviewed and all integrated gates passed. Awaiting owner acceptance/commit before downstream readiness changes.", "implementation_slices": [ { "owner": "/root/r12_backend", - "worktree": "/tmp/stock-bot-wave27.iR6JOC/backend", - "scope": "Atomic experiment service/routes, SQL22 admission/retention, compact summaries and API/PostgreSQL tests" + "worktree": "/tmp/stock-bot-wave28.AqRnN8/backend", + "scope": "Guarded manual retry service/routes, immutable SQL23 failure receipts, HTTP/native/PostgreSQL/Redis regressions" }, { "owner": "/root", - "scope": "Shared DTO/export, API/web composition, old migration fixtures, actual native browser workflow and planning" + "scope": "Shared DTO, migration allowlist/old fixtures, actual native browser workflow, integrated gates and planning" } - ] + ], + "partial_commit": "6f64ef62ba233b293ea1374c753bd0b467703792" }, { "id": "R07", @@ -1398,26 +1398,27 @@ "completed_commit": null, "blocker": null, "release_gates": ["W04"], - "integration_state": "partial_validated_uncommitted", - "integration_base": "30accfcf4370e96e58f771dff67639ea2a278188", + "integration_state": "component_validated_uncommitted", + "integration_base": "6f64ef62ba233b293ea1374c753bd0b467703792", "worktree": "/home/boki/repos/stock-bot", - "execution_component": "Same-experiment preview/progress/comparison UI", + "execution_component": "Per-trial retry controls and retained history", "component_exclusions": ["cross-experiment comparisons and table performance measurements"], - "component_readiness": "May implement against root-pinned shared DTO; release requires accepted integration of R06 retained-input component. Full R06 is not claimed complete.", + "component_readiness": "Integrated against the validated R06 retry contract. Full R07 still excludes broader cross-experiment comparison and paused table rendering measurements.", "reviewed_by": "/root/r04_review", - "verification_reference": "ROADMAP.md#twenty-seventh-wave-handoff--2026-10-24", - "review_notes": "Retained-input component independently reviewed and fully integrated. Full task stays in progress for its recorded exclusions; no downstream task is silently released.", + "verification_reference": "ROADMAP.md#twenty-eighth-wave-handoff--2026-10-24", + "review_notes": "Retry/history controls independently reviewed and all integrated gates passed. Broader comparison and paused table measurements remain outstanding; full task is not complete.", "implementation_slices": [ { "owner": "/root/r12_frontend", - "worktree": "/tmp/stock-bot-wave27.iR6JOC/frontend", - "scope": "Experiment editor/list/detail, browser client and focused interaction tests" + "worktree": "/tmp/stock-bot-wave28.AqRnN8/frontend", + "scope": "Failed-trial review/retry/history UI, frozen intent through refresh and ambiguous responses, interaction regressions" }, { "owner": "/root", - "scope": "Shared DTO/export, API/web composition, old migration fixtures, actual native browser workflow and planning" + "scope": "Shared DTO, migration allowlist/old fixtures, actual native browser workflow, integrated gates and planning" } - ] + ], + "partial_commit": "6f64ef62ba233b293ea1374c753bd0b467703792" }, { "id": "R08", @@ -6581,7 +6582,7 @@ "One atomic expansion reuses existing durable runs/outbox; fixed input preview commitment prevents mutable-template drift. Financial and performance policies unchanged." ], "twenty_seventh_wave_validation": { - "state": "validated_uncommitted", + "state": "validated_committed", "scope": "R06/R07 retained-input components; both full tasks remain in_progress", "integration_base": "30accfcf4370e96e58f771dff67639ea2a278188", "log_directory": "/tmp/stock-bot-wave27.iR6JOC", @@ -6673,6 +6674,97 @@ "Chromium only; existing bundle-size/Rust warnings remain. No performance profiling/optimization/benchmark runs, new-wave commit, push or PR." ], "cleanup": "Both exact --rm disposable PostgreSQL/Redis containers stopped successfully. 35 authored source/test files archived and hashed. Worktrees/logs retained; development/production services and data untouched.", - "next": "Finish R06 failed-trial retry as a narrow durable-state change: retain prior diagnostics, keep immutable logical trial inputs, create a new fenced attempt only for failed runs without results, and reject completed/cancelled retries. Reuse existing lease/outbox machinery and expose truthful retry controls after backend integration. Keep performance paused and other release gates intact." + "next": "Finish R06 failed-trial retry as a narrow durable-state change: retain prior diagnostics, keep immutable logical trial inputs, create a new fenced attempt only for failed runs without results, and reject completed/cancelled retries. Reuse existing lease/outbox machinery and expose truthful retry controls after backend integration. Keep performance paused and other release gates intact.", + "completed_commit": "6f64ef62ba233b293ea1374c753bd0b467703792" + }, + "twenty_eighth_wave": ["R06", "R07"], + "twenty_eighth_wave_base": "6f64ef62ba233b293ea1374c753bd0b467703792", + "twenty_eighth_wave_notes": [ + "One manual retry receipt also retains the prior failure; both observed lifetime attempt and manual-retry counters identify the failure including preclaim errors.", + "Original input/review snapshot remains immutable; fresh retry requires current approval and records its receipt separately. Existing lifetime automatic recovery budget remains unchanged." + ], + "twenty_eighth_wave_validation": { + "state": "validated_uncommitted", + "scope": "R06 retained-input experiment acceptance complete; R07 retry/history component complete, broader task partial", + "artifacts": "/tmp/stock-bot-wave28.AqRnN8", + "source_archive": "/tmp/stock-bot-wave28.AqRnN8/validated-source.tar.gz", + "source_files": { + "apps/stock/config/src/contracts/experiments.ts": "9bea8dc6ef3557912a46b3516670f8857654834f494cb9aaa34e51366d9bb223", + "apps/stock/web-api/src/migrations/migration-runner.ts": "671a719e189c42931e3b4107a21480ac66d4400c525b95ade4d4285346952370", + "apps/stock/web-api/src/routes/experiments.routes.ts": "560ccd8577fc73355aec1b91ad3235e5d3d3bd660cc0e25e12e783387f0d9e3e", + "apps/stock/web-api/src/services/experiment-retry.ts": "9a44aa7dfe875d7b66b9715df6f5ae1b7eaccb2c5e1ad61bbfa32e9f11d1b3f0", + "apps/stock/web-api/src/services/experiments.service.ts": "bfcf8d8034992278f539fda3744c65bc31754279b7c8bdd6acd1a0e625e22475", + "apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx": "f0827a1e50cd23a5f1aabd308de0368511a6b8dd72a88d4876bb1a0c6f45c82e", + "apps/stock/web-app/src/features/experiments/components/ExperimentTrialRecovery.tsx": "5e4016ce052e6e14ba5f3679777523ca2511ad087987b44505e4a147195acd51", + "apps/stock/web-app/src/features/experiments/services/experimentApi.ts": "b145996dede2ecb0838f1641029d82d8313d54b9189bf898ebbfe79ca4d1fdc7", + "database/postgres/init/23-experiment-retries.sql": "f19b7cf759a71cd3eeb55d0a0ca84a386d32fb0cad062e034901dfce96bbadd2", + "test/e2e/fixture.ts": "bf25802f3aa0c43d2229f658eb7c64ab99fef5d7320b1247faa36c7861d4198c", + "test/e2e/workbench.test.ts": "ee52abf3732340582c19e5e1479cc7a4a01fb7ac68904ce9946c1737596f9355", + "test/integration/experiment-retries-api.test.ts": "0228c9315a72a987473a3a0702af3ceecdebb547ffbd6fd7cd64b3945db44b82", + "test/integration/experiment-retries-ui.test.tsx": "6232596fb63842e5cf2759b379d776aa010a0be67325354052530b0f41cf3c88", + "test/integration/experiments-api.test.ts": "98caacdae9d30b5a5d6da113eabd07477494a6e238213c0dd8934b3adedfea5f", + "test/integration/experiments-ui.test.tsx": "3aa2f144b7d3bb4f122fe4a8031cff0b410bef9fa6d63b0fd1329204a9e96c2e", + "test/postgres/canonical-durable-backtest.test.ts": "9281282c6c84c75291cdade49e787b3a8c6b5f312c471829a01b060d75dfd0bc", + "test/postgres/canonical-research.test.ts": "95ceffc10022315119a9836352a7381f348900bc243789a5a19c79b313681545", + "test/postgres/catalog-backtest-drafts.test.ts": "5f16f9e917838af049ad1dcc54cf4cbab2176a42ecfd2606125071e9056df356", + "test/postgres/dataset-catalog.test.ts": "60202d147c978277ed1daf7f0b584fb89d987e8fa64ec2a19e0a7fd84568e12f", + "test/postgres/durable-backtest.test.ts": "3f1364982fbb3b1d6668fb91ae834f9853739b67f743586b6484c54a1f0c6015", + "test/postgres/experiment-retries.test.ts": "821f8b6a7407b9b16cad906519a649e8ad0f0e96312cb3252e8fe3fc2b069e4f", + "test/postgres/experiments.test.ts": "1b1eb3ea3cd778f72c471f8f971320fbc23222ac3fc3c470f450b8c75356d90d", + "test/postgres/migration-runner.test.ts": "b368039e030c5e1a1d71b12a17556e2e0267855a7a35215fd9a06675a783175d", + "test/postgres/research-retention.test.ts": "b47c24af8da0e182fad9f467519e33711fbcf7407bcd36565929d01f79f87a51", + "test/postgres/research-runtime-isolation.test.ts": "5b078b6c9fd33f329309c3a9a162432175cef254aef103b6125980f953a7552a", + "test/postgres/research-workspace.test.ts": "a2a386c4aca55e344767a9e71664b176b164e031cf9717e7de0f0efe534c30be", + "test/postgres/run-reproduction.test.ts": "16cdd2c8e0a014033260713cb139241965b8478eec72b55a1df2096397a915c2" + }, + "checks": [ + { + "command": "CARGO_BUILD_JOBS=2 bun run check", + "log": "/tmp/stock-bot-wave28.AqRnN8/check.log", + "outcome": "All repository gates passed: build/source/contracts/secrets/lint; 93 tooling, 43 utility, 44 calculation, 738 integration and 150 Rust tests (4 existing manual Rust ignored); zero failures." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:postgres", + "log": "/tmp/stock-bot-wave28.AqRnN8/postgres.log", + "outcome": "190 tests / 1609 assertions passed across 21 files. New focused retry suite11/101 covers exact timestamp/history retention, preclaim0 recurrence, stale callbacks, same/cross-parent receipt races, cancellation/archive/build gates, SQL tampering/rollback, Redis outage/native recovery and first/idempotent migration preservation." + }, + { + "command": "PIPELINE_TEST_DATABASE_URL= BACKTEST_TEST_REDIS_URL= bun run test:e2e", + "log": "/tmp/stock-bot-wave28.AqRnN8/e2e.log", + "outcome": "11 Chromium workflows / 285 assertions passed. New workflow records a real durable failed attempt, retries through the UI after mutable template/review changes, completes original inputs through Rust, replays the receipt after completion, checks exact timestamp/history and reopens the result. All 10 previous workflows passed." + }, + { + "command": "bunx tsc --project /tmp/stock-bot-wave28.AqRnN8/tests-tsconfig.json --noEmit", + "log": "/tmp/stock-bot-wave28.AqRnN8/integrated-test-types.log", + "outcome": "Strict new/changed tests and dependent sources passed." + }, + { + "command": "bunx eslint --max-warnings 0; bunx prettier --check ; git diff --check", + "log": "/tmp/stock-bot-wave28.AqRnN8/integrated-test-lint.log", + "outcome": "Scoped test lint, all changed source formatting and whitespace checks passed; final planning formatting checked separately." + }, + { + "command": "CARGO_BUILD_JOBS=2 bun run --cwd apps/stock/engine build:release", + "log": "/tmp/stock-bot-wave28.AqRnN8/native-release.log", + "outcome": "Release addon restored before PostgreSQL/browser gates. SHA256 ef00eed556f5c32332d36a9a00ef710682e90deb00b54552e4b5c8bfdfbe8103 matches previous wave; no engine/runner/dispatcher source changes." + } + ], + "reviews": [ + { + "reviewer": "/root/r04_review", + "scope": "All12 agent-owned hashes, shared contract, SQL23, final focused tests and root actual-browser/fixture delta", + "outcome": "Accepted without remaining source blockers. Independently ran API 12/177 and final retry/experiment UI 63/311; reviewed final backend PG 11/101 evidence. Root integrated all gates. R06 can enter review/uncommitted; full R05/R07 remain partial." + } + ], + "limitations": [ + "Manual retries apply only to failed canonical experiment trials with no result or cancellation. Same retained approved built-in, eligible single-asset data and exact installed build required for fresh acceptance. No standalone/batch retry endpoint.", + "History contains exact prior failures captured by accepted manual retries, not a reconstructed log of every automatic attempt. Original request/review snapshot remains unchanged; current approval is recorded separately on the receipt.", + "Lifetime attempt_number cannot decrease for experiment runs. Manual acceptance increments manual_retry_count only; the worker creates its fresh attempt UUID and increments attempt_number. Existing lifetime automatic-recovery budget is not reset.", + "Accepted receipt replay precedes current eligibility checks. Unresolved browser retry inputs/key persist through component refresh, not deliberate unload/navigation; saved receipts/history remain durable.", + "R05 provider preparation/default cutover and broader R07 comparisons remain incomplete. R08 readiness awaits R06 acceptance/commit; A01 additionally needs ADR-007. No performance/benchmark work, candidate execution, multi-asset/default/paper/live activation, AI execution, new-wave commit, push or PR.", + "Chromium only; existing bundle-size/Rust warnings and four manual Rust test exclusions remain. Initial focused SQL test parameter-type fixture error was corrected before the frozen 11/101 suite; final integrated gates passed on their first run." + ], + "cleanup": "Both exact --rm disposable PostgreSQL/Redis fixture containers stopped successfully. 27 authored source/test files archived and hashed; isolated worktrees/logs retained. Development/production services and data untouched.", + "next": "Accept/commit this R06 retry completion, then start R08 bounded chronological parameter selection and reset-segment validation on the accepted retained-input experiment foundation. Pin explicit training/validation/test/warmup boundaries and selection rule before execution; preserve all candidate evidence and label reset-segment results honestly. Keep performance paused and R05/R07/AI/multi-asset/default activation gates intact." } } diff --git a/docs/development/backlog/tasks/R06.md b/docs/development/backlog/tasks/R06.md index 775f05c9..11468329 100644 --- a/docs/development/backlog/tasks/R06.md +++ b/docs/development/backlog/tasks/R06.md @@ -31,7 +31,7 @@ Write locks: sql-migrations, experiment-api. One agent owns this change. Lock na ## Dependencies and blockers -The retained-input component requires the accepted R05 durable-run/provenance slice plus R01/R10/F08/S02/D01/W03/C06/R12. The manifest records that narrower prerequisite; provider preparation and broader default cutover remain outside it. Full R06 still requires the failed-retry acceptance below. +The retained-input component requires the accepted R05 durable-run/provenance slice plus R01/R10/F08/S02/D01/W03/C06/R12. The manifest records that narrower prerequisite; provider preparation and broader default cutover remain outside it. The failed-retry continuation satisfies the remaining acceptance below; final integration evidence is recorded in its validated handoff. Architecture decisions: ADR-006. Agents may not independently amend their policies. @@ -69,7 +69,7 @@ Report scope changes (if any), fixture expectations, API/schema changes, measure ## Authorized component — 2026-10-24 -Retained-input single-asset experiments depend on the accepted R05 runner/provenance component (`618fb9e`), not provider preparation or default cutover. One atomic bounded grid uses a current approved retained built-in, one eligible dataset and installed build, and fixed financial/reporting policy. Preview commits to exact inputs; submission receipts survive current eligibility changes. Existing runs/outbox/worker own execution. Failed retry is excluded from this component; full R06 remains incomplete until retry diagnostics/fencing acceptance is met. +Retained-input single-asset experiments depend on the accepted R05 runner/provenance component (`618fb9e`), not provider preparation or default cutover. One atomic bounded grid uses a current approved retained built-in, one eligible dataset and installed build, and fixed financial/reporting policy. Preview commits to exact inputs; submission receipts survive current eligibility changes. Existing runs/outbox/worker own execution. Failed retry was excluded from this first component; its continuation below supplies the remaining diagnostics/fencing acceptance. ### Pinned experiment contract @@ -77,8 +77,22 @@ Retained-input single-asset experiments depend on the accepted R05 runner/proven All children and outbox rows commit with the immutable experiment in one transaction. The initial bound is 100 trials; it bounds atomic admission and does not introduce a parallel scheduler. Only parameters and new run/account/session identities vary. `experiment_id`/`trial_key`/`trial_index` are immutable and mutually exclusive with new-run reproduction lineage. Child submission receipts are null; the experiment owns the unique principal/key receipt. SQL reconstructs exact trial requests from the manifest and preserves ordinary/reproduction admission guards. No template cloning/edit loop or separate financial engine. -Cancellation latches once, cancels pending children and requests worker acknowledgement for active children, preserving terminal outcomes. Counts are derived from actual children; the frozen candidate count exposes missing rows. Compact summaries validate retained provenance and statistical conventions, preserve null reasons and list inconsistent results as incomparable. No detail-array loading or financial recalculation is needed. Failed-run retry remains absent until history/fencing tests are implemented. +Cancellation latches once, cancels pending children and requests worker acknowledgement for active children, preserving terminal outcomes. Counts are derived from actual children; the frozen candidate count exposes missing rows. Compact summaries validate retained provenance and statistical conventions, preserve null reasons and list inconsistent results as incomparable. No detail-array loading or financial recalculation is needed. Failed-run retry was deferred from this first component to the continuation below. ### Validated component handoff -The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This component is uncommitted and does not complete the full task or release its downstream dependencies. +The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This first component is committed as `6f64ef6`; it did not alone complete the full task or release its downstream dependencies. + +## Failed-trial retry continuation — 2026-10-24 + +The retained-input experiment component is committed as `6f64ef6`. This continuation completes its failed-trial retry acceptance using the same immutable logical run. POST `/api/v2/experiments/:id/trials/:runId/retry` requires a stable idempotency key and both observed attempt/retry counters. GET the corresponding `/retries` path returns append-only snapshots captured by accepted manual retries. + +The new receipt retains the prior failure directly from SQL before clearing execution state; PostgreSQL timestamp precision is preserved. Current original-version approval and retained build/data eligibility are rechecked for fresh acceptance, with current approval recorded separately from the immutable original request. Completed/cancelled/result-bearing trials and cancelled experiments cannot be retried. Receipt replay precedes current eligibility checks. + +Lock order is parent → experiment → run → strategy family. Atomic acceptance increments `manual_retry_count`, resets execution fields and makes the existing outbox due; `attempt_number` remains monotonic and the worker supplies a fresh UUID. Manual retry does not reset the existing lifetime automatic-recovery budget. History is explicitly previous failure snapshots preserved by manual retries, not invented history of every old automatic attempt. Existing simulator/financial semantics remain unchanged. + +### Validated retry handoff + +R06's retained-input acceptance is complete and independently reviewed; status is `review` / `validated_uncommitted`. Existing bounded expansion/cancellation/compact comparison behavior is preserved. Full repository gates, PostgreSQL (190 tests / 1609 assertions) and Chromium (11 workflows / 285 assertions) passed. Exact source hashes and logs: `manifest.json` → `twenty_eighth_wave_validation`. + +The retry suite proves exact failure snapshots, duplicate/stale intent handling, lifetime counter monotonicity, rollback, old-attempt fencing, Redis recovery, current original-version approval and actual Rust completion with one result. SQL23 adds guards only to experiment retry semantics; ordinary run lifecycle behavior remains intact. No engine or dispatcher changes were required. Downstream R08 remains blocked until acceptance/commit; broader R05 cutover is still separate. diff --git a/docs/development/backlog/tasks/R07.md b/docs/development/backlog/tasks/R07.md index 89024065..ada7fb71 100644 --- a/docs/development/backlog/tasks/R07.md +++ b/docs/development/backlog/tasks/R07.md @@ -28,7 +28,7 @@ Write locks: web-experiments. One agent owns this change. Lock names do not over ## Dependencies and blockers -Component implementation may proceed against root-pinned R06 DTOs; activation requires integrated retained-input R06 admission/results. Full R06 failed-retry work is independent of this component and no retry action is exposed. +Component implementation may proceed against root-pinned R06 DTOs; activation requires integrated retained-input R06 admission/results. The initial component did not expose retry; the continuation below adds controls against the separately reviewed R06 retry contract. Architecture decisions: ADR-006. Agents may not independently amend their policies. @@ -77,4 +77,14 @@ Ambiguous submission preserves its exact body/key, and only an explicit new inte ### Validated component handoff -The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This component is uncommitted and does not complete the full task or release its downstream dependencies. +The retained-input component is implemented and independently reviewed. Full repository, PostgreSQL and Chromium gates passed; exact source hashes and logs are in `manifest.json` → `twenty_seventh_wave_validation`. See the twenty-seventh-wave roadmap handoff. This first component is committed as `6f64ef6`; it did not alone complete the full task or release its downstream dependencies. + +## Retry controls continuation — 2026-10-24 + +The first experiment UI component is committed as `6f64ef6`. Add per-trial failed-retry review/confirmation and lazy immutable failure-history views against the pinned R06 API. Preserve exact unresolved body/key through refresh and guard late responses, cancellation and route changes; a later failure requires a deliberate new intent. Reopening must show saved failure evidence after successful completion. Broader comparison/table measurement remains outside this continuation; performance work stays paused. + +### Validated retry controls handoff + +The retry/history component is independently reviewed and `component_validated_uncommitted`. The actual Chromium workflow retries a failed canonical trial, verifies the original immutable inputs despite template edits, replays the accepted receipt after completion and reopens saved failure history and the native result. Interaction tests cover uncertain responses, stale refresh/route responses, cancellation coordination, null/history/error states and explicit discard/new intent. Exact logs and hashes: `manifest.json` → `twenty_eighth_wave_validation`. + +Full R07 remains in progress for broader cross-experiment comparison and table measurements. All performance work stays paused. No new finance, statistics or result-ranking logic was added. diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index bc90283e..a867fcd1 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -294,6 +294,7 @@ export async function fixture(browser: Browser, native = false) { '20-research-workspace.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') @@ -345,6 +346,17 @@ export async function fixture(browser: Browser, native = false) { const engine = native ? new RustBacktestAdapter({ logger, storage: runStorage }, { timeoutMs: 15000 }) : controlled; + const canonicalFailures: string[] = []; + if (engine instanceof RustBacktestAdapter) { + const executeCanonical = engine.runCanonical.bind(engine); + engine.runCanonical = async (...args) => { + const failure = canonicalFailures.shift(); + if (failure) { + throw new Error(failure); + } + return executeCanonical(...args); + }; + } const runner = new BacktestRunner({ engine, engineName: 'native', @@ -570,6 +582,12 @@ export async function fixture(browser: Browser, native = false) { frames, delayResponse, controlled, + failNextCanonical: (message: string) => { + if (!native) { + throw new Error('A native fixture is required for canonical failure injection'); + } + canonicalFailures.push(message); + }, dispatcher, request, login, diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 69badd75..f67b3e3d 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -5,7 +5,12 @@ import { canonicalResearchSettingsSchema, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; -import type { ExperimentDetail, ExperimentPreview } from '@stock-bot/stock-config/experiments'; +import type { + ExperimentDetail, + ExperimentPreview, + ExperimentRetryResult, + ExperimentTrialRetry, +} from '@stock-bot/stock-config/experiments'; import { retainResearchDataset } from '../../scripts/import-research-dataset'; import { canonicalSettings } from '../fixtures/canonical-research'; import { canonicalSmaFixture } from '../fixtures/canonical-sma'; @@ -31,6 +36,166 @@ afterAll(async () => { }); const fixture = (native = false) => createFixture(browser, native); +test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_browser', async () => { + const f = await fixture(true); + f.page.on('dialog', dialog => void dialog.accept()); + try { + const { dataset } = canonicalSmaFixture(); + await retainResearchDataset(f.pool, dataset); + const selected = (await f.seedCatalog()).find( + item => item.package.program.strategyId === 'sma_crossover' + )!; + await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', { + decision: 'approve', + reason: 'Reviewed retained failure/retry fixture', + }); + const definition = { + name: 'Retry original inputs', + strategy: 'catalog', + strategyVersionId: selected.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: dataset.manifest.executionSeries.map(series => series.instrumentId), + startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: dataset.manifest.hash, + dataFrequency: dataset.manifest.series[0]!.interval, + canonical: canonicalSettings, + }, + }; + const backtest = await f.request('/api/v2/backtests', 'POST', { + ...definition, + autoStart: false, + }); + const input = { backtestId: backtest.id, name: 'Recovered experiment', grid: {} }; + const { preview } = (await f.request('/api/v2/experiments/preview', 'POST', input)) as { + preview: ExperimentPreview; + }; + const { experiment } = (await f.request( + '/api/v2/experiments', + 'POST', + { ...input, previewHash: preview.previewHash }, + { 'Idempotency-Key': randomUUID() } + )) as { experiment: ExperimentDetail }; + const runId = experiment.trials[0]!.runId!; + f.failNextCanonical('Injected canonical worker failure before financial replay'); + f.dispatcher.start(); + await until( + async () => + (await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status === + 'failed', + 'original canonical attempt fails durably' + ); + const failed = ( + await f.pool.query( + `SELECT *,to_char(completed_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS completed_at_exact + FROM runs WHERE id=$1`, + [runId] + ) + ).rows[0]; + expect(failed.attempt_number).toBe(1); + expect(failed.manual_retry_count).toBe(0); + expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(0); + // A retry uses the original request even after edits and a later approval. + await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', { + ...definition, + name: 'Changed template after failure', + initialCapital: 20000, + strategyParameters: { fastPeriod: 1, slowPeriod: 2 }, + }); + await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', { + decision: 'approve', + reason: 'Reapproved original version for the manual retry', + }); + await f.login(); + await f.page.goto(`${f.origin}/experiments/${experiment.id}`); + await visible(f.page, /failed: 1/); + await f.page.getByRole('button', { name: 'Retry trial 1', exact: true }).click(); + const retrying = f.page.waitForResponse(response => + response.url().endsWith(`/experiments/${experiment.id}/trials/${runId}/retry`) + ); + await f.page.getByRole('button', { name: 'Confirm retry trial 1', exact: true }).click(); + const response = await retrying; + expect(response.status()).toBe(202); + expect(response.request().postDataJSON()).toEqual({ + expectedAttemptNumber: 1, + expectedRetryCount: 0, + }); + const accepted = (await response.json()) as ExperimentRetryResult; + expect(accepted.retry.runId).toBe(runId); + expect(accepted.retry.previousAttemptId).toBe(failed.attempt_id); + expect(accepted.retry.previousAttemptNumber).toBe(1); + expect(accepted.retry.retryNumber).toBe(1); + expect(accepted.retry.error).toBe(failed.error); + expect(accepted.retry.completedAt).toBe(failed.completed_at_exact); + expect(accepted.retry.reviewId).not.toBe(failed.request_snapshot.strategy.reviewId); + await until( + async () => + (await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status === + 'completed', + 'retried trial redispatches and completes in the native engine' + ); + const complete = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0]; + expect(complete.attempt_number).toBe(2); + expect(complete.attempt_id).not.toBe(failed.attempt_id); + expect(complete.manual_retry_count).toBe(1); + expect(complete.request_snapshot).toEqual(failed.request_snapshot); + expect(complete.dataset_hash).toBe(failed.dataset_hash); + expect(complete.trial_key).toBe(failed.trial_key); + expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1); + expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1); + const replay = await f.page.evaluate( + async ({ path, key, body }) => { + const reply = await fetch(path, { + method: 'POST', + credentials: 'include', + headers: { + 'Content-Type': 'application/json', + 'Idempotency-Key': key, + }, + body: JSON.stringify(body), + }); + return { status: reply.status, body: await reply.json() }; + }, + { + path: `/api/v2/experiments/${experiment.id}/trials/${runId}/retry`, + key: response.request().headers()['idempotency-key']!, + body: response.request().postDataJSON(), + } + ); + expect(replay.status).toBe(202); + expect(replay.body.retry.id).toBe(accepted.retry.id); + await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click(); + await visible(f.page, /completed: 1/); + expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(1); + await f.page + .getByRole('button', { name: 'Show retry history for trial 1', exact: true }) + .click(); + await visible(f.page, /Injected canonical worker failure before financial replay/); + const { retries } = (await f.request( + `/api/v2/experiments/${experiment.id}/trials/${runId}/retries` + )) as { + retries: ExperimentTrialRetry[]; + }; + expect(retries).toEqual([accepted.retry]); + await f.page.reload(); + await visible(f.page, /completed: 1/); + await f.page + .getByRole('button', { name: 'Show retry history for trial 1', exact: true }) + .click(); + await visible(f.page, /Injected canonical worker failure before financial replay/); + await f.page.locator(`a[href="/backtests/${backtest.id}/run/${runId}"]`).click(); + await visible(f.page, 'Canonical research result'); + const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult; + expect(result.request).toEqual(failed.request_snapshot); + expect(f.historicalDataReads).toEqual([]); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}); + test('retained_experiment_preview_submit_compare_cancel_and_reopen_browser', async () => { const f = await fixture(true); f.page.on('dialog', dialog => void dialog.accept()); diff --git a/test/integration/experiment-retries-api.test.ts b/test/integration/experiment-retries-api.test.ts new file mode 100644 index 00000000..ab97f2f0 --- /dev/null +++ b/test/integration/experiment-retries-api.test.ts @@ -0,0 +1,369 @@ +import { randomUUID } from 'node:crypto'; +import { describe, expect, mock, test } from 'bun:test'; +import { Hono } from 'hono'; +import { z } from 'zod'; +import { createHttpSecurity } from '@stock-bot/di'; +import type { IServiceContainer } from '@stock-bot/services'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes'; +import { + buildExperimentPreview, + experimentHash, + PREVIEW_RUN_ID, +} from '../../apps/stock/web-api/src/services/experiment-input'; +import { canonicalSmaFixture } from '../fixtures/canonical-sma'; + +const tokens = { + operator: 'experiment-admin-fixture-not-a-real-secret-1234', + service: 'experiment-service-fixture-not-a-real-secret-1234', + read: 'experiment-read-fixture-not-a-real-secret-1234', +}; +const backtestId = randomUUID(), + experimentId = randomUUID(); +const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } }; +type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record[] }>; +function fixture( + mode: 'enabled' | 'disabled' | 'absent' = 'enabled', + query: Query = async () => ({ rows: [] }) +) { + const client = { query: mock(query) }; + const database = { + ...client, + transaction: mock(async (work: (client: { query: Query }) => Promise) => work(client)), + }; + const app = new Hono(); + if (mode !== 'absent') { + createHttpSecurity({ + adminToken: tokens.operator, + serviceToken: tokens.service, + readToken: tokens.read, + environment: 'test', + hostname: '127.0.0.1', + disabled: mode === 'disabled', + }).mount(app); + } + app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer)); + return { + database, + request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) { + return app.request(`/api/v2/experiments${path}`, { + method, + headers: { + 'Content-Type': 'application/json', + ...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}), + ...(key === undefined ? {} : { 'Idempotency-Key': key }), + }, + ...(body === undefined ? {} : { body }), + }); + }, + }; +} +function retainedPreview() { + const version = randomUUID(), + owner = `strategy:${version}`; + const fixture = canonicalSmaFixture([owner]); + const descriptor = builtinCatalogDescriptors[0]!; + const policy = structuredClone(fixture.config); + policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID; + policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`; + const request = canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: PREVIEW_RUN_ID, + backtestId, + name: 'Template', + strategy: { + familyId: randomUUID(), + versionId: version, + origin: 'builtin', + reviewId: randomUUID(), + package: { + version: 1, + program: descriptor.program, + parameterSchema: descriptor.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: descriptor.entryExport, + content: 'fixture', + sha256: 'a'.repeat(64), + }, + dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: 'fixture', target: 'browser' }, + }, + selection: fixture.selections[0], + }, + datasetHash: fixture.dataset.manifest.hash, + policy, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: 'fixture', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }); + return buildExperimentPreview(input, request, fixture.dataset.manifest); +} + +const runId = randomUUID(); +const retryBody = { expectedAttemptNumber: 1, expectedRetryCount: 0 }; +const path = `/${experimentId}/trials/${runId}`; +function savedRetry(overrides: Record = {}) { + return { + id: randomUUID(), + experiment_id: experimentId, + run_id: runId, + trial_key: 'a'.repeat(64), + retry_number: 1, + previous_attempt_number: 1, + previous_attempt_id: null, + error: null, + progress: '14.25', + current_simulation_date: null, + started_at: null, + completed_at: '2026-10-24T10:00:00.123456Z', + paused_at: null, + failure_updated_at: '2026-10-24T10:00:00.654321Z', + recorded_at: '2026-10-24T10:00:01.000001Z', + principal: 'operator', + review_id: randomUUID(), + submission_hash: 'a'.repeat(64), + ...overrides, + }; +} +function detailRow(preview: ReturnType) { + return { + id: experimentId, + backtest_id: backtestId, + name: input.name, + created_at: '2026-10-24T00:00:00Z', + cancel_requested: true, + trial_count: 2, + dataset_hash: preview.request.datasetHash, + strategy_version_id: preview.request.strategy.versionId, + preview_hash: preview.previewHash, + counts: {}, + preview, + }; +} + +describe('failed trial retry HTTP contract', () => { + test('credential proof/read role/strict body/counters/IDs/receipt key gate storage', async () => { + for (const mode of ['enabled', 'disabled', 'absent'] as const) { + const f = fixture(mode); + expect( + (await f.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), undefined, 'key')) + .status + ).toBe(401); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + const read = fixture(); + expect( + (await read.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'read', 'key')).status + ).toBe(403); + expect((await read.request(`${path}/retries`)).status).toBe(401); + for (const [target, body, key] of [ + [path, '{}', 'key'], + [path, '{', 'key'], + [path, JSON.stringify({ ...retryBody, expectedRetryCount: -1 }), 'key'], + [path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 1.5 }), 'key'], + [path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 2147483648 }), 'key'], + [path, JSON.stringify({ ...retryBody, parameters: { fastPeriod: 2 } }), 'key'], + [path, JSON.stringify(retryBody), undefined], + [path, JSON.stringify(retryBody), 'bad key'], + [path, JSON.stringify(retryBody), 'x'.repeat(201)], + [`/bad/trials/${runId}`, JSON.stringify(retryBody), 'key'], + [`/${experimentId}/trials/bad`, JSON.stringify(retryBody), 'key'], + ]) { + const f = fixture(); + expect((await f.request(`${target}/retry`, 'POST', body, 'operator', key)).status).toBe(400); + expect(f.database.query.mock.calls).toHaveLength(0); + expect(f.database.transaction.mock.calls).toHaveLength(0); + } + expect( + (await read.request(`/${experimentId}/trials/bad/retries`, 'GET', undefined, 'read')).status + ).toBe(400); + }); + test('accepted receipt replay returns202/current detail before current eligibility and preserves historical timestamp precision', async () => { + const preview = retainedPreview(); + const hash = experimentHash({ + version: 1, + operation: 'retry-experiment-trial', + experimentId, + runId, + ...retryBody, + }); + for (const principal of ['operator', 'service'] as const) { + const saved = savedRetry({ + principal, + submission_hash: hash, + trial_key: preview.candidates[0]!.trialKey, + }); + const f = fixture('enabled', async (sql, values) => { + if (sql.includes('h.principal=$1')) { + expect(values).toEqual([principal, 'accepted']); + return { rows: [saved] }; + } + if (sql.includes('SELECT r.id')) { + return { rows: [] }; + } + expect(sql).not.toContain('FROM backtests'); + expect(sql).not.toContain('FOR UPDATE'); + return { rows: [detailRow(preview)] }; + }); + const response = await f.request( + `${path}/retry`, + 'POST', + JSON.stringify(retryBody), + principal, + 'accepted' + ); + expect(response.status).toBe(202); + expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + const result = await response.json(); + expect(result.retry).toMatchObject({ + id: saved.id, + runId, + experimentId, + principal, + previousAttemptId: null, + error: null, + progress: 14.25, + completedAt: '2026-10-24T10:00:00.123456Z', + failureUpdatedAt: '2026-10-24T10:00:00.654321Z', + }); + expect(result.experiment.cancelRequested).toBe(true); + expect(result.experiment.trials[0]).toMatchObject({ + status: 'missing', + attemptNumber: 0, + retryCount: 0, + }); + expect(result.retry).not.toHaveProperty('submission_hash'); + } + }); + test('history returns ordered immutable snapshots and membership uses404/409 without accepting another experiment', async () => { + const saved = savedRetry(); + const f = fixture('enabled', async sql => { + if (sql.includes('SELECT id FROM research_experiments')) { + return { rows: [{ id: experimentId }] }; + } + if (sql.includes('SELECT experiment_id FROM runs')) { + return { rows: [{ experiment_id: experimentId }] }; + } + expect(sql).toContain('ORDER BY h.retry_number'); + expect(sql).not.toContain('canonical_result'); + return { rows: [saved] }; + }); + const response = await f.request(`${path}/retries`, 'GET', undefined, 'read'); + expect(response.status).toBe(200); + expect((await response.json()).retries[0]).toMatchObject({ id: saved.id, retryNumber: 1 }); + const missing = fixture(); + expect((await missing.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(404); + const wrong = fixture('enabled', async sql => ({ + rows: sql.includes('research_experiments') + ? [{ id: experimentId }] + : [{ experiment_id: randomUUID() }], + })); + expect((await wrong.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(409); + }); + test('conflict/missing/stale are explicit and arbitrary database/schema faults remain sanitized500', async () => { + const conflict = fixture('enabled', async () => ({ rows: [savedRetry()] })); + expect( + ( + await conflict.request( + `${path}/retry`, + 'POST', + JSON.stringify(retryBody), + 'operator', + 'key' + ) + ).status + ).toBe(409); + const missing = fixture(); + expect( + (await missing.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key')) + .status + ).toBe(404); + const stale = fixture('enabled', async sql => { + if (sql.includes('experiment_trial_retries')) { + return { rows: [] }; + } + if (sql.includes('FROM backtests')) { + return { rows: [{ id: backtestId, archived_at: null }] }; + } + if (sql.includes('FROM research_experiments')) { + return { rows: [{ id: experimentId, cancel_requested: false }] }; + } + return { + rows: [ + { + id: runId, + experiment_id: experimentId, + status: 'failed', + cancel_requested: false, + attempt_number: 1, + manual_retry_count: 1, + }, + ], + }; + }); + expect( + (await stale.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key')) + .status + ).toBe(409); + for (const failure of [new Error('private connection details'), new z.ZodError([])]) { + const f = fixture('enabled', async () => { + throw failure; + }); + for (const [suffix, method, body] of [ + ['retry', 'POST', JSON.stringify(retryBody)], + ['retries', 'GET', undefined], + ]) { + const response = await f.request(`${path}/${suffix}`, method, body, 'operator', 'key'); + expect(response.status).toBe(500); + expect(await response.text()).not.toContain('private'); + } + } + }); + test('counter projection uses the same child rows as statuses rather than previous summary observations', async () => { + const preview = retainedPreview(); + const f = fixture('enabled', async sql => + sql.includes('SELECT r.id') + ? { + rows: [ + { + id: runId, + trial_index: 0, + trial_key: preview.candidates[0]!.trialKey, + status: 'failed', + attempt_number: 3, + manual_retry_count: 2, + progress: 14, + cancel_requested: false, + error: 'later failure', + request_snapshot: null, + dataset_hash: preview.request.datasetHash, + backtest_id: backtestId, + }, + ], + } + : { rows: [detailRow(preview)] } + ); + const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read'); + expect(response.status).toBe(200); + expect((await response.json()).experiment.trials[0]).toMatchObject({ + status: 'failed', + attemptNumber: 3, + retryCount: 2, + error: 'later failure', + }); + }); +}); diff --git a/test/integration/experiment-retries-ui.test.tsx b/test/integration/experiment-retries-ui.test.tsx new file mode 100644 index 00000000..09bd6651 --- /dev/null +++ b/test/integration/experiment-retries-ui.test.tsx @@ -0,0 +1,801 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement } from 'react'; +import type { Root } from 'react-dom/client'; +import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research'; +import type { + ExperimentDetail, + ExperimentPreview, + ExperimentTrial, + ExperimentTrialRetry, +} from '@stock-bot/stock-config/experiments'; +import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy'; +import { nativeReplayFixture } from '../fixtures/native-replay'; + +const browser = new GlobalWindow({ url: 'http://localhost:5173' }); +const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); +let createRoot: typeof import('react-dom/client').createRoot; +let router: typeof import('react-router-dom'); +let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage; +let root: Root | undefined; +let host: HTMLDivElement; +let navigate: ReturnType; +let location = ''; +const backtestId = '11111111-1111-4111-8111-111111111111'; +const experimentId = '33333333-3333-4333-8333-333333333333'; +const otherExperimentId = '44444444-4444-4444-8444-444444444444'; +const versionId = '55555555-5555-4555-8555-555555555555'; +const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`; +const retryPath = (index = 0, id = experimentId) => + `/api/v2/experiments/${id}/trials/${runId(index)}/retry`; +const historyPath = (index = 0, id = experimentId) => + `/api/v2/experiments/${id}/trials/${runId(index)}/retries`; +function deferred() { + let resolve!: (value: T) => void; + let reject!: (cause: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} +type Pending = ReturnType> & { + path: string; + method: string; + body: unknown; + rawBody: unknown; + headers: Headers; + settled: boolean; + signal?: AbortSignal | null; + credentials?: RequestCredentials; +}; +const requests: Pending[] = []; +function request(path: string, method = 'GET') { + const found = requests.find( + item => item.path === path && item.method === method && !item.settled + ); + if (!found) { + throw new Error( + `Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}` + ); + } + return found; +} +function reply(item: Pending, value: unknown, status = 200) { + item.settled = true; + item.resolve(Response.json(value, { status })); +} +async function flush(action: () => void = () => {}) { + await act(async () => { + action(); + await Promise.resolve(); + }); +} +function button(label: string) { + const found = [...host.querySelectorAll('button')].find( + item => item.textContent?.trim() === label + ); + if (!found) { + throw new Error(`Missing button ${label}: ${host.textContent}`); + } + return found; +} +function Probe() { + navigate = router.useNavigate(); + location = router.useLocation().pathname; + return null; +} +function preview(count = 2, parent = backtestId): ExperimentPreview { + const owner = `strategy:${versionId}`; + const { config, dataset } = nativeReplayFixture(3, 1, [owner]); + const previewId = '00000000-0000-4000-8000-000000000001'; + config.matching.risk.ledger.sessionId = previewId; + config.matching.risk.ledger.accountId = `research:${previewId}`; + const builtin = builtinCatalogDescriptors[0]!; + const candidates = Array.from({ length: count }, (_, index) => ({ + index, + trialKey: String(index + 1).padStart(64, '0'), + parameters: { fastPeriod: index + 2, slowPeriod: 20 }, + })); + return { + version: 'research-experiment-preview/v1', + previewHash: 'e'.repeat(64), + input: { + backtestId: parent, + name: 'Trend study', + grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) }, + }, + dataset: dataset.manifest, + candidates, + request: canonicalRunRequestSchema.parse({ + kind: 'canonical-research/v1', + runId: previewId, + backtestId: parent, + name: 'Frozen template name', + strategy: { + familyId: '66666666-6666-4666-8666-666666666666', + versionId, + origin: 'builtin', + reviewId: '88888888-8888-4888-8888-888888888888', + package: { + version: 1, + program: builtin.program, + parameterSchema: builtin.parameterSchema, + artifact: { + format: 'esm-bundle/v1', + entryExport: builtin.entryExport, + content: 'Never execute fixture code', + sha256: 'a'.repeat(64), + }, + dependencyLock: { + format: 'bun-lock/v1', + content: 'Retained lock', + sha256: 'b'.repeat(64), + }, + source: { revision: 'c'.repeat(40), dirty: false }, + build: { tool: 'bun', version: '1.2.17', target: 'browser' }, + }, + selection: { + strategyId: builtin.program.strategyId, + strategyVersion: builtin.program.strategyVersion, + ownerId: owner, + seed: 17, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: '100', + parameters: { fastPeriod: 2, slowPeriod: 20 }, + }, + }, + datasetHash: dataset.manifest.hash, + policy: config, + analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: '1.2.17', + platform: 'linux', + arch: 'x64', + }, + modelArtifacts: [], + }), + }; +} +function metrics(): NonNullable { + return { + totalReturn: 0, + cagr: null, + maxDrawdown: 0, + exposureTime: 0, + volatility: null, + downsideDeviation: null, + sharpeRatio: null, + sortinoRatio: null, + var95: null, + cvar95: null, + var99: null, + alpha: null, + beta: null, + informationRatio: null, + roundTripCount: null, + winRate: null, + profitFactor: null, + avgWin: null, + avgLoss: null, + }; +} +function detail( + source = preview(), + statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending') +): ExperimentDetail { + const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({ + ...item, + runId: statuses[index] === 'missing' ? null : runId(index), + attemptNumber: 0, + retryCount: 0, + status: statuses[index]!, + progress: statuses[index] === 'completed' ? 100 : 0, + cancelRequested: false, + error: statuses[index] === 'failed' ? 'Strategy callback failed' : null, + comparable: statuses[index] === 'completed', + diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null, + metrics: statuses[index] === 'completed' ? metrics() : null, + unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null, + limitations: [], + })); + return { + id: experimentId, + name: source.input.name, + backtestId: source.input.backtestId, + createdAt: '2026-10-24T14:00:00Z', + cancelRequested: false, + trialCount: trials.length, + counts: { + pending: 0, + running: 0, + paused: 0, + completed: 0, + failed: 0, + cancelled: 0, + ...Object.fromEntries( + ['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [ + status, + trials.filter(item => item.status === status).length, + ]) + ), + }, + datasetHash: source.request.datasetHash, + strategyVersionId: versionId, + previewHash: source.previewHash, + preview: source, + trials, + }; +} + +function failure(attemptNumber = 1, retryCount = 0) { + const value = detail(preview(2), ['failed', 'running']); + value.trials[0]!.attemptNumber = attemptNumber; + value.trials[0]!.retryCount = retryCount; + value.trials[0]!.progress = 43; + return value; +} +function transition(value: ExperimentDetail, index: number, change: Partial) { + const next = structuredClone(value); + Object.assign(next.trials[index]!, change); + if (change.status) { + next.trials[index]!.metrics = change.status === 'completed' ? metrics() : null; + next.trials[index]!.unavailable = change.status === 'completed' ? {} : null; + next.trials[index]!.comparable = change.status === 'completed'; + } + for (const status of [ + 'pending', + 'running', + 'paused', + 'completed', + 'failed', + 'cancelled', + ] as const) { + next.counts[status] = next.trials.filter(item => item.status === status).length; + } + return next; +} +function receipt(value: ExperimentDetail, index = 0): ExperimentTrialRetry { + const trial = value.trials[index]!; + return { + id: `99999999-9999-4999-8999-${String(trial.retryCount + 1).padStart(12, '0')}`, + experimentId: value.id, + runId: trial.runId!, + trialKey: trial.trialKey, + retryNumber: trial.retryCount + 1, + previousAttemptNumber: trial.attemptNumber, + previousAttemptId: null, + error: trial.error, + progress: trial.progress, + currentDate: null, + startedAt: null, + completedAt: '2026-10-24T14:00:00.123456Z', + pausedAt: null, + failureUpdatedAt: '2026-10-24T14:00:00.654321Z', + recordedAt: '2026-10-24T14:01:00.000001Z', + principal: 'operator', + reviewId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + }; +} +function accepted(value: ExperimentDetail) { + return { + retry: receipt(value), + experiment: transition(value, 0, { + status: 'pending', + retryCount: value.trials[0]!.retryCount + 1, + error: null, + progress: 0, + }), + }; +} +async function show(value: ExperimentDetail) { + root ??= createRoot(host); + await flush(() => + root!.render( + createElement( + router.MemoryRouter, + { initialEntries: [`/experiments/${value.id}`] }, + createElement( + router.Routes, + null, + createElement(router.Route, { + path: '/experiments/:experimentId', + element: createElement(ExperimentDetailPage), + }) + ), + createElement(Probe) + ) + ) + ); + await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value })); +} +async function start(value = failure()) { + await show(value); + await flush(() => button('Retry trial 1').click()); + return value; +} +async function send(value = failure()) { + await start(value); + await flush(() => button('Confirm retry trial 1').click()); + return request(retryPath(), 'POST'); +} +async function lose(post: Pending) { + await flush(() => { + post.settled = true; + post.reject(new Error('Response lost')); + }); +} +beforeAll(async () => { + for (const [key, value] of Object.entries({ + window: browser, + document: browser.document, + Event: browser.Event, + ResizeObserver: browser.ResizeObserver, + IS_REACT_ACT_ENVIRONMENT: true, + })) { + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + } + ({ createRoot } = await import('react-dom/client')); + router = await import('react-router-dom'); + ({ ExperimentDetailPage } = await import('../../apps/stock/web-app/src/features/experiments')); +}); +beforeEach(() => { + requests.length = 0; + location = ''; + host = browser.document.createElement('div') as unknown as HTMLDivElement; + browser.document.body.append(host as never); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + Object.defineProperty(browser, 'fetch', { + configurable: true, + value: (input: unknown, init?: RequestInit) => { + const url = new URL(String(input)); + const item: Pending = { + ...deferred(), + path: url.pathname + url.search, + method: init?.method ?? 'GET', + rawBody: init?.body, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + headers: new Headers(init?.headers), + signal: init?.signal, + credentials: init?.credentials, + settled: false, + }; + requests.push(item); + return item.promise; // Deliberately ignore abort to exercise stale-response fences. + }, + }); +}); +afterEach(async () => { + if (root) { + await flush(() => root!.unmount()); + } + root = undefined; + host.remove(); +}); +afterAll(async () => { + await browser.happyDOM.close(); + for (const key of keys) { + const old = originals.get(key); + if (old) { + Object.defineProperty(globalThis, key, old); + } else { + Reflect.deleteProperty(globalThis, key); + } + } +}); + +describe('exact failed-trial retry intent', () => { + test('review is explicit and duplicate confirmation admits only one exact-counter intent', async () => { + const value = await start(failure(3, 2)); + expect(host.textContent).toContain( + 'Reviewed failed attempt 3 · prior manual retries 2 · progress 43%' + ); + expect(host.textContent).toContain('Strategy callback failed'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + await flush(() => { + button('Confirm retry trial 1').click(); + button('Confirm retry trial 1').click(); + }); + const post = request(retryPath(), 'POST'); + expect(post.body).toEqual({ expectedAttemptNumber: 3, expectedRetryCount: 2 }); + expect(post.headers.get('Idempotency-Key')).toBeTruthy(); + expect(post.credentials).toBe('include'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(button('Refresh experiment').disabled).toBe(true); + expect(button('Cancel remaining trials').disabled).toBe(true); + await flush(() => reply(post, accepted(value), 202)); + expect(host.textContent).toContain('Retry 3 accepted for trial 1'); + expect(host.textContent).toContain('Attempt 3 · Manual retries 3'); + expect(host.textContent).not.toContain('Reviewed failed attempt'); + }); + test.each(['cancelled-experiment', 'cancelled-run', 'completed', 'missing'] as const)( + '%s cannot prepare a fresh retry', + async state => { + let value = failure(); + if (state === 'cancelled-experiment') { + value.cancelRequested = true; + } + if (state === 'cancelled-run') { + value.trials[0]!.cancelRequested = true; + } + if (state === 'completed') { + value = transition(value, 0, { status: 'completed' }); + } + if (state === 'missing') { + value = transition(value, 0, { + status: 'missing', + runId: null, + attemptNumber: 0, + retryCount: 0, + }); + } + await show(value); + expect(host.textContent).not.toContain('Retry trial 1'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + } + ); + test.each(['failed', 'completed', 'cancelled'] as const)( + 'ambiguous retry keeps exact body/key through refresh to newer %s state and accepts older receipt', + async status => { + const value = failure(0, 0); + const post = await send(value); + await lose(post); + const newer = transition(value, 0, { + status, + attemptNumber: 2, + retryCount: 2, + error: status === 'failed' ? 'Later failure' : null, + }); + if (status === 'cancelled') { + newer.cancelRequested = true; + newer.trials[0]!.cancelRequested = true; + } + await flush(() => button('Refresh experiment').click()); + expect(host.textContent).toContain('Acceptance is unconfirmed'); + await flush(() => + reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer }) + ); + expect(host.textContent).toContain('Reviewed failed attempt 0 · prior manual retries 0'); + expect(host.textContent).toContain('current trial state has changed'); + await flush(() => button('Retry same request for trial 1').click()); + const retry = request(retryPath(), 'POST'); + expect(retry.rawBody).toBe(post.rawBody); + expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key')); + await flush(() => reply(retry, { retry: receipt(value), experiment: newer }, 202)); + expect(host.textContent).toContain('Retry 1 accepted for trial 1'); + expect(host.textContent).not.toContain('Acceptance is unconfirmed'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(2); + if (status === 'failed') { + await flush(() => button('Retry trial 1').click()); + expect(host.textContent).toContain('Reviewed failed attempt 2 · prior manual retries 2'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(2); + await flush(() => button('Confirm retry trial 1').click()); + const fresh = request(retryPath(), 'POST'); + expect(fresh.body).toEqual({ expectedAttemptNumber: 2, expectedRetryCount: 2 }); + expect(fresh.headers.get('Idempotency-Key')).not.toBe(post.headers.get('Idempotency-Key')); + } + } + ); + test('failed detail refresh retains mounted retry intent and same-key recovery', async () => { + const value = failure(); + const post = await send(value); + await lose(post); + await flush(() => button('Refresh experiment').click()); + await flush(() => + reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Read unavailable' }, 500) + ); + expect(host.textContent).toContain('Showing the last loaded state'); + expect(host.textContent).toContain('Acceptance is unconfirmed'); + await flush(() => button('Retry same request for trial 1').click()); + const retry = request(retryPath(), 'POST'); + expect(retry.rawBody).toBe(post.rawBody); + expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key')); + await flush(() => reply(retry, accepted(value), 202)); + expect(host.textContent).toContain('Retry 1 accepted'); + }); + test.each([ + 'experiment', + 'run', + 'trial-key', + 'retry-number', + 'previous-attempt', + 'partial', + 'wrong-status', + ] as const)( + 'malformed %s acceptance keeps uncertain intent and never changes visible state', + async kind => { + const value = failure(2, 1); + const post = await send(value); + const result = accepted(value); + if (kind === 'experiment') { + result.retry.experimentId = otherExperimentId; + } + if (kind === 'run') { + result.retry.runId = runId(1); + } + if (kind === 'trial-key') { + result.retry.trialKey = 'f'.repeat(64); + } + if (kind === 'retry-number') { + result.retry.retryNumber = 3; + } + if (kind === 'previous-attempt') { + result.retry.previousAttemptNumber = 3; + } + await flush(() => + reply( + post, + kind === 'partial' + ? { retry: { id: result.retry.id }, experiment: result.experiment } + : result, + kind === 'wrong-status' ? 200 : 202 + ) + ); + expect(host.textContent).toContain('could not be verified'); + expect(host.textContent).toContain('Acceptance is unconfirmed'); + expect(host.textContent).not.toContain('Retry 2 accepted'); + expect(host.textContent).toContain('Attempt 2 · Manual retries 1'); + await flush(() => button('Retry same request for trial 1').click()); + const retry = request(retryPath(), 'POST'); + expect(retry.rawBody).toBe(post.rawBody); + expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key')); + } + ); + test.each([400, 401, 404, 409, 500])( + 'HTTP %s shows explicit failure with no automatic new intent', + async status => { + const post = await send(); + await flush(() => reply(post, { error: 'Retry admission refused' }, status)); + expect(host.textContent).toContain('Retry admission refused'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false }); + await flush(() => button('Discard retry request for trial 1').click()); + expect(host.textContent).toContain('Retry same request for trial 1'); + Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true }); + await flush(() => button('Discard retry request for trial 1').click()); + expect(host.textContent).not.toContain('Reviewed failed attempt'); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + } + ); + test('refresh changing a reviewed but unsubmitted failure requires deliberate fresh review', async () => { + const value = await start(failure(0, 1)); + const newer = transition(value, 0, { retryCount: 2, error: 'New preclaim failure' }); + await flush(() => button('Refresh experiment').click()); + await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer })); + expect(button('Confirm retry trial 1').disabled).toBe(true); + expect(host.textContent).toContain('Reviewed failed attempt 0 · prior manual retries 1'); + await flush(() => button('Discard retry request for trial 1').click()); + await flush(() => button('Retry trial 1').click()); + await flush(() => button('Confirm retry trial 1').click()); + expect(request(retryPath(), 'POST').body).toEqual({ + expectedAttemptNumber: 0, + expectedRetryCount: 2, + }); + }); +}); + +describe('retry coordination and navigation', () => { + test('an active detail refresh disables both retry and cancellation without discarding the review', async () => { + const value = await start(); + await flush(() => button('Refresh experiment').click()); + expect(button('Confirm retry trial 1').disabled).toBe(true); + expect(button('Cancel remaining trials').disabled).toBe(true); + await flush(() => { + button('Confirm retry trial 1').click(); + button('Cancel remaining trials').click(); + }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(0); + await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value })); + expect(host.textContent).toContain('Reviewed failed attempt 1'); + await flush(() => button('Confirm retry trial 1').click()); + await flush(() => reply(request(retryPath(), 'POST'), accepted(value), 202)); + expect(host.textContent).toContain('Retry 1 accepted'); + }); + test('cancel and retry share one synchronous mutation gate', async () => { + await start(); + await flush(() => { + button('Cancel remaining trials').click(); + button('Confirm retry trial 1').click(); + }); + expect(requests.filter(item => item.method === 'POST')).toHaveLength(1); + expect(requests.find(item => item.method === 'POST')!.path).toBe( + `/api/v2/experiments/${experimentId}/cancel` + ); + expect(button('Confirm retry trial 1').disabled).toBe(true); + }); + test('ambiguous intent survives explicit cancellation and receipt replay afterward', async () => { + const value = failure(); + const post = await send(value); + await lose(post); + await flush(() => button('Cancel remaining trials').click()); + let cancelled = transition(value, 0, { + status: 'cancelled', + retryCount: 1, + cancelRequested: true, + }); + cancelled = transition(cancelled, 1, { status: 'cancelled', cancelRequested: true }); + cancelled.cancelRequested = true; + await flush(() => + reply(request(`/api/v2/experiments/${experimentId}/cancel`, 'POST'), { + experiment: cancelled, + }) + ); + expect(host.textContent).toContain('Acceptance is unconfirmed'); + await flush(() => button('Retry same request for trial 1').click()); + const retry = request(retryPath(), 'POST'); + expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key')); + await flush(() => reply(retry, { retry: receipt(value), experiment: cancelled }, 202)); + expect(host.textContent).toContain('Retry 1 accepted'); + expect(host.textContent).toContain('cancelled: 2'); + }); + test('owned navigation warns before discarding an uncertain request and refusal preserves its key', async () => { + const post = await send(); + await lose(post); + let prompts = 0; + Object.defineProperty(browser, 'confirm', { + configurable: true, + value: () => { + prompts++; + return false; + }, + }); + await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click()); + await flush(() => + ( + host.querySelector( + `a[href="/backtests/${backtestId}/run/${runId(0)}"]` + ) as HTMLAnchorElement + ).click() + ); + expect(prompts).toBe(2); + expect(location).toBe(`/experiments/${experimentId}`); + await flush(() => button('Retry same request for trial 1').click()); + expect(request(retryPath(), 'POST').headers.get('Idempotency-Key')).toBe( + post.headers.get('Idempotency-Key') + ); + }); + test('late retry success and old detail completion cannot overwrite another route', async () => { + const value = failure(); + const post = await send(value); + await flush(() => navigate(`/experiments/${otherExperimentId}`)); + const otherRead = request(`/api/v2/experiments/${otherExperimentId}`); + const other = failure(); + other.id = otherExperimentId; + other.name = 'Other experiment'; + other.preview.input.name = other.name; + await flush(() => reply(otherRead, { experiment: other })); + await flush(() => reply(post, accepted(value), 202)); + expect(host.querySelector('h1')!.textContent).toBe('Other experiment'); + expect(host.textContent).not.toContain('Retry 1 accepted'); + await flush(() => button('Refresh experiment').click()); + const oldRead = request(`/api/v2/experiments/${otherExperimentId}`); + await flush(() => navigate(`/experiments/${experimentId}`)); + await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value })); + await flush(() => reply(oldRead, { experiment: other })); + expect(host.querySelector('h1')!.textContent).toBe('Trend study'); + }); + test('refresh and confirmation in one event cannot install a stale read over accepted retry state', async () => { + const value = await start(); + await flush(() => { + button('Refresh experiment').click(); + button('Confirm retry trial 1').click(); + }); + const post = request(retryPath(), 'POST'); + await flush(() => reply(post, accepted(value), 202)); + expect(host.textContent).toContain('Retry 1 accepted'); + expect(host.textContent).toContain('Attempt 1 · Manual retries 1'); + expect(host.textContent).not.toContain('Loading experiment...'); + }); +}); + +describe('immutable retry failure history', () => { + test('a later retry count refresh fences an older history read without losing its newer snapshot', async () => { + const value = failure(); + await show(value); + await flush(() => button('Show retry history for trial 1').click()); + const old = request(historyPath()); + await flush(() => button('Refresh experiment').click()); + const newer = transition(value, 0, { retryCount: 1, attemptNumber: 2, error: 'Later failure' }); + await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer })); + const current = requests.filter(item => item.path === historyPath() && !item.settled).at(-1)!; + expect(current).not.toBe(old); + await flush(() => reply(current, { retries: [receipt(value)] })); + await flush(() => reply(old, { retries: [] })); + expect(host.textContent).toContain('Retry 1 · previous attempt 1'); + expect(host.textContent).not.toContain('No accepted manual retries'); + }); + test('history is lazy and renders empty/loading states then exact nullable failure snapshots', async () => { + const value = failure(0, 0); + value.trials[0]!.error = null; + await show(value); + expect(requests.some(item => item.path.endsWith('/retries'))).toBe(false); + await flush(() => button('Show retry history for trial 1').click()); + expect(host.textContent).toContain('Loading retry history for trial 1'); + await flush(() => reply(request(historyPath()), { retries: [] })); + expect(host.textContent).toContain('No accepted manual retries for this trial'); + await flush(() => button('Refresh retry history for trial 1').click()); + const saved = receipt(value); + await flush(() => reply(request(historyPath()), { retries: [saved] })); + expect(host.textContent).toContain('Retry 1 · previous attempt 0'); + expect(host.textContent).toContain('No error was recorded for this failure'); + expect(host.textContent).toContain('No attempt ID was recorded'); + expect(host.textContent).toContain(saved.failureUpdatedAt); + expect(host.textContent).toContain(saved.completedAt!); + expect(host.textContent).toContain(saved.recordedAt); + expect(host.textContent).toContain(saved.reviewId); + expect(host.textContent).toContain('not a complete history of automatic recovery attempts'); + }); + test.each(['partial', 'foreign', 'unordered', 'duplicate', 'http'] as const)( + '%s history is an error, never a false empty/success state, and explicit refresh recovers', + async kind => { + const value = failure(); + await show(value); + await flush(() => button('Show retry history for trial 1').click()); + const saved = receipt(value); + const bad = structuredClone(saved); + if (kind === 'foreign') { + bad.runId = runId(1); + } + if (kind === 'unordered') { + bad.retryNumber = 2; + } + const rows = + kind === 'partial' ? [{ id: saved.id }] : kind === 'duplicate' ? [saved, saved] : [bad]; + await flush(() => + reply( + request(historyPath()), + kind === 'http' ? { error: 'History unavailable' } : { retries: rows }, + kind === 'http' ? 500 : 200 + ) + ); + expect( + host.querySelector('[aria-label="Retry history for trial 1"] [role="alert"]') + ).not.toBeNull(); + expect(host.textContent).not.toContain('No accepted manual retries'); + expect(host.textContent).not.toContain('Retry 1 · previous attempt'); + await flush(() => button('Refresh retry history for trial 1').click()); + await flush(() => reply(request(historyPath()), { retries: [saved] })); + expect(host.textContent).toContain('Retry 1 · previous attempt 1'); + } + ); + test('hide/reopen fences a delayed history response and a successful retry refreshes open history', async () => { + const value = await start(); + await flush(() => button('Show retry history for trial 1').click()); + const old = request(historyPath()); + await flush(() => button('Hide retry history for trial 1').click()); + await flush(() => button('Show retry history for trial 1').click()); + const current = requests.filter(item => item.path === historyPath() && !item.settled).at(-1)!; + await flush(() => reply(current, { retries: [] })); + await flush(() => reply(old, { error: 'Old failure' }, 500)); + expect(host.textContent).toContain('No accepted manual retries'); + expect(host.textContent).not.toContain('Old failure'); + await flush(() => button('Confirm retry trial 1').click()); + await flush(() => reply(request(retryPath(), 'POST'), accepted(value), 202)); + expect(host.textContent).toContain('Loading retry history for trial 1'); + await flush(() => reply(request(historyPath()), { retries: [receipt(value)] })); + expect(host.textContent).toContain('Retry 1 · previous attempt 1'); + }); + test('late history response cannot appear in another selected experiment', async () => { + const value = failure(); + await show(value); + await flush(() => button('Show retry history for trial 1').click()); + const old = request(historyPath()); + await flush(() => navigate(`/experiments/${otherExperimentId}`)); + const other = failure(); + other.id = otherExperimentId; + await flush(() => + reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other }) + ); + await flush(() => reply(old, { retries: [receipt(value)] })); + expect(host.querySelector('[aria-label="Retry history for trial 1"]')).toBeNull(); + expect(host.textContent).not.toContain('Retry 1 · previous attempt 1'); + }); +}); diff --git a/test/integration/experiments-api.test.ts b/test/integration/experiments-api.test.ts index f747a6f1..d2f5ff70 100644 --- a/test/integration/experiments-api.test.ts +++ b/test/integration/experiments-api.test.ts @@ -272,6 +272,8 @@ describe('experiment HTTP contract', () => { status: index === 0 ? 'completed' : 'failed', progress: index === 0 ? 100 : 50, cancel_requested: false, + attempt_number: 1, + manual_retry_count: 0, error: index === 1 ? 'failure' : null, dataset_hash: preview.request.datasetHash, request_snapshot: experimentTrialRequest(preview, candidate, id), diff --git a/test/integration/experiments-ui.test.tsx b/test/integration/experiments-ui.test.tsx index b974b621..60360056 100644 --- a/test/integration/experiments-ui.test.tsx +++ b/test/integration/experiments-ui.test.tsx @@ -239,6 +239,8 @@ function detail( const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({ ...item, runId: statuses[index] === 'missing' ? null : runId(index), + attemptNumber: 0, + retryCount: 0, status: statuses[index]!, progress: statuses[index] === 'completed' ? 100 : 0, cancelRequested: false, diff --git a/test/postgres/canonical-durable-backtest.test.ts b/test/postgres/canonical-durable-backtest.test.ts index 67e5d3e7..63296da1 100644 --- a/test/postgres/canonical-durable-backtest.test.ts +++ b/test/postgres/canonical-durable-backtest.test.ts @@ -64,6 +64,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/canonical-research.test.ts b/test/postgres/canonical-research.test.ts index abd4223a..fed79226 100644 --- a/test/postgres/canonical-research.test.ts +++ b/test/postgres/canonical-research.test.ts @@ -63,6 +63,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/catalog-backtest-drafts.test.ts b/test/postgres/catalog-backtest-drafts.test.ts index 311a5f15..e9611824 100644 --- a/test/postgres/catalog-backtest-drafts.test.ts +++ b/test/postgres/catalog-backtest-drafts.test.ts @@ -102,6 +102,7 @@ async function fixture() { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/dataset-catalog.test.ts b/test/postgres/dataset-catalog.test.ts index f321e77c..06024ae6 100644 --- a/test/postgres/dataset-catalog.test.ts +++ b/test/postgres/dataset-catalog.test.ts @@ -75,6 +75,7 @@ async function fixture() { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 62cb58b9..2cf1a2d9 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -86,6 +86,7 @@ async function fixture() { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/experiment-retries.test.ts b/test/postgres/experiment-retries.test.ts new file mode 100644 index 00000000..42b960ad --- /dev/null +++ b/test/postgres/experiment-retries.test.ts @@ -0,0 +1,837 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { HandlerRegistry } from '@stock-bot/handler-registry'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { Queue } from '@stock-bot/queue'; +import type { + CanonicalRunRequest, + CanonicalRunResult, +} from '@stock-bot/stock-config/canonical-research'; +import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; +import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; +import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; +import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; +import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; +import { + experimentHash, + experimentTrialRequest, +} from '../../apps/stock/web-api/src/services/experiment-input'; +import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service'; +import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; +import { retainResearchDataset } from '../../scripts/import-research-dataset'; +import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies'; +import { canonicalSettings } from '../fixtures/canonical-research'; +import { canonicalSmaFixture } from '../fixtures/canonical-sma'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('experiment-retries'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +let packages: ReturnType | undefined; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); +async function fixture(poolMax = 4, withRetries = true) { + const dataset = canonicalSmaFixture().dataset; + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Disposable safety database required'); + } + const schema = 'stock_bot_safety_retries_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + application_name: schema, + max: poolMax, + options: `-c search_path=${schema} -c statement_timeout=10000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + for (const name of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '12-historical-datasets.sql', + '14-backtest-submission.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + ...(withRetries ? ['23-experiment-retries.sql'] : []), + ]) { + await pool.query( + readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') + ); + } + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); + const container = { postgres, logger }; + const api = new BacktestServiceV2(container); + const experiments = new ExperimentsService(container); + const repository = new PostgresBacktestRunRepository(postgres); + const catalog = new StrategyCatalogService(container); + const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!; + const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed'); + await retainResearchDataset(pool, dataset); + const definition = { + name: 'Canonical API', + strategy: 'catalog', + strategyVersionId: version.id, + strategyParameters: { fastPeriod: 2, slowPeriod: 3 }, + symbols: dataset.manifest.executionSeries.map(s => s.instrumentId), + startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(), + endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(), + initialCapital: 10000, + config: { + datasetHash: dataset.manifest.hash, + dataFrequency: dataset.manifest.series[0]!.interval, + canonical: canonicalSettings, + }, + }; + const draft = await api.createBacktest(definition, { autoStart: false }); + const approve = async () => { + await catalog.reviewVersion( + version.id, + { decision: 'approve', reason: 'Reviewed retained builtin' }, + 'operator' + ); + return (await catalog.getVersionReviews(version.id)).at(-1)!; + }; + const execute = async (id: string) => { + const engine = new RustBacktestAdapter({ + logger, + storage: { + async getHistoricalBars() { + throw new Error('Canonical execution must never load provider data'); + }, + }, + }); + const runner = new BacktestRunner({ + engine, + engineName: 'native', + repository: new PostgresBacktestRunRepository(postgres), + logger, + }); + try { + await runner.runQueued(id); + } finally { + await runner.shutdown(); + } + }; + return { + pool, + postgres, + schema, + api, + experiments, + repository, + catalog, + pkg, + version, + draft, + definition, + dataset, + approve, + execute, + }; +} + +const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key }); +type Fixture = Awaited>; +async function prepare(f: Fixture) { + await f.approve(); + const input = { backtestId: f.draft.id, name: 'Retry fixture', grid: {} }; + const preview = await f.experiments.preview(input); + const experiment = await f.experiments.submit( + { ...input, previewHash: preview.previewHash }, + receipt() + ); + const runId = experiment.trials[0]!.runId!; + const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])) + .rows[0].request_snapshot as CanonicalRunRequest; + return { experiment, runId, request }; +} +async function row(f: Fixture, id: string) { + return (await f.pool.query('SELECT to_jsonb(r) AS value FROM runs r WHERE id=$1', [id])).rows[0] + .value; +} +async function failBeforeClaim( + f: Fixture, + id: string, + error: string | null = 'Preclaim diagnostic' +) { + await f.pool.query( + "UPDATE runs SET status='failed',error=$2,completed_at=clock_timestamp() WHERE id=$1", + [id, error] + ); +} +async function nativeResult(f: Fixture, request: CanonicalRunRequest): Promise { + const engine = new RustBacktestAdapter({ + logger, + storage: { + async getHistoricalBars() { + throw new Error('Provider access forbidden'); + }, + }, + }); + try { + return { + kind: 'canonical-result/v1', + runId: request.runId, + backtestId: request.backtestId, + status: 'completed', + completedAt: new Date().toISOString(), + executionTime: 0, + financialEngine: 'rust', + strategyExecution: 'typescript-retained-builtin/v1', + request, + ...(await engine.runCanonical(request, async () => f.dataset)), + }; + } finally { + await engine.shutdown(); + } +} +async function snapshotCounts(f: Fixture) { + return ( + await f.pool.query(`SELECT (SELECT count(*)::int FROM experiment_trial_retries) AS retries, + (SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_results) AS results,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`) + ).rows[0]; +} +const observed = (attempt = 0, retry = 0) => ({ + expectedAttemptNumber: attempt, + expectedRetryCount: retry, +}); +async function rawReceipt( + f: Fixture, + runId: string, + reviewId: string, + changes: Record = {} +) { + const retryId = randomUUID(); + return f.pool.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,COALESCE($4::uuid,experiment_id),id,trial_key,COALESCE($5::int,manual_retry_count+1),attempt_number,attempt_id, + CASE WHEN $6::text IS NULL THEN error ELSE $6::text END,progress,current_simulation_date,started_at,completed_at,paused_at, + ${changes.roundTime ? "date_trunc('milliseconds',updated_at)" : 'updated_at'},'operator',$3,$7,$8 + FROM runs WHERE id=$2 RETURNING id`, + [ + retryId, + runId, + reviewId, + changes.experiment ?? null, + changes.retryNumber ?? null, + changes.error ?? null, + randomUUID(), + 'a'.repeat(64), + ] + ); +} + +describe.skipIf(!url)('guarded failed experiment trial retry', () => { + test('failed worker retry retains exact failure timestamps and frozen identity, fences every stale callback, and completes once in real Rust', async () => { + const f = await fixture(1), + { experiment, runId, request } = await prepare(f); + const claim = await f.repository.startCanonical(request); + await f.repository.updateProgress(runId, 37.25, '2024-01-01T09:03:00.123Z', claim.attemptId); + await f.pool.query( + "UPDATE runs SET started_at='2026-10-24T10:00:00.123456Z',paused_at='2026-10-24T10:01:00.654321Z' WHERE id=$1", + [runId] + ); + const result = await nativeResult(f, request); + await f.repository.fail(runId, 'Observed failure after computation', claim.attemptId); + await expect( + f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [runId]) + ).rejects.toMatchObject({ code: '23514' }); + const before = await row(f, runId), + key = receipt(); + const latest = await f.approve(); + expect(latest.id).not.toBe(request.strategy.reviewId); + const retried = await f.experiments.retryTrial(experiment.id, runId, observed(1), key); + expect(retried.retry).toMatchObject({ + runId, + experimentId: experiment.id, + retryNumber: 1, + previousAttemptNumber: 1, + previousAttemptId: claim.attemptId, + error: before.error, + progress: 37.25, + reviewId: latest.id, + }); + expect(retried.retry.startedAt).toBe('2026-10-24T10:00:00.123456Z'); + expect(retried.retry.pausedAt).toBe('2026-10-24T10:01:00.654321Z'); + const exact = ( + await f.pool.query( + `SELECT h.started_at=($2::jsonb->>'started_at')::timestamptz AND h.paused_at=($2::jsonb->>'paused_at')::timestamptz + AND h.completed_at=($2::jsonb->>'completed_at')::timestamptz AND h.failure_updated_at=($2::jsonb->>'updated_at')::timestamptz AS exact + FROM experiment_trial_retries h WHERE run_id=$1`, + [runId, before] + ) + ).rows[0]; + expect(exact.exact).toBe(true); + const pending = await row(f, runId); + expect(pending).toMatchObject({ + status: 'pending', + attempt_number: 1, + manual_retry_count: 1, + attempt_id: null, + lease_expires_at: null, + progress: 0, + error: null, + current_simulation_date: null, + started_at: null, + completed_at: null, + paused_at: null, + request_snapshot: request, + dataset_hash: request.datasetHash, + }); + expect(pending.request_snapshot.strategy.reviewId).toBe(request.strategy.reviewId); + const assertStale = async () => { + const current = await row(f, runId); + await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow(); + await expect( + f.repository.updateProgress(runId, 99, undefined, claim.attemptId) + ).rejects.toThrow(); + await f.repository.fail(runId, 'Stale overwrite', claim.attemptId); + await expect(f.repository.cancel(runId, claim.attemptId)).rejects.toThrow(); + await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toThrow(); + expect(await row(f, runId)).toEqual(current); + }; + await assertStale(); + const next = await f.repository.startCanonical(request); + expect(next.attemptId).not.toBe(claim.attemptId); + await assertStale(); + await f.repository.completeCanonical(result, next.attemptId); + expect((await f.api.getRunResults(runId))!.runId).toBe(runId); + expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 }); + expect((await f.experiments.get(experiment.id)).trials[0]).toMatchObject({ + attemptNumber: 2, + retryCount: 1, + status: 'completed', + comparable: true, + }); + expect((await f.experiments.retryTrial(experiment.id, runId, observed(1), key)).retry).toEqual( + retried.retry + ); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(2, 1), receipt()) + ).rejects.toMatchObject({ status: 409 }); + expect(await f.experiments.listTrialRetries(experiment.id, runId)).toEqual([retried.retry]); + }); + + test('preclaim failure0 can recur; both counters prevent stale intent and null prior identifiers stay honest', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId, null); + const key = receipt(), + first = await f.experiments.retryTrial(experiment.id, runId, observed(), key); + expect(first.retry).toMatchObject({ + previousAttemptNumber: 0, + previousAttemptId: null, + error: null, + retryNumber: 1, + startedAt: null, + pausedAt: null, + currentDate: null, + }); + await failBeforeClaim(f, runId, 'second preclaim failure'); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) + ).rejects.toMatchObject({ status: 409 }); + expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( + first.retry + ); + const second = await f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()); + expect(second.retry).toMatchObject({ + retryNumber: 2, + previousAttemptNumber: 0, + previousAttemptId: null, + error: 'second preclaim failure', + }); + expect( + (await f.experiments.listTrialRetries(experiment.id, runId)).map(h => h.retryNumber) + ).toEqual([1, 2]); + expect((await row(f, runId)).attempt_number).toBe(0); + }); + + test('same-key race replays one receipt; different keys or cross-experiment reuse cannot reset twice', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId); + const key = receipt(); + const [a, b] = await Promise.all([ + f.experiments.retryTrial(experiment.id, runId, observed(), key), + f.experiments.retryTrial(experiment.id, runId, observed(), key), + ]); + expect(a.retry.id).toBe(b.retry.id); + await failBeforeClaim(f, runId); + const race = await Promise.allSettled([ + f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()), + f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()), + ]); + expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1); + expect( + race.filter(r => r.status === 'rejected').map(r => (r as PromiseRejectedResult).reason.status) + ).toEqual([409]); + await expect( + f.experiments.retryTrial(randomUUID(), runId, observed(), key) + ).rejects.toMatchObject({ status: 409 }); + expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 0, retries: 2, dispatch: 1 }); + const secondParent = await f.api.createBacktest( + { ...f.definition, name: 'Second retry parent' }, + { autoStart: false } + ); + const secondInput = { backtestId: secondParent.id, name: 'Other parent experiment', grid: {} }; + const secondPreview = await f.experiments.preview(secondInput); + const secondExperiment = await f.experiments.submit( + { ...secondInput, previewHash: secondPreview.previewHash }, + receipt() + ); + const secondRunId = secondExperiment.trials[0]!.runId!; + await failBeforeClaim(f, runId); + await failBeforeClaim(f, secondRunId); + const crossKey = receipt(); + const cross = await Promise.allSettled([ + f.experiments.retryTrial(experiment.id, runId, observed(0, 2), crossKey), + f.experiments.retryTrial(secondExperiment.id, secondRunId, observed(), crossKey), + ]); + expect(cross.filter(item => item.status === 'fulfilled')).toHaveLength(1); + expect( + cross + .filter(item => item.status === 'rejected') + .map(item => (item as PromiseRejectedResult).reason.status) + ).toEqual([409]); + expect(await snapshotCounts(f)).toEqual({ runs: 2, results: 0, retries: 3, dispatch: 2 }); + }); + + test('latest original-version approval governs retries despite template edits; accepted receipts survive revocation/archive/cancellation', async () => { + const f = await fixture(), + { experiment, runId, request } = await prepare(f); + await failBeforeClaim(f, runId); + const other = (await (packages ??= packageBuiltinStrategies()))[1]!; + const version = await f.catalog.seedBuiltin('Different template version', other, 'seed-other'); + await f.api.updateBacktest(f.draft.id, { + name: 'Different template', + strategyVersionId: version.id, + strategyParameters: { + lookbackPeriod: 2, + trendPeriod: 3, + momentumPeriod: 1, + volatilityPeriod: 2, + entryZScore: 1, + exitZScore: 0.1, + minTrendReturn: -0.5, + minMomentumReturn: -0.5, + maxVolatility: 1, + minNotionalVolume: '0', + regimeFilter: 'none', + }, + initialCapital: 20000, + }); + await f.catalog.reviewVersion( + f.version.id, + { decision: 'revoke', reason: 'No new execution' }, + 'operator' + ); + const before = await row(f, runId); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) + ).rejects.toMatchObject({ status: 409 }); + expect(await row(f, runId)).toEqual(before); + const latest = await f.approve(), + key = receipt(); + const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key); + expect(accepted.retry.reviewId).toBe(latest.id); + expect((await row(f, runId)).request_snapshot).toEqual(request); + await f.catalog.reviewVersion( + f.version.id, + { decision: 'revoke', reason: 'Pause' }, + 'operator' + ); + await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]); + await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + await f.experiments.cancel(experiment.id); + expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( + accepted.retry + ); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()) + ).rejects.toMatchObject({ status: 409 }); + }); + + test('outbox fault rolls back history and reset; due redispatch survives publication outage without resetting lifetime attempt budget', async () => { + const f = await fixture(), + { experiment, runId, request } = await prepare(f); + const claim = await f.repository.startCanonical(request); + await f.repository.fail(runId, 'worker failure', claim.attemptId); + await f.pool.query( + "UPDATE backtest_dispatch SET publish_count=9,last_published_at='2026-10-24T10:00:00.123456Z',next_publish_at=NOW()+interval '1 day' WHERE run_id=$1", + [runId] + ); + await f.pool + .query(`CREATE FUNCTION reject_retry_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture outage'; END $$; + CREATE TRIGGER fixture_dispatch_outage BEFORE UPDATE ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_retry_dispatch()`); + const before = await row(f, runId), + key = receipt(); + await expect(f.experiments.retryTrial(experiment.id, runId, observed(1), key)).rejects.toThrow( + 'fixture outage' + ); + expect(await row(f, runId)).toEqual(before); + expect((await snapshotCounts(f)).retries).toBe(0); + await f.pool.query('DROP TRIGGER fixture_dispatch_outage ON backtest_dispatch'); + await f.experiments.retryTrial(experiment.id, runId, observed(1), key); + const dispatch = ( + await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId]) + ).rows[0]; + expect(dispatch.publish_count).toBe(9); + expect(dispatch.last_published_at.toISOString()).toBe('2026-10-24T10:00:00.123Z'); + let failed = true; + const delivered: string[] = []; + const dispatcher = new BacktestDispatcher( + f.postgres, + { + async add(_name: string, data: unknown) { + if (failed) { + throw new Error('Redis unavailable'); + } + delivered.push((data as { payload: { runId: string } }).payload.runId); + return {}; + }, + } as never, + logger, + { intervalMs: 20, republishMs: 5, maxAttempts: 1 } + ); + await expect(dispatcher.tick()).rejects.toThrow('Redis unavailable'); + expect((await row(f, runId)).status).toBe('pending'); + failed = false; + await new Promise(resolve => setTimeout(resolve, 10)); + await dispatcher.tick(); + expect(delivered).toEqual([runId]); + const next = await f.repository.startCanonical(request); + expect((await row(f, runId)).attempt_number).toBe(2); + await f.pool.query("UPDATE runs SET lease_expires_at=NOW()-interval '1 second' WHERE id=$1", [ + runId, + ]); + await dispatcher.tick(); + expect(await row(f, runId)).toMatchObject({ + status: 'failed', + attempt_number: 2, + manual_retry_count: 1, + attempt_id: null, + error: 'Execution lease expired; retry limit reached', + }); + await expect(f.repository.heartbeat(runId, next.attemptId)).rejects.toThrow(); + await dispatcher.shutdown(); + }); + + test('SQL rejects missing receipts, altered or rounded snapshots, history tampering, count changes and incomplete resets', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId); + const review = (await f.catalog.getVersionReviews(f.version.id)).at(-1)!; + const original = await row(f, runId); + for (const patch of ["status='pending'", "status='running'", 'manual_retry_count=1']) { + await expect( + f.pool.query(`UPDATE runs SET ${patch} WHERE id=$1`, [runId]) + ).rejects.toMatchObject({ code: '23514' }); + } + for (const changes of [ + { error: 'invented failure' }, + { retryNumber: 2 }, + { experiment: randomUUID() }, + { roundTime: true }, + {}, + ]) { + await expect(rawReceipt(f, runId, review.id, changes)).rejects.toMatchObject({ + code: '23514', + }); + } + expect(await row(f, runId)).toEqual(original); + const client = await f.pool.connect(); + try { + await client.query('BEGIN'); + // Use the SQL capture itself, then prove a partial reset cannot consume the receipt. + 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,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,'operator',$3,$4,$5 FROM runs WHERE id=$2`, + [randomUUID(), runId, review.id, randomUUID(), 'a'.repeat(64)] + ); + await expect( + client.query("UPDATE runs SET status='pending',manual_retry_count=1 WHERE id=$1", [runId]) + ).rejects.toMatchObject({ code: '23514' }); + } finally { + await client.query('ROLLBACK'); + client.release(); + } + const retry = await f.experiments.retryTrial(experiment.id, runId, observed(), receipt()); + for (const sql of [ + "UPDATE experiment_trial_retries SET error='changed' WHERE id=$1", + 'DELETE FROM experiment_trial_retries WHERE id=$1', + ]) { + await expect(f.pool.query(sql, [retry.retry.id])).rejects.toMatchObject({ code: '23514' }); + } + await expect(f.pool.query('TRUNCATE experiment_trial_retries')).rejects.toMatchObject({ + code: '23514', + }); + await expect( + f.pool.query('UPDATE runs SET manual_retry_count=0 WHERE id=$1', [runId]) + ).rejects.toMatchObject({ code: '23514' }); + expect((await snapshotCounts(f)).retries).toBe(1); + }); + + test('cancellation race either rejects retry or cancels its reset run; wrong membership/results/current terminal states reject', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(), receipt()) + ).rejects.toMatchObject({ status: 409 }); + await expect( + f.experiments.retryTrial(experiment.id, randomUUID(), observed(), receipt()) + ).rejects.toMatchObject({ status: 404 }); + const ordinary = await f.api.createRun({ backtestId: f.draft.id }); + await expect( + f.experiments.retryTrial(experiment.id, ordinary.id, observed(), receipt()) + ).rejects.toMatchObject({ status: 409 }); + await expect(f.experiments.listTrialRetries(experiment.id, ordinary.id)).rejects.toMatchObject({ + status: 409, + }); + await failBeforeClaim(f, runId); + await Promise.allSettled([ + f.experiments.retryTrial(experiment.id, runId, observed(), receipt()), + f.experiments.cancel(experiment.id), + ]); + const current = await row(f, runId); + expect(current.status === 'failed' || current.status === 'cancelled').toBe(true); + expect((await f.experiments.get(experiment.id)).cancelRequested).toBe(true); + await expect( + f.experiments.retryTrial( + experiment.id, + runId, + observed(0, current.manual_retry_count), + receipt() + ) + ).rejects.toMatchObject({ status: 409 }); + const completed = await prepare(f); + await f.execute(completed.runId); + // Deliberate corruption in this disposable schema proves retained results still forbid retry. + await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [completed.runId]); + await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); + const evidence = await row(f, completed.runId); + await expect( + f.experiments.retryTrial(completed.experiment.id, completed.runId, observed(1), receipt()) + ).rejects.toMatchObject({ status: 409 }); + expect(await row(f, completed.runId)).toEqual(evidence); + await expect( + f.pool.query("UPDATE runs SET status='pending' WHERE id=$1", [completed.runId]) + ).rejects.toMatchObject({ code: '23514' }); + }); + test('real Redis publication outage recovers the same retried run and real Rust result once', async () => { + const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; + if (!redisUrl || new URL(redisUrl).pathname !== '/15') { + throw new Error('Dedicated Redis database15 required'); + } + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId); + await f.experiments.retryTrial(experiment.id, runId, observed(), receipt()); + const endpoint = new URL(redisUrl), + redis = { host: endpoint.hostname, port: Number(endpoint.port), db: 15 }; + const name = `stock-bot-safety-retry-${randomUUID()}`; + const producer = new Queue(name, redis, {}, { workers: 0 }, logger); + await producer.getBullQueue().waitUntilReady(); + cleanup.push(async () => { + await producer.getBullQueue().obliterate({ force: true }); + await producer.close(); + }); + const dispatcher = new BacktestDispatcher(f.postgres, producer, logger, { + intervalMs: 20, + republishMs: 30, + maxAttempts: 3, + }); + cleanup.push(() => dispatcher.shutdown()); + const connection = await producer.getBullQueue().client; + connection.disconnect(); + await expect(dispatcher.tick()).rejects.toThrow(); + expect((await row(f, runId)).status).toBe('pending'); + await connection.connect(); + await new Promise(resolve => setTimeout(resolve, 40)); + await dispatcher.tick(); + const registry = new HandlerRegistry(); + registry.registerConfiguration({ + name: 'orchestrator', + operations: { + 'run-backtest': async payload => f.execute((payload as { runId: string }).runId), + }, + }); + const worker = new Queue( + name, + redis, + {}, + { workers: 1, concurrency: 1, handlerRegistry: registry }, + logger + ); + cleanup.push(() => worker.close()); + let done = false; + for (let i = 0; i < 150; i++) { + if ((await row(f, runId)).status === 'completed') { + done = true; + break; + } + await new Promise(resolve => setTimeout(resolve, 20)); + } + expect(done).toBe(true); + expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 }); + await f.execute(runId); // Repeat delivery is harmless after completion. + expect((await snapshotCounts(f)).results).toBe(1); + expect((await row(f, runId)).attempt_number).toBe(1); + }); + + test('first SQL23 upgrade preserves old failed experiment evidence with count0 and no invented history; reapplication preserves accepted retry', async () => { + const f = await fixture(4, false); + await f.approve(); + const input = { backtestId: f.draft.id, name: 'Pre-migration experiment', grid: {} }; + const preview = await f.experiments.preview(input), + experimentId = randomUUID(), + runId = randomUUID(); + const candidate = preview.candidates[0]!, + request = experimentTrialRequest(preview, candidate, runId); + await f.pool.query( + `INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) + VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`, + [ + experimentId, + f.draft.id, + input.name, + preview, + preview.previewHash, + randomUUID(), + 'a'.repeat(64), + ] + ); + await f.pool.query( + `INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index) + VALUES($1,$2,1,'pending',NULL,$3,$4,$5,$6,0)`, + [runId, f.draft.id, request, request.datasetHash, experimentId, candidate.trialKey] + ); + await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]); + await failBeforeClaim(f, runId); + const before = await row(f, runId), + outbox = (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows; + const sql = readFileSync( + new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url), + 'utf8' + ); + await f.pool.query(sql); + expect(await row(f, runId)).toEqual({ ...before, manual_retry_count: 0 }); + expect( + (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows + ).toEqual(outbox); + expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([]); + const accepted = await f.experiments.retryTrial(experimentId, runId, observed(), receipt()); + const after = await row(f, runId); + await f.pool.query(sql); + expect(await row(f, runId)).toEqual(after); + expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([accepted.retry]); + await f.execute(runId); + expect((await f.experiments.get(experimentId)).trials[0]).toMatchObject({ + status: 'completed', + attemptNumber: 1, + retryCount: 1, + }); + }); + test('current-family archive serializes fresh retry and leaves the prior failure intact', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId); + const before = await row(f, runId); + const blocker = await f.pool.connect(); + let pending: Promise | undefined; + try { + await blocker.query('BEGIN'); + await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [ + f.version.strategyId, + ]); + pending = f.experiments.retryTrial(experiment.id, runId, observed(), receipt()).then( + value => ({ value }), + error => ({ error }) + ); + let waiting = false; + for (let i = 0; i < 100; i++) { + if ( + ( + await f.pool.query( + "SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", + [f.schema] + ) + ).rows.length + ) { + waiting = true; + break; + } + await new Promise(resolve => setTimeout(resolve, 10)); + } + expect(waiting).toBe(true); + await blocker.query('COMMIT'); + expect(await pending).toMatchObject({ error: { status: 409 } }); + } finally { + await blocker.query('ROLLBACK'); + blocker.release(); + await pending; + } + expect(await row(f, runId)).toEqual(before); + expect((await snapshotCounts(f)).retries).toBe(0); + }); + + test('unsupported retained build rejects fresh retry while accepted receipt replays before current build eligibility', async () => { + const f = await fixture(), + { experiment, runId } = await prepare(f); + await failBeforeClaim(f, runId); + const key = receipt(); + const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key); + await failBeforeClaim(f, runId, 'Later failure'); + // Alter retained evidence only in this disposable schema to model a no-longer-installed historical build. + const altered = structuredClone(experiment.preview); + altered.request.build.runtimeVersion = 'unavailable-historical-build'; + const { previewHash: _oldHash, ...manifest } = altered; + altered.previewHash = experimentHash(manifest); + const request = experimentTrialRequest(altered, altered.candidates[0]!, runId); + await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER'); + await f.pool.query('UPDATE research_experiments SET preview=$2,preview_hash=$3 WHERE id=$1', [ + experiment.id, + altered, + altered.previewHash, + ]); + await f.pool.query('UPDATE runs SET request_snapshot=$2 WHERE id=$1', [runId, request]); + await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER'); + await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER'); + const before = await row(f, runId); + await expect( + f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()) + ).rejects.toMatchObject({ status: 409 }); + expect(await row(f, runId)).toEqual(before); + expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual( + accepted.retry + ); + expect((await snapshotCounts(f)).retries).toBe(1); + }); +}); diff --git a/test/postgres/experiments.test.ts b/test/postgres/experiments.test.ts index 545b849e..3dc6bd88 100644 --- a/test/postgres/experiments.test.ts +++ b/test/postgres/experiments.test.ts @@ -64,7 +64,7 @@ async function fixture(poolMax = 4, withExperiments = true) { '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '21-run-reproduction.sql', - ...(withExperiments ? ['22-experiments.sql'] : []), + ...(withExperiments ? ['22-experiments.sql', '23-experiment-retries.sql'] : []), ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') @@ -702,6 +702,13 @@ describe.skipIf(!url)('retained-input experiments', () => { expect((await f.api.getReproductionComparison(reproduction.id)).status).toBe('match'); const ordinary = await f.api.createRun({ backtestId: f.draft.id }, receipt()); expect(ordinary.status).toBe('pending'); + // The current experiment reader includes retry counters introduced after SQL22. + await f.pool.query( + readFileSync( + new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url), + 'utf8' + ) + ); const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} }; const preview = await f.experiments.preview(input); expect( diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 7907fedb..ebb22132 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -25,6 +25,7 @@ const migrations = [ '20-research-workspace.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { diff --git a/test/postgres/research-retention.test.ts b/test/postgres/research-retention.test.ts index 01ddcd56..185196bd 100644 --- a/test/postgres/research-retention.test.ts +++ b/test/postgres/research-retention.test.ts @@ -27,7 +27,9 @@ const retention = sql('19-canonical-research.sql') + '\n' + sql('21-run-reproduction.sql') + - sql('22-experiments.sql'); + sql('22-experiments.sql') + + '\n' + + sql('23-experiment-retries.sql'); const request = { name: 'Retained evidence', strategy: 'sma-crossover', diff --git a/test/postgres/research-runtime-isolation.test.ts b/test/postgres/research-runtime-isolation.test.ts index 6dbecff2..96e64e54 100644 --- a/test/postgres/research-runtime-isolation.test.ts +++ b/test/postgres/research-runtime-isolation.test.ts @@ -71,6 +71,7 @@ async function fixture() { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') diff --git a/test/postgres/research-workspace.test.ts b/test/postgres/research-workspace.test.ts index 42cf4c37..1d637a3e 100644 --- a/test/postgres/research-workspace.test.ts +++ b/test/postgres/research-workspace.test.ts @@ -62,6 +62,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) { '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', + '23-experiment-retries.sql', ]) { await pool.query(sql(name)); } diff --git a/test/postgres/run-reproduction.test.ts b/test/postgres/run-reproduction.test.ts index a11de1e7..9f421d23 100644 --- a/test/postgres/run-reproduction.test.ts +++ b/test/postgres/run-reproduction.test.ts @@ -61,7 +61,9 @@ async function fixture(poolMax = 4, withReproduction = true) { '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', - ...(withReproduction ? ['21-run-reproduction.sql', '22-experiments.sql'] : []), + ...(withReproduction + ? ['21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql'] + : []), ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')