From f0e7d074760841f6f59c83334f929f94ed1b50ed Mon Sep 17 00:00:00 2001 From: Boki Date: Tue, 27 Oct 2026 13:37:48 -0400 Subject: [PATCH] fix(research): keep experiment choices after linked template failure (RP10) --- .../hooks/useExperimentTemplates.ts | 24 ++- docs/development/backlog/tasks/RP10.md | 2 + docs/guide/backtest-walkthrough.md | 7 + test/e2e/workbench.test.ts | 32 +++- test/integration/experiments-ui.test.tsx | 173 ++++++++++++++++++ 5 files changed, 230 insertions(+), 8 deletions(-) diff --git a/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts b/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts index f325d74a..a07e7f26 100644 --- a/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts +++ b/apps/stock/web-app/src/features/experiments/hooks/useExperimentTemplates.ts @@ -30,13 +30,23 @@ export function useExperimentTemplates(initialBacktestId: string) { if (!Array.isArray(rows)) { throw new Error('The saved backtest list could not be read'); } - const selected = - initialBacktestId && !rows.some(item => item?.id === initialBacktestId) - ? await backtestApiV2.getBacktest(initialBacktestId) - : null; - if (current) { - setMoreTemplates(rows.length === limit); - setBacktests((selected ? [...rows, selected] : rows).filter(canonical)); + if (!current) { + return; + } + setMoreTemplates(rows.length === limit); + setBacktests(rows.filter(canonical)); + if (initialBacktestId && !rows.some(item => item?.id === initialBacktestId)) { + // A missing linked template must not hide the successfully loaded catalog. + try { + const selected = await backtestApiV2.getBacktest(initialBacktestId); + if (current) { + setBacktests([...rows, selected].filter(canonical)); + } + } catch (cause) { + if (current) { + setTemplateError(`Could not load the selected backtest: ${message(cause)}`); + } + } } })() .catch(cause => { diff --git a/docs/development/backlog/tasks/RP10.md b/docs/development/backlog/tasks/RP10.md index f956709d..ebc46969 100644 --- a/docs/development/backlog/tasks/RP10.md +++ b/docs/development/backlog/tasks/RP10.md @@ -11,3 +11,5 @@ Ownership: experiment agent owns `useExperimentTemplates.ts`, a small `Experimen Acceptance/tests: 404/transport failure of the linked lookup leaves valid catalog options selectable and missing selection explicitly unavailable. Choosing a valid option preserves name/grid and enables normal preview; no save or submission occurs merely by selecting. Retry can recover the linked option without changing the current choice. List errors, empty catalogs, pagination and unavailable/noncanonical selections retain honest states. Late lookup/list replies after parent change, reload or unmount cannot replace current choices. Use existing test fixtures. Gates: focused experiment/cost/validation tests, application/authored types, strict lint/build, root full repository check and browser recovery from a missing query-string backtest ID. No financial, execution, statistical or conditional optimization changes. + +Accepted October 27, 2026. Missing and failed linked-template regressions failed on the baseline before the fix. Independent review passed 38 focused tests / 207 assertions. Root full repository check passed, including 1,334 integration and 150 Rust tests; the actual browser recovery scenario passed in the full invocation and continued through the existing durable experiment workflow. It verifies the missing selection, valid alternatives, unchanged draft/template and zero submissions until explicit action. [Combined evidence](../../real-data-research.md) records all gates and the separate clone-fixture correction. No editor, transport, backend or financial changes were required. diff --git a/docs/guide/backtest-walkthrough.md b/docs/guide/backtest-walkthrough.md index eeabfdd3..a384754f 100644 --- a/docs/guide/backtest-walkthrough.md +++ b/docs/guide/backtest-walkthrough.md @@ -141,6 +141,13 @@ See [RunReproduction](../../apps/stock/web-app/src/features/backtest/components/ ## Grow one run into a research workflow +When a linked backtest cannot be loaded, the setup page keeps other successfully loaded +catalog choices available and reports the lookup failure. The unavailable +selection stays selected until you choose another; your experiment name and parameter grid +are preserved. **Retry saved backtests** retries loading without automatically choosing a +different template. Selecting a valid template does not save anything or submit runs; use +the normal preview and confirmation steps. + 1. Create a **research project and hypothesis**, link a strategy, and save the backtest configuration. Keep the proposed explanation separate from measured evidence. 2. Create an **experiment** with a bounded parameter grid. Each trial uses the same durable run path above. Compare completed results alongside errors and incomplete trials. 3. Use **chronological validation** to select on training data, then evaluate the selected parameters on held-out validation/test data. A saved sealed report links the evidence. Walk-forward applies this over windows; its current windows reset state and capital, so do not interpret them as one continuously traded account. diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 33669eb9..c344f1c9 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -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') ); diff --git a/test/integration/experiments-ui.test.tsx b/test/integration/experiments-ui.test.tsx index b4169cbd..b8eb29fd 100644 --- a/test/integration/experiments-ui.test.tsx +++ b/test/integration/experiments-ui.test.tsx @@ -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; let root: Root | undefined; let host: HTMLDivElement; let navigate: ReturnType; @@ -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.');