fix(research): keep experiment choices after linked template failure (RP10)

This commit is contained in:
Boki 2026-10-27 13:37:48 -04:00
parent 49da701aa7
commit f0e7d07476
5 changed files with 230 additions and 8 deletions

View file

@ -1476,9 +1476,39 @@ test('retained_experiment_preview_submit_compare_cancel_and_reopen_browser', asy
await f.login();
await f.page.goto(`${f.origin}/backtests/${backtest.id}`);
await f.page.getByRole('link', { name: 'Create experiment', exact: true }).click();
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
// A stale link must not hide the valid saved template in the catalog.
const missingBacktestId = randomUUID();
const missingLookup = f.page.waitForResponse(response =>
response.url().endsWith(`/api/v2/backtests/${missingBacktestId}`)
);
await f.page.goto(`${f.origin}/experiments?backtestId=${missingBacktestId}`);
expect((await missingLookup).status()).toBe(404);
await visible(f.page, /Could not load the selected backtest:/);
expect(await f.page.getByLabel('Saved backtest').inputValue()).toBe(missingBacktestId);
await f.page
.getByLabel('Saved backtest')
.locator(`option[value="${backtest.id}"]`)
.waitFor({ state: 'attached' });
await f.page.getByLabel('Experiment name', { exact: true }).fill('Retained SMA sweep');
await f.page.getByLabel('Parameter grid (JSON)').fill('{"fastPeriod":[1,2],"slowPeriod":[3]}');
expect(
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).isDisabled()
).toBe(true);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
expect(await f.page.getByLabel('Experiment name', { exact: true }).inputValue()).toBe(
'Retained SMA sweep'
);
expect(await f.page.getByLabel('Parameter grid (JSON)').inputValue()).toBe(
'{"fastPeriod":[1,2],"slowPeriod":[3]}'
);
expect(await f.request(`/api/v2/backtests/${backtest.id}`)).toEqual(backtest);
expect(
(await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n
).toBe(0);
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
0
);
const previewing = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/experiments/preview')
);

View file

@ -19,6 +19,8 @@ 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>;
@ -108,6 +110,10 @@ function Probe() {
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(() =>
@ -341,6 +347,9 @@ beforeAll(async () => {
({ 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;
@ -388,6 +397,170 @@ afterAll(async () => {
});
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.');