stock-bot/test/integration/experiment-retries-ui.test.tsx

808 lines
32 KiB
TypeScript

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 serialize the read before retry acceptance', async () => {
const value = await start();
await flush(() => {
button('Refresh experiment').click();
button('Confirm retry trial 1').click();
});
expect(
requests.filter(item => item.path === retryPath() && item.method === 'POST')
).toHaveLength(0);
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
await flush(() => 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 renders loading/empty states, exact nullable failure snapshots and research agent authorship', 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);
saved.principal = 'agent:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
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(saved.principal);
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');
});
});