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);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@ import { randomUUID } from 'node:crypto';
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { Pool } from 'pg';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
|
|
@ -21,7 +23,10 @@ import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-d
|
|||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
RunSubmissionConflictError,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
|
@ -74,6 +79,7 @@ async function fixture() {
|
|||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
@ -204,6 +210,216 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
test('idempotent_submission_postgres_race: one snapshot/outbox, canonical null speed and stable original intent after edits', async () => {
|
||||
const f = await fixture();
|
||||
const submission = { principal: 'operator' as const, key: 'same-intent' };
|
||||
const runs = await Promise.all(
|
||||
Array.from({ length: 8 }, (_, i) =>
|
||||
f.api.createRun(
|
||||
{ backtestId: f.definition.id, ...(i % 2 ? { speedMultiplier: null } : {}) },
|
||||
submission
|
||||
)
|
||||
)
|
||||
);
|
||||
expect(new Set(runs.map(run => run.id)).size).toBe(1);
|
||||
const original = await f.snapshot(runs[0]!.id);
|
||||
await f.api.updateBacktest(f.definition.id, {
|
||||
initialCapital: 12345,
|
||||
config: { fastPeriod: 4, slowPeriod: 9 },
|
||||
});
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
runs[0]!.id
|
||||
);
|
||||
expect(await f.snapshot(runs[0]!.id)).toEqual(original);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
await expect(
|
||||
f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 2 }, submission)
|
||||
).rejects.toBeInstanceOf(RunSubmissionConflictError);
|
||||
});
|
||||
|
||||
test('submission_key_conflict: different definitions racing for one principal/key cannot both commit', async () => {
|
||||
const f = await fixture();
|
||||
const second = await f.api.createBacktest(
|
||||
{
|
||||
...f.definition,
|
||||
startDate: f.definition.startDate.toISOString(),
|
||||
endDate: f.definition.endDate.toISOString(),
|
||||
name: 'Second',
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const barrierKey = parseInt(randomUUID().slice(0, 7), 16);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION delay_submission() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
PERFORM pg_advisory_xact_lock_shared(40303, ${barrierKey}); RETURN NEW; END $$;
|
||||
CREATE TRIGGER delay_submission BEFORE INSERT ON runs FOR EACH ROW EXECUTE FUNCTION delay_submission()`);
|
||||
const submission = { principal: 'operator' as const, key: 'cross-definition' };
|
||||
const barrier = await f.pool.connect();
|
||||
await barrier.query('SELECT pg_advisory_lock(40303, $1)', [barrierKey]);
|
||||
const submissions = Promise.allSettled(
|
||||
[f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission))
|
||||
);
|
||||
try {
|
||||
// Both parent-row locks are held, neither run exists yet, and both transactions
|
||||
// are inside their INSERT. Releasing shared waiters forces the unique-index race.
|
||||
await until(
|
||||
async () =>
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT count(*)::int AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 40303 AND objid = $1 AND NOT granted",
|
||||
[barrierKey]
|
||||
)
|
||||
).rows[0].count === 2
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
} finally {
|
||||
await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]);
|
||||
barrier.release();
|
||||
}
|
||||
const outcomes = await submissions;
|
||||
expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1);
|
||||
const rejection = outcomes.find(outcome => outcome.status === 'rejected');
|
||||
expect(rejection?.status === 'rejected' && rejection.reason).toBeInstanceOf(
|
||||
RunSubmissionConflictError
|
||||
);
|
||||
const committed = (await f.pool.query('SELECT * FROM runs')).rows;
|
||||
expect(committed).toHaveLength(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
const otherId = committed[0].backtest_id === f.definition.id ? second.id : f.definition.id;
|
||||
await expect(f.api.createRun({ backtestId: otherId }, submission)).rejects.toBeInstanceOf(
|
||||
RunSubmissionConflictError
|
||||
);
|
||||
});
|
||||
|
||||
test('different principals can reuse keys; concurrent distinct and legacy submissions preserve run numbering', async () => {
|
||||
const f = await fixture();
|
||||
const runs = await Promise.all([
|
||||
f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }),
|
||||
f.api.createRun({ backtestId: f.definition.id }, { principal: 'service', key: 'shared' }),
|
||||
...Array.from({ length: 4 }, (_, i) =>
|
||||
f.api.createRun(
|
||||
{ backtestId: f.definition.id },
|
||||
{ principal: 'operator', key: `intent-${i}` }
|
||||
)
|
||||
),
|
||||
f.api.createRun({ backtestId: f.definition.id }),
|
||||
f.api.createRun({ backtestId: f.definition.id }),
|
||||
]);
|
||||
expect(new Set(runs.map(run => run.id)).size).toBe(8);
|
||||
expect(runs.map(run => run.runNumber).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM runs WHERE submission_key IS NULL')).rows
|
||||
).toHaveLength(2);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(8);
|
||||
});
|
||||
|
||||
test('outbox failure rolls back the submission claim and retry creates exactly one run', async () => {
|
||||
const f = await fixture();
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_submission_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
RAISE EXCEPTION 'injected submission outbox failure'; END $$;
|
||||
CREATE TRIGGER reject_submission_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_submission_outbox()`);
|
||||
const submission = { principal: 'operator' as const, key: 'retry-after-rollback' };
|
||||
await expect(f.api.createRun({ backtestId: f.definition.id }, submission)).rejects.toThrow(
|
||||
'injected submission'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
await f.pool.query('DROP TRIGGER reject_submission_outbox ON backtest_dispatch');
|
||||
const created = await f.api.createRun({ backtestId: f.definition.id }, submission);
|
||||
expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe(
|
||||
created.id
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('save_only route honors autoStart; authenticated keyed submissions return202/Location or409', async () => {
|
||||
const f = await fixture();
|
||||
const app = new Hono();
|
||||
createHttpSecurity({ disabled: true, environment: 'test' }).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const body = { ...f.definition, autoStart: false };
|
||||
expect(
|
||||
(
|
||||
await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: 'false' }),
|
||||
})
|
||||
).status
|
||||
).toBe(400);
|
||||
const saved = await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
expect(saved.status).toBe(201);
|
||||
const definition = await saved.json();
|
||||
expect(await f.api.listRuns(definition.id)).toHaveLength(0);
|
||||
const post = (payload: object) =>
|
||||
app.request(`/api/v2/backtests/${definition.id}/runs`, {
|
||||
method: 'POST',
|
||||
headers: { 'Idempotency-Key': 'route-retry' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const response = await post({});
|
||||
expect(response.status).toBe(202);
|
||||
const run = await response.json();
|
||||
expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`);
|
||||
expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id);
|
||||
expect((await post({ speedMultiplier: 2 })).status).toBe(409);
|
||||
const legacy = await app.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...body, autoStart: undefined }),
|
||||
});
|
||||
expect(await f.api.listRuns((await legacy.json()).id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => {
|
||||
const f = await fixture();
|
||||
const adminToken = 'submission-fixture-admin-not-a-secret-123456';
|
||||
const serviceToken = 'submission-fixture-service-not-a-secret-123456';
|
||||
const app = new Hono();
|
||||
createHttpSecurity({
|
||||
adminToken,
|
||||
serviceToken,
|
||||
browserSessions: true,
|
||||
origins: ['http://ui.test'],
|
||||
}).mount(app);
|
||||
app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger }));
|
||||
const submit = async (headers: Record<string, string>) => {
|
||||
const response = await app.request(`/api/v2/backtests/${f.definition.id}/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Idempotency-Key': 'authenticated-intent',
|
||||
'X-Principal': 'spoofed',
|
||||
...headers,
|
||||
},
|
||||
body: '{}',
|
||||
});
|
||||
expect(response.status).toBe(202);
|
||||
return (await response.json()).id as string;
|
||||
};
|
||||
const original = await submit({ Authorization: `Bearer ${adminToken}` });
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const login = await app.request('/api/auth/session', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' },
|
||||
body: JSON.stringify({ token: adminToken }),
|
||||
});
|
||||
expect(login.status).toBe(200);
|
||||
expect(
|
||||
await submit({
|
||||
Cookie: login.headers.get('Set-Cookie')!.split(';')[0]!,
|
||||
Origin: 'http://ui.test',
|
||||
})
|
||||
).toBe(original);
|
||||
}
|
||||
expect(await submit({ Authorization: `Bearer ${serviceToken}` })).not.toBe(original);
|
||||
expect(
|
||||
(await f.pool.query('SELECT submission_principal FROM runs ORDER BY run_number')).rows
|
||||
).toEqual([{ submission_principal: 'operator' }, { submission_principal: 'service' }]);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => {
|
||||
const f = await fixture();
|
||||
const run = await f.api.createRun({ backtestId: f.definition.id });
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ const migrations = [
|
|||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -130,6 +131,40 @@ async function fixture() {
|
|||
}
|
||||
|
||||
describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
||||
test('submission migration preserves legacy NULL-key runs and enforces complete key records', async () => {
|
||||
const f = await fixture();
|
||||
for (const filename of migrations.filter(name => name !== '14-backtest-submission.sql')) {
|
||||
await f.pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const backtestId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
await f.pool.query(
|
||||
`INSERT INTO backtests (id,name,strategy,symbols,start_date,end_date,initial_capital)
|
||||
VALUES ($1,'Legacy','sma-crossover','["A.US"]','2024-01-01','2024-02-01',10000)`,
|
||||
[backtestId]
|
||||
);
|
||||
await f.pool.query(
|
||||
"INSERT INTO runs (id,backtest_id,run_number,status,request_snapshot) VALUES ($1,$2,1,'completed','{\"legacy\":true}')",
|
||||
[runId, backtestId]
|
||||
);
|
||||
await f.startup().run();
|
||||
const row = (await f.pool.query('SELECT * FROM runs WHERE id = $1', [runId])).rows[0];
|
||||
expect(row.request_snapshot).toEqual({ legacy: true });
|
||||
expect(row.status).toBe('completed');
|
||||
expect([row.submission_principal, row.submission_key, row.submission_hash]).toEqual([
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
]);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET submission_key = 'incomplete' WHERE id = $1", [runId])
|
||||
).rejects.toThrow('runs_submission_complete');
|
||||
await f.startup().run();
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('two_concurrent_startups_same_client_lock and precheck_inside_lock', async () => {
|
||||
const f = await fixture();
|
||||
const firstAtPrecheck = gate();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue