stock-bot/test/integration/backtest-run-controls.test.tsx

573 lines
21 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 type {
Run,
RunResult,
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
// Local to this file: no global preload, browser server or second test runner.
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const globals = ['window', 'document', 'WebSocket', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const savedGlobals = new Map(
globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
);
const realTimeout = globalThis.setTimeout;
const realClearTimeout = globalThis.clearTimeout;
const realInterval = globalThis.setInterval;
const realClearInterval = globalThis.clearInterval;
let createRoot: typeof import('react-dom/client').createRoot;
let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2;
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 router: typeof import('react-router-dom');
let root: Root | undefined;
let host: HTMLDivElement;
let latest: ReturnType<typeof useBacktestV2>;
let renders = 0;
let now = 0;
let timerId = 0;
const timers = new Map<
number,
{ at: number; delay: number; callback: () => void; repeat: boolean }
>();
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
const promise = new Promise<T>((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
type Request = ReturnType<typeof deferred<Response>> & {
path: string;
method: string;
signal?: AbortSignal | null;
settled: boolean;
};
const requests: Request[] = [];
function request(path: string, method = 'GET') {
const found = requests.find(
item => item.path === path && item.method === method && !item.settled
);
if (!found) throw new Error(`No pending ${method} ${path}`);
return found;
}
function reply(pending: Request, body: unknown, status = 200) {
pending.settled = true;
pending.resolve(Response.json(body, { status }));
}
function fail(pending: Request) {
pending.settled = true;
pending.reject(new Error('Network unavailable'));
}
const run = (id: string, status: Run['status'] = 'running', extra: Partial<Run> = {}): Run => ({
id,
backtestId: 'definition',
runNumber: 1,
status,
speedMultiplier: null,
progress: 0,
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
...extra,
});
const results = (id: string): RunResult => ({
runId: id,
backtestId: 'definition',
engine: 'typescript',
status: 'completed',
completedAt: '2024-02-01',
config: {
name: 'Fixture',
strategy: 'sma',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
initialCapital: 1000,
commission: 0,
slippage: 0,
dataFrequency: '1d',
parameters: {},
},
metrics: {
totalReturn: 0,
sharpeRatio: null,
maxDrawdown: 0,
winRate: 0,
totalTrades: 0,
profitFactor: null,
},
equity: [],
ohlcData: {},
positions: [],
trades: [],
analytics: {},
executionTime: 0,
});
const definition = {
id: 'definition',
name: 'Fixture',
strategy: 'sma',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
initialCapital: 1000,
config: {},
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
};
class TestSocket {
static OPEN = 1;
static CONNECTING = 0;
static instances: TestSocket[] = [];
readyState = 0;
onopen: (() => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
constructor(readonly url: string) {
TestSocket.instances.push(this);
}
send() {}
open() {
this.readyState = 1;
this.onopen?.();
}
close() {
this.readyState = 3;
this.onclose?.();
}
message(value: unknown) {
this.onmessage?.({ data: JSON.stringify(value) });
}
}
async function flush(action: () => void = () => {}) {
await act(async () => {
action();
await Promise.resolve();
});
}
async function advance(ms: number) {
now += ms;
const due = [...timers].filter(([, timer]) => timer.at <= now);
await flush(() => {
for (const [id, timer] of due) {
if (!timers.has(id)) continue;
timers.delete(id);
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
timer.callback();
}
});
}
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
);
if (!button) throw new Error(`Missing button ${label}`);
button.click();
}
function HookHost({ socket = false }: { socket?: boolean }) {
latest = useBacktestV2();
renders++;
useWebSocket({
runId: socket ? (latest.currentRun?.id ?? null) : null,
onMessage: message => {
if (message.type !== 'pong') void latest.refreshRun(message.runId);
},
});
return latest.currentRun
? createElement(RunControlsCompact, {
run: latest.currentRun,
cancelRequested: latest.cancelRequested,
onCancel: latest.cancelRun,
onRerun: () => {},
})
: null;
}
async function mount(element: ReactElement = createElement(HookHost)) {
root = createRoot(host);
await flush(() => root!.render(element));
}
async function select(id: string) {
await flush(() => {
void latest.selectRun(id);
});
}
async function selectRunning(id = 'A', status: Run['status'] = 'running') {
await select(id);
await flush(() => reply(request(`/api/v2/runs/${id}`), run(id, status)));
}
async function mountPage(status: Run['status']) {
await mount(
createElement(
router.MemoryRouter,
{ initialEntries: ['/backtests/definition/run/A'] },
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/backtests/:id/run/:runId',
element: createElement(BacktestDetailPageV2),
})
)
)
);
await flush(() => {
reply(request('/api/v2/backtests/definition'), definition);
reply(request('/api/v2/backtests/definition/runs'), []);
reply(
request('/api/v2/runs/A'),
run('A', status, status === 'failed' ? { error: 'Fixture failure' } : {})
);
});
}
beforeAll(async () => {
for (const [key, value] of Object.entries({
window: browser,
document: browser.document,
WebSocket: TestSocket,
IS_REACT_ACT_ENVIRONMENT: true,
}))
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
({ createRoot } = await import('react-dom/client'));
({ useBacktestV2 } = await import(
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
));
({ useWebSocket } = await import('../../apps/stock/web-app/src/hooks/useWebSocket'));
({ RunControlsCompact } = await import(
'../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'
));
({ BacktestDetailPageV2 } = await import(
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
));
router = await import('react-router-dom');
});
beforeEach(() => {
requests.length = 0;
TestSocket.instances.length = 0;
renders = 0;
now = 0;
timers.clear();
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
const pending: Request = {
...deferred<Response>(),
path: new URL(String(input)).pathname,
method: init?.method ?? 'GET',
signal: init?.signal,
settled: false,
};
requests.push(pending);
// Deliberately ignore abort: guards must also reject a late server continuation.
return pending.promise;
}) as typeof browser.fetch;
const schedule = (repeat: boolean, original: typeof setTimeout) =>
((callback: () => void, delay?: number, ...args: unknown[]) => {
if (![1000, 3000, 30000].includes(delay ?? 0)) return original(callback, delay, ...args);
const id = ++timerId;
timers.set(id, { at: now + delay!, delay: delay!, callback, repeat });
return id;
}) as typeof setTimeout;
globalThis.setTimeout = schedule(false, realTimeout);
globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval;
globalThis.clearTimeout = ((id: number) => {
if (!timers.delete(id)) realClearTimeout(id);
}) as typeof clearTimeout;
globalThis.clearInterval = ((id: number) => {
if (!timers.delete(id)) realClearInterval(id);
}) as typeof clearInterval;
});
afterEach(async () => {
let leakedTimers = 0;
try {
if (root) await flush(() => root!.unmount());
leakedTimers = timers.size;
} finally {
root = undefined;
globalThis.setTimeout = realTimeout;
globalThis.clearTimeout = realClearTimeout;
globalThis.setInterval = realInterval;
globalThis.clearInterval = realClearInterval;
timers.clear();
host?.remove();
}
expect(leakedTimers).toBe(0);
});
afterAll(async () => {
try {
await browser.happyDOM.close();
} finally {
for (const key of globals) {
const descriptor = savedGlobals.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
describe('run selection and persisted status authority', () => {
for (const lateFailure of [false, true]) {
test(`stale_status_response: A ${lateFailure ? 'error' : 'success'}/finally cannot replace B loading`, async () => {
await mount();
await select('A');
const previous = request('/api/v2/runs/A');
await select('B');
expect(previous.signal?.aborted).toBe(true);
await flush(() => (lateFailure ? fail(previous) : reply(previous, run('A'))));
expect(latest.currentRun).toBeNull();
expect(latest.isLoading).toBe(true);
expect(latest.error).toBeNull();
await flush(() => reply(request('/api/v2/runs/B'), run('B')));
expect(latest.currentRun?.id).toBe('B');
expect(latest.isLoading).toBe(false);
expect(polls()).toBe(1);
});
test(`stale_results_response: A ${lateFailure ? 'error' : 'success'} cannot replace B results`, async () => {
await mount();
await select('A');
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
const previous = request('/api/v2/runs/A/results');
await select('B');
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'completed')));
await flush(() => reply(request('/api/v2/runs/B/results'), results('B')));
await flush(() => (lateFailure ? fail(previous) : reply(previous, results('A'))));
expect(previous.signal?.aborted).toBe(true);
expect(latest.currentRun?.id).toBe('B');
expect(latest.runResults?.runId).toBe('B');
expect(latest.error).toBeNull();
expect(polls()).toBe(0);
});
}
test('one_poll_in_flight: invalidations coalesce, slow requests do not overlap, polling recovers', async () => {
await mount();
await selectRunning();
await advance(1000);
const first = request('/api/v2/runs/A');
await advance(10000);
await flush(() => {
void latest.refreshRun('A');
void latest.refreshRun('A');
});
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(2);
await flush(() => reply(first, run('A', 'running', { progress: 20 })));
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(3);
await flush(() => fail(request('/api/v2/runs/A')));
expect(latest.error).toContain('Network unavailable');
expect(latest.currentRun?.progress).toBe(20);
expect(polls()).toBe(1);
await advance(1000);
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
expect(latest.error).toBeNull();
expect(latest.runResults?.runId).toBe('A');
expect(polls()).toBe(0);
});
test('stale results error/finally does not clear the newer selection loading state', async () => {
await mount();
await select('A');
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
const previous = request('/api/v2/runs/A/results');
await select('B');
await flush(() => fail(previous));
expect(latest.isLoading).toBe(true);
expect(latest.error).toBeNull();
expect(latest.currentRun).toBeNull();
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed')));
expect(latest.currentRun?.id).toBe('B');
expect(latest.isLoading).toBe(false);
});
test('no_publish_after_unmount also ignores a late initial status failure', async () => {
await mount();
await select('A');
const pending = request('/api/v2/runs/A');
await flush(() => root!.unmount());
root = undefined;
const before = renders;
await flush(() => fail(pending));
expect(pending.signal?.aborted).toBe(true);
expect(renders).toBe(before);
expect(timers.size).toBe(0);
});
test('no_publish_after_unmount: abort results and remove pending poll/subscription work', async () => {
await mount(createElement(HookHost, { socket: true }));
await selectRunning();
const socket = TestSocket.instances[0]!;
await flush(() => socket.open());
await advance(1000);
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
const pending = request('/api/v2/runs/A/results');
await flush(() => root!.unmount());
root = undefined;
const before = renders;
await flush(() => reply(pending, results('A')));
await advance(30000);
expect(pending.signal?.aborted).toBe(true);
expect(socket.readyState).toBe(3);
expect(renders).toBe(before);
expect(timers.size).toBe(0);
});
for (const initial of ['pending', 'running'] as const) {
test(`pending_vs_active_cancel: ${initial} acknowledgement is not invented completion`, async () => {
await mount();
await selectRunning('A', initial);
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
expect(latest.currentRun?.status).toBe(initial);
const acknowledged = initial === 'pending' ? 'cancelled' : 'running';
await flush(() =>
reply(request('/api/v2/runs/A'), run('A', acknowledged, { cancelRequested: true }))
);
expect(latest.currentRun?.status).toBe(acknowledged);
if (initial === 'running') {
expect(latest.cancelRequested).toBe(true);
expect(host.textContent).toContain('Cancellation requested');
await advance(1000);
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
}
expect(host.textContent).toContain('Cancelled');
expect(latest.cancelRequested).toBe(false);
expect(latest.runResults).toBeNull();
expect(polls()).toBe(0);
});
}
test('late cancel failure cannot change a newer selection', async () => {
await mount();
await selectRunning();
await flush(() => click('Cancel run'));
const pending = request('/api/v2/runs/A/cancel', 'POST');
await selectRunning('B');
await flush(() => fail(pending));
expect(latest.currentRun?.id).toBe('B');
expect(latest.cancelRequested).toBe(false);
expect(latest.error).toBeNull();
});
test('failed cancellation is retriable and a racing persisted completion wins', async () => {
await mount();
await selectRunning();
await flush(() => click('Cancel run'));
await flush(() => fail(request('/api/v2/runs/A/cancel', 'POST')));
expect(latest.cancelRequested).toBe(false);
expect(latest.error).toContain('Network unavailable');
await flush(() => click('Cancel run'));
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
expect(latest.currentRun?.status).toBe('completed');
expect(latest.cancelRequested).toBe(false);
expect(latest.error).toBeNull();
expect(latest.runResults?.runId).toBe('A');
expect(polls()).toBe(0);
});
test('unsupported_controls: server pause/resume/speed are absent for running and paused runs', async () => {
await mount();
await selectRunning();
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
'Cancel run',
'Rerun',
]);
await selectRunning('B', 'paused');
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
'Cancel run',
'Rerun',
]);
});
test('reconnect_or_poll_recovery: reconnect refetches persisted state and old sockets cannot publish', async () => {
await mount(createElement(HookHost, { socket: true }));
await selectRunning();
const first = TestSocket.instances[0]!;
await flush(() => first.open());
const lateMessage = first.onmessage!;
await flush(() => first.close());
await advance(3000);
expect(TestSocket.instances).toHaveLength(2);
const second = TestSocket.instances[1]!;
await flush(() => {
second.open();
second.message({ type: 'connected', runId: 'A' });
});
// The websocket invalidation coalesces with the already due fallback poll.
expect(requests.filter(item => !item.settled && item.path === '/api/v2/runs/A')).toHaveLength(
1
);
await selectRunning('B');
const count = requests.length;
await flush(() => lateMessage({ data: JSON.stringify({ type: 'completed', runId: 'A' }) }));
expect(requests).toHaveLength(count);
expect(latest.currentRun?.id).toBe('B');
expect(second.readyState).toBe(3);
});
});
describe('actual detail page result states', () => {
test('detail cancel control is wired to durable cancellation, not chart playback', async () => {
await mountPage('running');
await flush(() => click('Cancel run'));
expect(host.textContent).toContain('Cancellation requested');
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), {}, 202));
expect(host.textContent).not.toContain('Run cancelled');
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
expect(host.textContent).toContain('Run cancelled');
expect(host.textContent).not.toContain('No trades executed');
});
for (const status of ['failed', 'cancelled'] as const) {
test(`${status} is not successful zero-trade data`, async () => {
await mountPage(status);
await flush(() => click('Trades'));
expect(host.textContent).toContain(
status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled'
);
expect(host.textContent).not.toContain('No trades executed');
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
});
}
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
await mountPage('completed');
expect(host.textContent).toContain('Loading run data');
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
await flush(() => click('Trades'));
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
expect(host.textContent).toContain('saved results are unavailable');
expect(host.textContent).not.toContain('No trades executed');
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
await flush(() => click('Retry results'));
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
expect(host.textContent).toContain('No trades executed in this backtest.');
expect(host.textContent).not.toContain('saved results are unavailable');
});
test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => {
await mountPage('completed');
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
const evidence = host.querySelector('[aria-label="Result provenance and limitations"]');
expect(evidence).not.toBeNull();
expect(evidence!.textContent).toContain('Research only · Unverified economics');
const details = evidence!.querySelector('details')!;
await flush(() => details.querySelector('summary')!.click());
expect(details.open).toBe(true);
expect(evidence!.textContent).toContain('Stored run configuration: Unknown');
expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API');
expect(host.textContent).toContain('Performance');
});
});