feat(backtests): separate saving from retry-safe run submission
This commit is contained in:
parent
5eb0985057
commit
9b9403e36b
18 changed files with 1200 additions and 226 deletions
|
|
@ -3,6 +3,7 @@ import { GlobalWindow } from 'happy-dom';
|
|||
import { act, createElement, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type {
|
||||
Backtest,
|
||||
Run,
|
||||
RunResult,
|
||||
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
||||
|
|
@ -22,11 +23,15 @@ let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest
|
|||
let useWebSocket: typeof import('../../apps/stock/web-app/src/hooks/useWebSocket').useWebSocket;
|
||||
let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact;
|
||||
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
||||
let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog;
|
||||
let BacktestListPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestListPageV2').BacktestListPageV2;
|
||||
let router: typeof import('react-router-dom');
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let latest: ReturnType<typeof useBacktestV2>;
|
||||
let renders = 0;
|
||||
let pageLocation = '';
|
||||
let navigatePage: ReturnType<typeof router.useNavigate>;
|
||||
let now = 0;
|
||||
let timerId = 0;
|
||||
const timers = new Map<
|
||||
|
|
@ -48,6 +53,8 @@ type Request = ReturnType<typeof deferred<Response>> & {
|
|||
method: string;
|
||||
signal?: AbortSignal | null;
|
||||
settled: boolean;
|
||||
body?: string;
|
||||
headers: Headers;
|
||||
};
|
||||
const requests: Request[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
|
|
@ -168,9 +175,10 @@ async function advance(ms: number) {
|
|||
}
|
||||
const polls = () => [...timers.values()].filter(timer => timer.delay === 1000).length;
|
||||
function click(label: string) {
|
||||
const button = [...host.querySelectorAll('button')].find(
|
||||
item => item.getAttribute('aria-label') === label || item.textContent?.trim() === label
|
||||
);
|
||||
const buttons = [...host.querySelectorAll('button')];
|
||||
const button =
|
||||
buttons.find(item => item.textContent?.trim() === label) ??
|
||||
buttons.find(item => item.getAttribute('aria-label') === label);
|
||||
if (!button) throw new Error(`Missing button ${label}`);
|
||||
button.click();
|
||||
}
|
||||
|
|
@ -217,7 +225,8 @@ async function mountPage(status: Run['status']) {
|
|||
path: '/backtests/:id/run/:runId',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
)
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => {
|
||||
|
|
@ -230,6 +239,12 @@ async function mountPage(status: Run['status']) {
|
|||
});
|
||||
}
|
||||
|
||||
function LocationProbe() {
|
||||
pageLocation = router.useLocation().pathname;
|
||||
navigatePage = router.useNavigate();
|
||||
return null;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
|
|
@ -249,12 +264,19 @@ beforeAll(async () => {
|
|||
({ BacktestDetailPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
||||
));
|
||||
({ CreateBacktestDialog } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog'
|
||||
));
|
||||
({ BacktestListPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestListPageV2'
|
||||
));
|
||||
router = await import('react-router-dom');
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
TestSocket.instances.length = 0;
|
||||
renders = 0;
|
||||
pageLocation = '';
|
||||
now = 0;
|
||||
timers.clear();
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
|
|
@ -265,6 +287,8 @@ beforeEach(() => {
|
|||
path: new URL(String(input)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
signal: init?.signal,
|
||||
body: typeof init?.body === 'string' ? init.body : undefined,
|
||||
headers: new Headers(init?.headers),
|
||||
settled: false,
|
||||
};
|
||||
requests.push(pending);
|
||||
|
|
@ -482,12 +506,12 @@ describe('run selection and persisted status authority', () => {
|
|||
await selectRunning();
|
||||
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
|
||||
'Cancel run',
|
||||
'Rerun',
|
||||
'Run current settings',
|
||||
]);
|
||||
await selectRunning('B', 'paused');
|
||||
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
|
||||
'Cancel run',
|
||||
'Rerun',
|
||||
'Run current settings',
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -571,3 +595,347 @@ describe('actual detail page result states', () => {
|
|||
expect(host.textContent).toContain('Performance');
|
||||
});
|
||||
});
|
||||
|
||||
async function nameBacktest() {
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
input,
|
||||
'Fixture'
|
||||
);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadDefinition(id = 'definition') {
|
||||
await flush(() => {
|
||||
void latest.loadBacktest(id);
|
||||
});
|
||||
await flush(() => {
|
||||
reply(request(`/api/v2/backtests/${id}`), { ...definition, id });
|
||||
reply(request(`/api/v2/backtests/${id}/runs`), []);
|
||||
});
|
||||
}
|
||||
|
||||
describe('explicit save and repeat-safe run submission', () => {
|
||||
test('save_only: definition save explicitly disables auto-start and makes no run request', async () => {
|
||||
const created: Backtest[] = [];
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: value => created.push(value),
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => {
|
||||
click('Save');
|
||||
click('Save');
|
||||
});
|
||||
const saving = request('/api/v2/backtests', 'POST');
|
||||
expect(JSON.parse(saving.body!).autoStart).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => reply(saving, definition));
|
||||
expect(created).toEqual([definition]);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
});
|
||||
|
||||
for (const failure of ['rejection', 'lost successful response'] as const) {
|
||||
test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => {
|
||||
const created: { definition: Backtest; run?: Run }[] = [];
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: (value, submitted) => created.push({ definition: value, run: submitted }),
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Save and run');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(first.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null });
|
||||
// In the lost-response case the server has accepted A; the transport fails.
|
||||
await flush(() =>
|
||||
failure === 'rejection'
|
||||
? reply(first, { error: 'Submission unavailable' }, 503)
|
||||
: fail(first)
|
||||
);
|
||||
expect(created).toHaveLength(0);
|
||||
expect(host.textContent).toContain('Backtest saved, but run submission failed');
|
||||
expect(host.querySelector('fieldset')!.disabled).toBe(true);
|
||||
await flush(() => {
|
||||
click('Retry submission');
|
||||
click('Retry submission');
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(3);
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(created).toEqual([{ definition, run: run('A', 'pending') }]);
|
||||
});
|
||||
}
|
||||
|
||||
for (const boundary of ['definition', 'submission'] as const) {
|
||||
test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => {
|
||||
let navigated = false;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
onClose: () => {},
|
||||
onCreated: () => {
|
||||
navigated = true;
|
||||
},
|
||||
})
|
||||
);
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
if (boundary === 'submission') {
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
}
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(
|
||||
boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs',
|
||||
'POST'
|
||||
),
|
||||
boundary === 'definition' ? definition : run('A')
|
||||
)
|
||||
);
|
||||
expect(navigated).toBe(false);
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(
|
||||
boundary === 'definition' ? 1 : 2
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
// The ref guard must work before the disabled state has rendered.
|
||||
await flush(() => {
|
||||
click('Save and run');
|
||||
click('Close backtest dialog');
|
||||
});
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull();
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(1);
|
||||
await flush(() => click('Close'));
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
await flush(() => reply(submitting, run('A', 'pending'), 202));
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
test('closing saved-but-failed dialog reloads the real list without navigating', async () => {
|
||||
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click('Save and run'));
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST')));
|
||||
await flush(() => click('Close'));
|
||||
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
||||
// Virtualized rows need real layout (W04). Here verify the refetch and that
|
||||
// the real list, not a detail route, remains mounted after closing.
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
||||
).toHaveLength(2);
|
||||
expect(host.textContent).toContain('Create and manage backtest configurations');
|
||||
expect(host.textContent).not.toContain('Retry submission');
|
||||
});
|
||||
|
||||
for (const intent of ['Save', 'Save and run'] as const) {
|
||||
test(`real list ${intent} navigates only after the requested operation succeeds`, async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: ['/backtests'] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests',
|
||||
element: createElement(BacktestListPageV2),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement('p', null, 'Saved definition'),
|
||||
}),
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id/run/:runId',
|
||||
element: createElement('p', null, 'Submitted run'),
|
||||
})
|
||||
),
|
||||
createElement(LocationProbe)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request('/api/v2/backtests'), []));
|
||||
await flush(() => click('New Backtest'));
|
||||
await nameBacktest();
|
||||
await flush(() => click(intent));
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
||||
if (intent === 'Save and run') {
|
||||
expect(pageLocation).toBe('/backtests');
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202)
|
||||
);
|
||||
}
|
||||
expect(pageLocation).toBe(
|
||||
`/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
|
||||
await mountPage('failed');
|
||||
await flush(() => click('Runs'));
|
||||
await flush(() => click('New Run'));
|
||||
await flush(() => click('Run current settings'));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => click('Cancel'));
|
||||
await flush(() => reply(submitting, run('B', 'pending'), 202));
|
||||
expect(pageLocation).toBe('/backtests/definition/run/A');
|
||||
expect(host.textContent).not.toContain('Submit the current configuration');
|
||||
});
|
||||
|
||||
test('changing the actual run route prevents late submission navigation', async () => {
|
||||
await mountPage('failed');
|
||||
await flush(() => click('Run current settings'));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => {
|
||||
void navigatePage('/backtests/definition/run/B');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed')));
|
||||
await flush(() => reply(submitting, run('C', 'pending'), 202));
|
||||
expect(pageLocation).toBe('/backtests/definition/run/B');
|
||||
expect(requests.some(item => item.path === '/api/v2/runs/C')).toBe(false);
|
||||
});
|
||||
|
||||
test('submission errors remain visible after selecting another run and retry the same intent', async () => {
|
||||
await mountPage('failed');
|
||||
await flush(() => click('Run current settings'));
|
||||
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
await flush(() => {
|
||||
void navigatePage('/backtests/definition/run/B');
|
||||
});
|
||||
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' })));
|
||||
await flush(() => fail(submitting));
|
||||
expect(pageLocation).toBe('/backtests/definition/run/B');
|
||||
expect(host.textContent).toContain('Run submission failed: Network unavailable');
|
||||
expect(host.textContent).toContain('Run failed: B failure');
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(submitting.body);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
|
||||
});
|
||||
|
||||
test('detail retries freeze payload/key across settings edits; acknowledged next intent has a fresh key', async () => {
|
||||
await mount();
|
||||
await loadDefinition();
|
||||
await flush(() => {
|
||||
void latest.createRun(2);
|
||||
void latest.createRun(9);
|
||||
});
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(latest.isSubmitting).toBe(true);
|
||||
await flush(() => fail(first));
|
||||
expect(latest.submissionError).toContain('Network unavailable');
|
||||
await flush(() => {
|
||||
void latest.updateBacktest('definition', { initialCapital: 2000 });
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition', 'PUT'), { ...definition, initialCapital: 2000 })
|
||||
);
|
||||
// A status reader may already have learned the run accepted before the lost response.
|
||||
await selectRunning('A');
|
||||
await flush(() => {
|
||||
void latest.createRun(9);
|
||||
});
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.body).toBe(first.body);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, run('A', 'pending'), 202));
|
||||
expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1);
|
||||
await flush(() => {
|
||||
void latest.createRun(9);
|
||||
});
|
||||
const next = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 });
|
||||
await flush(() => reply(next, run('B', 'pending'), 202));
|
||||
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
|
||||
});
|
||||
|
||||
test('new-run form remains open and submission failure is visible alongside a polling failure', async () => {
|
||||
await mountPage('running');
|
||||
await advance(1000);
|
||||
await flush(() => fail(request('/api/v2/runs/A')));
|
||||
await flush(() => click('Runs'));
|
||||
await flush(() => click('New Run'));
|
||||
await flush(() => {
|
||||
click('Run current settings');
|
||||
click('Run current settings');
|
||||
});
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
await flush(() => reply(first, { error: 'Submission unavailable' }, 503));
|
||||
expect(host.textContent).toContain('Run submission failed');
|
||||
expect(host.textContent).toContain('Network unavailable');
|
||||
expect(host.textContent).toContain('Submit the current configuration');
|
||||
await flush(() => click('Retry submission'));
|
||||
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toBe(first.body);
|
||||
});
|
||||
|
||||
for (const change of ['selection', 'backtest', 'unmount'] as const) {
|
||||
test(`late submission completion cannot navigate or replace newer ${change}`, async () => {
|
||||
await mount();
|
||||
await loadDefinition();
|
||||
let completed: Run | undefined;
|
||||
await flush(() => {
|
||||
void latest.createRun().then(value => {
|
||||
completed = value;
|
||||
});
|
||||
});
|
||||
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
||||
if (change === 'selection') {
|
||||
await selectRunning('B');
|
||||
} else if (change === 'backtest') {
|
||||
await loadDefinition('other');
|
||||
} else {
|
||||
await flush(() => root!.unmount());
|
||||
root = undefined;
|
||||
}
|
||||
const rendered = renders;
|
||||
await flush(() => reply(first, run('A', 'pending'), 202));
|
||||
expect(completed).toBeUndefined();
|
||||
expect(latest.runs.some(item => item.id === 'A')).toBe(false);
|
||||
if (change === 'selection') {
|
||||
expect(latest.currentRun?.id).toBe('B');
|
||||
} else if (change === 'backtest') {
|
||||
expect(latest.backtest?.id).toBe('other');
|
||||
} else {
|
||||
expect(renders).toBe(rendered);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -83,6 +83,7 @@ async function fixture(
|
|||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0, dataset_hash text,
|
||||
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
|
||||
submission_principal text, submission_key text, submission_hash text,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
|
||||
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue