stock-bot/test/integration/experiments-ui.test.tsx

923 lines
39 KiB
TypeScript

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { GlobalWindow } from 'happy-dom';
import { act, createElement, type ReactElement } from 'react';
import type { Root } from 'react-dom/client';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import type {
ExperimentDetail,
ExperimentPreview,
ExperimentTrial,
} from '@stock-bot/stock-config/experiments';
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
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 ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage;
let useExperimentTemplates: typeof import('../../apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates').useExperimentTemplates;
let templateState: ReturnType<typeof useExperimentTemplates>;
let root: Root | undefined;
let host: HTMLDivElement;
let navigate: ReturnType<typeof router.useNavigate>;
let location = '';
const backtestId = '11111111-1111-4111-8111-111111111111';
const otherBacktestId = '22222222-2222-4222-8222-222222222222';
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')}`;
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 field(label: string) {
const found = [...host.querySelectorAll('label')]
.find(item => item.firstChild?.textContent?.trim() === label)
?.querySelector('input,select,textarea');
if (!found) {
throw new Error(`Missing field ${label}`);
}
return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
}
function change(label: string, value: string) {
const input = field(label);
const prototype =
input.tagName === 'SELECT'
? browser.HTMLSelectElement.prototype
: input.tagName === 'TEXTAREA'
? browser.HTMLTextAreaElement.prototype
: browser.HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
input.dispatchEvent(
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
bubbles: true,
}) as unknown as Event
);
}
function Probe() {
navigate = router.useNavigate();
location = router.useLocation().pathname + router.useLocation().search;
return null;
}
function TemplateProbe({ id }: { id: string }) {
templateState = useExperimentTemplates(id);
return null;
}
async function render(element: ReactElement, path: string) {
root ??= createRoot(host);
await flush(() =>
root!.render(
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
)
);
}
const template = (id = backtestId): Backtest => ({
id,
name: 'Saved canonical template',
strategy: 'sma',
strategyVersionId: versionId,
symbols: ['X0.US'],
startDate: '2024-01-01',
endDate: '2024-01-02',
initialCapital: 100,
config: { canonical: {}, datasetHash: 'a'.repeat(64) },
archivedAt: null,
createdAt: '2026-10-24',
updatedAt: '2026-10-24',
});
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,
};
}
async function list(parent = backtestId) {
await render(createElement(ExperimentListPage), `/experiments?backtestId=${parent}`);
await flush(() => {
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(parent)]);
reply(request(`/api/v2/experiments?backtestId=${parent}`), { experiments: [] });
});
}
async function ready(value = preview()) {
await list(value.input.backtestId);
await flush(() => {
change('Experiment name', value.input.name);
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
});
await flush(() => button('Preview experiment').click());
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
return value;
}
test('same-event candidate toggle then Preview never captures the old builtin strategy', async () => {
await list();
await flush(() => change('Experiment name', 'Candidate draft'));
const checkbox = [...host.querySelectorAll('input[type="checkbox"]')].find(input =>
input.closest('label')?.textContent?.includes('Use an isolated candidate version')
) as HTMLInputElement;
expect(checkbox).toBeDefined();
await flush(() => {
checkbox.click();
button('Preview experiment').click();
});
expect(requests.filter(item => item.path === '/api/v2/experiments/preview')).toHaveLength(0);
expect(button('Preview experiment').disabled).toBe(true);
expect(host.textContent).toContain('Select an immutable candidate');
});
async function showDetail(value?: ExperimentDetail) {
const routes = createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/experiments/:experimentId',
element: createElement(ExperimentDetailPage),
})
);
await render(routes, `/experiments/${value?.id ?? experimentId}`);
if (value) {
await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value }));
}
}
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');
({ ExperimentListPage, ExperimentDetailPage } = await import(
'../../apps/stock/web-app/src/features/experiments'
));
({ useExperimentTemplates } = await import(
'../../apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates'
));
});
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: identity fences must still reject stale responses.
},
});
});
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('bounded experiment creation', () => {
describe('linked template recovery', () => {
const choices = () =>
[...(field('Saved backtest') as HTMLSelectElement).options].map(option => option.value);
const openMissing = async () => {
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
await flush(() => {
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(otherBacktestId)]);
change('Experiment name', 'Preserved recovery draft');
change('Parameter grid (JSON)', '{"fastPeriod":[2,4]}');
});
return request(`/api/v2/backtests/${backtestId}`);
};
for (const failure of ['missing', 'transport'] as const) {
test(`${failure} linked lookup leaves catalog choices and retry without changing the draft`, async () => {
const lookup = await openMissing();
await flush(() => {
if (failure === 'missing') {
reply(lookup, { error: 'Backtest not found' }, 404);
} else {
lookup.settled = true;
lookup.reject(new Error('Connection lost'));
}
});
expect(choices()).toEqual(['', backtestId, otherBacktestId]);
expect(field('Saved backtest').value).toBe(backtestId);
expect(field('Saved backtest').disabled).toBe(false);
expect(host.textContent).toContain('Selected backtest is unavailable');
expect(host.textContent).toContain('Could not load the selected backtest:');
expect(button('Preview experiment').disabled).toBe(true);
await flush(() => change('Saved backtest', otherBacktestId));
expect(button('Preview experiment').disabled).toBe(false);
expect(field('Experiment name').value).toBe('Preserved recovery draft');
expect(field('Parameter grid (JSON)').value).toBe('{"fastPeriod":[2,4]}');
expect(requests.every(item => item.method === 'GET')).toBe(true);
await flush(() => button('Retry saved backtests').click());
await flush(() =>
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(otherBacktestId)])
);
await flush(() => reply(request(`/api/v2/backtests/${backtestId}`), template()));
expect(choices()).toEqual(['', otherBacktestId, backtestId]);
expect(field('Saved backtest').value).toBe(otherBacktestId);
expect(field('Experiment name').value).toBe('Preserved recovery draft');
expect(field('Parameter grid (JSON)').value).toBe('{"fastPeriod":[2,4]}');
expect(host.textContent).not.toContain('Could not load the selected backtest:');
expect(requests.every(item => item.method === 'GET')).toBe(true);
await flush(() => button('Preview experiment').click());
expect(request('/api/v2/experiments/preview', 'POST').body).toEqual({
backtestId: otherBacktestId,
name: 'Preserved recovery draft',
grid: { fastPeriod: [2, 4] },
});
});
}
test('a genuine catalog failure remains distinct and retry can load an off-page linked template', async () => {
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
await flush(() =>
reply(request('/api/v2/backtests?limit=50&offset=0'), { error: 'Catalog unavailable' }, 500)
);
expect(host.textContent).toContain('Catalog unavailable');
expect(host.textContent).not.toContain('Could not load the selected backtest:');
expect(requests.some(item => item.path === `/api/v2/backtests/${backtestId}`)).toBe(false);
expect(choices()).toEqual(['', backtestId]);
await flush(() => button('Retry saved backtests').click());
await flush(() => reply(request('/api/v2/backtests?limit=50&offset=0'), []));
await flush(() => reply(request(`/api/v2/backtests/${backtestId}`), template()));
expect(field('Saved backtest').value).toBe(backtestId);
expect(host.textContent).not.toContain('Selected backtest is unavailable');
expect(host.textContent).not.toContain('Catalog unavailable');
expect(host.textContent).not.toContain('No saved canonical backtests');
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test('empty and noncanonical choices stay unavailable without auto-selection', async () => {
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
await flush(() =>
reply(request('/api/v2/backtests?limit=50&offset=0'), [
{ ...template(otherBacktestId), config: {} },
{ ...template(runId(0)), archivedAt: '2026-10-27' },
])
);
await flush(() =>
reply(request(`/api/v2/backtests/${backtestId}`), {
...template(),
strategyVersionId: null,
})
);
expect(choices()).toEqual(['', backtestId]);
expect(field('Saved backtest').value).toBe(backtestId);
expect(host.textContent).toContain('Selected backtest is unavailable');
expect(host.textContent).toContain('No saved canonical backtests');
expect(button('Preview experiment').disabled).toBe(true);
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test('lookup failure preserves pagination and a later catalog page can recover the linked choice', async () => {
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
const rows = Array.from({ length: 50 }, (_, index) => template(runId(index)));
await flush(() => reply(request('/api/v2/backtests?limit=50&offset=0'), rows));
await flush(() => reply(request(`/api/v2/backtests/${backtestId}`), {}, 404));
expect(choices()).toHaveLength(52); // Empty + unavailable linked choice + 50 catalog rows.
expect(button('Load more backtests').disabled).toBe(false);
await flush(() => button('Load more backtests').click());
await flush(() =>
reply(request('/api/v2/backtests?limit=100&offset=0'), [...rows, template()])
);
expect(choices()).toHaveLength(52);
expect(field('Saved backtest').value).toBe(backtestId);
expect(host.textContent).not.toContain('Selected backtest is unavailable');
expect(host.textContent).not.toContain('Could not load the selected backtest:');
expect(host.textContent).not.toContain('Load more backtests');
expect(requests.filter(item => item.path === `/api/v2/backtests/${backtestId}`)).toHaveLength(
1
);
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
for (const stage of ['list', 'lookup'] as const) {
for (const change of ['parent', 'reload', 'unmount'] as const) {
test(`late ${stage} response after ${change} cannot replace current choices`, async () => {
await render(createElement(TemplateProbe, { id: backtestId }), '/experiments');
let stale = request('/api/v2/backtests?limit=50&offset=0');
if (stage === 'lookup') {
await flush(() => reply(stale, [template(otherBacktestId)]));
stale = request(`/api/v2/backtests/${backtestId}`);
}
await flush(() => {
if (change === 'parent') {
root!.render(createElement(TemplateProbe, { id: otherBacktestId }));
} else if (change === 'reload') {
templateState.setTemplateReload(value => value + 1);
} else {
root!.unmount();
root = undefined;
}
});
if (change !== 'unmount') {
const latest = requests
.filter(item => item.path === '/api/v2/backtests?limit=50&offset=0')
.at(-1)!;
await flush(() => reply(latest, [template(), template(otherBacktestId)]));
}
const current = templateState;
await flush(() => {
if (stage === 'lookup' && change === 'reload') {
stale.settled = true;
stale.reject(new Error('Old lookup failed'));
} else {
reply(stale, stage === 'list' ? [] : template());
}
});
expect(templateState).toBe(current);
expect(
requests.filter(item => item.path === `/api/v2/backtests/${backtestId}`)
).toHaveLength(stage === 'lookup' ? 1 : 0);
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
}
}
});
test('preview displays frozen count/window/policies before duplicate-safe admission and exact navigation', async () => {
const value = await ready();
expect(host.textContent).toContain('No experiments yet.');
expect(host.textContent).toContain('2 trials · Frozen template name');
expect(host.textContent).toContain(new Date(value.dataset.bounds.tradeStart).toISOString());
expect(host.textContent).toContain(value.request.datasetHash);
const asset = [...host.querySelectorAll('dt')].find(
item => item.textContent === 'Asset / timeframe'
);
expect(asset?.nextElementSibling?.textContent).toBe('X0.US / 1m');
expect(
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
).toHaveLength(0);
await flush(() => {
button('Confirm experiment').click();
button('Confirm experiment').click();
});
const post = request('/api/v2/experiments', 'POST');
expect(post.body).toEqual({ ...value.input, previewHash: value.previewHash });
expect(post.headers.get('Idempotency-Key')).toBeTruthy();
expect(post.credentials).toBe('include');
expect(
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
).toHaveLength(1);
await flush(() => reply(post, { experiment: detail(value) }, 202));
expect(location).toBe(`/experiments/${experimentId}`);
});
test('every form change invalidates the preview and rejects a late response for the old input', async () => {
const value = await ready();
await flush(() => change('Experiment name', 'Edited study'));
expect(host.textContent).not.toContain('Confirm experiment');
await flush(() => button('Preview experiment').click());
const stale = request('/api/v2/experiments/preview', 'POST');
await flush(() => change('Parameter grid (JSON)', '{}'));
const old = structuredClone(value);
old.input.name = 'Edited study';
await flush(() => reply(stale, { preview: old }));
expect(host.textContent).not.toContain('Confirm experiment');
expect(host.querySelector('[aria-label="Frozen experiment inputs"]')).toBeNull();
});
test('invalid JSON and reserved keys are rejected before preview; server validation stays visible', async () => {
await list();
await flush(() => {
change('Experiment name', 'Trend study');
change('Parameter grid (JSON)', '{');
});
await flush(() => button('Preview experiment').click());
expect(host.querySelector('[role="alert"]')).not.toBeNull();
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
await flush(() => change('Parameter grid (JSON)', '{"__proto__":[1]}'));
await flush(() => button('Preview experiment').click());
expect(host.textContent).toContain('Invalid parameter name');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[20],"slowPeriod":[10]}'));
await flush(() => button('Preview experiment').click());
await flush(() =>
reply(
request('/api/v2/experiments/preview', 'POST'),
{ error: 'fastPeriod must be below slowPeriod' },
400
)
);
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
expect(host.textContent).not.toContain('Confirm experiment');
});
test.each(['network', 'malformed', 'foreign', 'server'] as const)(
'%s create ambiguity retains byte-identical body/key and locks editing until explicit retry',
async failure => {
const value = await ready();
await flush(() => button('Confirm experiment').click());
const first = request('/api/v2/experiments', 'POST');
await flush(() => {
if (failure === 'network') {
first.settled = true;
first.reject(new Error('response lost'));
} else if (failure === 'malformed') {
reply(first, { experiment: { id: experimentId } }, 202);
} else if (failure === 'foreign') {
reply(first, { experiment: detail(preview(2, otherBacktestId)) }, 202);
} else {
reply(first, { error: 'Temporary failure' }, 500);
}
});
expect(host.textContent).toContain('Acceptance is unconfirmed');
expect(field('Experiment name').disabled).toBe(true);
expect(field('Saved backtest').disabled).toBe(true);
expect(button('Preview experiment').disabled).toBe(true);
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
await flush(() => button('Refresh experiments').click());
await flush(() =>
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] })
);
await flush(() => button('Retry experiment submission').click());
const second = request('/api/v2/experiments', 'POST');
expect(second.rawBody).toBe(first.rawBody);
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(second, { experiment: detail(value) }, 202));
expect(location).toBe(`/experiments/${experimentId}`);
}
);
test('stale-preview conflict does not silently replace intent and explicit new intent requires a fresh preview', async () => {
const value = await ready();
await flush(() => button('Confirm experiment').click());
const first = request('/api/v2/experiments', 'POST');
await flush(() => reply(first, { error: 'Preview changed; refresh inputs' }, 409));
expect(host.textContent).toContain('Preview changed; refresh inputs');
expect(
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
).toHaveLength(1);
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
await flush(() => button('Start new experiment').click());
expect(field('Experiment name').disabled).toBe(true);
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
await flush(() => button('Start new experiment').click());
expect(host.textContent).not.toContain('Confirm experiment');
expect(field('Experiment name').disabled).toBe(false);
await flush(() => button('Preview experiment').click());
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
await flush(() => button('Confirm experiment').click());
expect(request('/api/v2/experiments', 'POST').headers.get('Idempotency-Key')).not.toBe(
first.headers.get('Idempotency-Key')
);
});
test('old create completion cannot navigate after selecting a different backtest', async () => {
const value = await ready();
await flush(() => button('Confirm experiment').click());
const old = request('/api/v2/experiments', 'POST');
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
await flush(() => reply(old, { experiment: detail(value) }, 202));
expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
expect(field('Experiment name').value).toBe('');
expect(host.textContent).not.toContain('Retry experiment submission');
});
test.each([
'wrong-parent',
'duplicate-trial',
'wrong-dataset',
'invalid-date',
'wrong-series',
] as const)('malformed %s preview never enables admission', async kind => {
await list();
const value = preview();
await flush(() => {
change('Experiment name', value.input.name);
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
});
await flush(() => button('Preview experiment').click());
if (kind === 'wrong-parent') {
value.input.backtestId = otherBacktestId;
}
if (kind === 'duplicate-trial') {
value.candidates[1]!.trialKey = value.candidates[0]!.trialKey;
}
if (kind === 'wrong-dataset') {
value.dataset = { ...value.dataset, hash: 'f'.repeat(64) };
}
if (kind === 'invalid-date') {
value.dataset = { ...value.dataset, bounds: { ...value.dataset.bounds, tradeEnd: 9e15 } };
}
if (kind === 'wrong-series') {
value.dataset = { ...value.dataset, series: [] };
}
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
expect(host.textContent).toContain('could not be verified');
expect(host.textContent).not.toContain('Confirm experiment');
});
test('owned links require deliberate discard and keep ambiguous body/key when navigation is declined', async () => {
const value = await ready();
await flush(() => button('Confirm experiment').click());
const first = request('/api/v2/experiments', 'POST');
await flush(() => {
first.settled = true;
first.reject(new Error('lost'));
});
await flush(() => button('Refresh experiments').click());
await flush(() =>
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
experiments: [detail(value)],
})
);
let prompts = 0;
Object.defineProperty(browser, 'confirm', {
configurable: true,
value: () => {
prompts++;
return false;
},
});
await flush(() =>
(host.querySelector(`a[href="/experiments/${experimentId}"]`) as HTMLAnchorElement).click()
);
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
expect(prompts).toBe(2);
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
expect(field('Experiment name').disabled).toBe(true);
await flush(() => button('Retry experiment submission').click());
const retry = request('/api/v2/experiments', 'POST');
expect(retry.rawBody).toBe(first.rawBody);
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, { experiment: detail(value) }, 202));
expect(location).toBe(`/experiments/${experimentId}`);
});
test('list loading/error/empty states recover and saved links preserve missing counts', async () => {
await render(createElement(ExperimentListPage), '/experiments');
expect(host.textContent).toContain('Loading experiments...');
await flush(() => {
reply(request('/api/v2/experiments'), { error: 'Read unavailable' }, 500);
reply(request('/api/v2/backtests?limit=50&offset=0'), []);
});
expect(host.textContent).toContain('No saved canonical backtests');
expect(host.textContent).toContain('Read unavailable');
await flush(() => button('Refresh experiments').click());
const value = detail(preview(2), ['completed', 'missing']);
await flush(() => reply(request('/api/v2/experiments'), { experiments: [value] }));
expect(host.textContent).toContain('missing: 1');
expect(host.querySelector(`a[href="/experiments/${experimentId}"]`)).not.toBeNull();
});
});
describe('experiment outcomes and cancellation', () => {
test('all states, null reasons, exact zero, mismatches, provenance and exact run links remain visible', async () => {
const value = detail(preview(8), [
'completed',
'failed',
'missing',
'cancelled',
'running',
'paused',
'pending',
'completed',
]);
value.trials[7]!.comparable = false;
value.trials[7]!.diagnostic = 'Retained request does not match the candidate';
value.trials[7]!.limitations = ['Result cannot be compared'];
value.trials[7]!.metrics = null;
value.trials[7]!.unavailable = null;
await showDetail(value);
expect(host.querySelectorAll('tbody tr')).toHaveLength(8);
expect(host.textContent).toContain('missing: 1');
expect(host.textContent).toContain('Strategy callback failed');
expect(host.textContent).toContain('Child run missing');
expect(host.textContent).toContain('Incomparable');
expect(host.textContent).toContain('Retained request does not match');
expect(host.textContent).toContain('Unavailable: insufficient-periods');
const first = host.querySelector('tbody tr')!;
expect(first.querySelectorAll('td')[3]!.textContent).toBe('0');
expect(first.querySelectorAll('td')[4]!.textContent).toBe('0');
expect(host.querySelector(`a[href="/backtests/${backtestId}/run/${runId(0)}"]`)).not.toBeNull();
expect(host.querySelectorAll('tbody a')).toHaveLength(7);
expect(host.textContent).toContain(value.previewHash);
expect(host.textContent).toContain(value.preview.request.build.engineBinarySha256);
expect(host.textContent).not.toContain('Retry failed');
});
test('cancel is explicit and duplicate-safe, retains terminal outcomes and distinguishes requested running work', async () => {
const value = detail(preview(3), ['completed', 'running', 'pending']);
await showDetail(value);
await flush(() => {
button('Cancel remaining trials').click();
button('Cancel remaining trials').click();
});
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
expect(post.body).toEqual({});
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
const cancelled = detail(value.preview, ['completed', 'running', 'cancelled']);
cancelled.cancelRequested = true;
cancelled.trials[1]!.cancelRequested = true;
await flush(() => reply(post, { experiment: cancelled }));
expect(host.textContent).toContain('Cancellation requested. Running trials may still finish');
expect(host.textContent).toContain('completed: 1');
expect(host.textContent).toContain('running: 1');
expect(host.textContent).toContain('cancelled: 1');
expect(host.textContent).not.toContain('Cancel remaining trials');
});
test('cancellation response loss is visible and refresh verifies persisted state', async () => {
const value = detail();
await showDetail(value);
await flush(() => button('Cancel remaining trials').click());
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
await flush(() => {
post.settled = true;
post.reject(new Error('lost'));
});
expect(host.textContent).toContain('Refresh to verify the saved state');
await flush(() => button('Refresh experiment').click());
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
cancelled.cancelRequested = true;
await flush(() =>
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: cancelled })
);
expect(host.textContent).toContain('cancelled: 2');
});
test('old detail and cancel responses never overwrite a different selected experiment', async () => {
const value = detail();
await showDetail(value);
await flush(() => button('Cancel remaining trials').click());
const oldCancel = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
await flush(() => navigate(`/experiments/${otherExperimentId}`));
const other = detail(preview(1));
other.id = otherExperimentId;
other.name = 'Other experiment';
other.preview.input.name = other.name;
await flush(() =>
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
);
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
cancelled.cancelRequested = true;
await flush(() => reply(oldCancel, { experiment: cancelled }));
expect(host.querySelector('h1')!.textContent).toBe('Other experiment');
await flush(() => button('Refresh experiment').click());
const stale = request(`/api/v2/experiments/${otherExperimentId}`);
await flush(() => navigate(`/experiments/${experimentId}`));
await flush(() => reply(stale, { experiment: other }));
expect(host.textContent).not.toContain('Other experiment');
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
});
test.each([
'identity',
'missing-row',
'wrong-parameters',
'count-mismatch',
'malformed-metrics',
] as const)('malformed %s detail fails closed and recovers after refresh', async kind => {
await showDetail();
const value = detail(preview(), ['completed', 'pending']);
if (kind === 'identity') {
value.id = otherExperimentId;
}
if (kind === 'missing-row') {
value.trials.pop();
}
if (kind === 'wrong-parameters') {
value.trials[0]!.parameters = { fastPeriod: 19 };
}
if (kind === 'count-mismatch') {
value.counts.completed = 0;
}
if (kind === 'malformed-metrics') {
(value.trials[0]!.metrics as unknown as Record<string, unknown>).totalReturn = '0';
}
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
expect(host.textContent).toContain('could not be verified');
expect(host.querySelector('tbody')).toBeNull();
await flush(() => button('Refresh experiment').click());
await flush(() =>
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: detail() })
);
expect(host.querySelectorAll('tbody tr')).toHaveLength(2);
});
test('not-found/read failures show recovery controls without claiming an empty result', async () => {
await showDetail();
expect(host.textContent).toContain('Loading experiment...');
await flush(() =>
reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Experiment not found' }, 404)
);
expect(host.textContent).toContain('Experiment not found');
expect(button('Refresh experiment').disabled).toBe(false);
expect(host.querySelector('tbody')).toBeNull();
});
});