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

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

View file

@ -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<string, unknown>[] }>;
function fixture(
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => ({ rows: [] })
) {
const client = { query: mock(query) };
const database = {
...client,
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => 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<string, unknown> = {}) {
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<typeof retainedPreview>) {
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',
});
});
});

View file

@ -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<typeof router.useNavigate>;
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<T>() {
let resolve!: (value: T) => void;
let reject!: (cause: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
type Pending = ReturnType<typeof deferred<Response>> & {
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<ExperimentTrial['metrics']> {
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<ExperimentTrial>) {
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<Response>(),
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');
});
});

View file

@ -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),

View file

@ -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,