feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -45,6 +45,13 @@ const timers = new Map<
{ at: number; delay: number; callback: () => void; repeat: boolean }
>();
function submittedBody(request: { body?: string }): string {
if (typeof request.body !== 'string') {
throw new Error('Submission body is missing');
}
return request.body;
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: Error) => void;
@ -68,7 +75,9 @@ 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}`);
if (!found) {
throw new Error(`No pending ${method} ${path}`);
}
return found;
}
function reply(pending: Request, body: unknown, status = 200) {
@ -115,18 +124,21 @@ const results = (id: string): RunResult => ({
winRate: 0,
totalTrades: 0,
profitFactor: null,
avgWin: 0,
avgLoss: 0,
},
equity: [],
ohlcData: {},
positions: [],
trades: [],
analytics: {},
analytics: { exposureTime: null },
executionTime: 0,
});
const definition = {
id: 'definition',
name: 'Fixture',
strategy: 'sma',
strategy: 'catalog',
strategyVersionId: 'version-one',
symbols: ['A.US'],
startDate: '2024-01-01',
endDate: '2024-02-01',
@ -174,9 +186,13 @@ async function advance(ms: number) {
const due = [...timers].filter(([, timer]) => timer.at <= now);
await flush(() => {
for (const [id, timer] of due) {
if (!timers.has(id)) continue;
if (!timers.has(id)) {
continue;
}
timers.delete(id);
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
if (timer.repeat) {
timers.set(id, { ...timer, at: now + timer.delay });
}
timer.callback();
}
});
@ -187,7 +203,9 @@ function click(label: string) {
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}`);
if (!button) {
throw new Error(`Missing button ${label}`);
}
button.click();
}
function HookHost({ socket = false }: { socket?: boolean }) {
@ -196,7 +214,9 @@ function HookHost({ socket = false }: { socket?: boolean }) {
useWebSocket({
runId: socket ? (latest.currentRun?.id ?? null) : null,
onMessage: message => {
if (message.type !== 'pong') void latest.refreshRun(message.runId);
if (message.type !== 'pong') {
void latest.refreshRun(message.runId);
}
},
});
return latest.currentRun
@ -210,7 +230,13 @@ function HookHost({ socket = false }: { socket?: boolean }) {
}
async function mount(element: ReactElement = createElement(HookHost)) {
root = createRoot(host);
await flush(() => root!.render(element));
await flush(() =>
root!.render(
element.type === CreateBacktestDialog
? createElement(router.MemoryRouter, null, element)
: element
)
);
}
async function select(id: string) {
await flush(() => {
@ -260,8 +286,9 @@ beforeAll(async () => {
WebSocket: TestSocket,
ResizeObserver: browser.ResizeObserver,
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'
@ -291,6 +318,9 @@ beforeEach(() => {
host = browser.document.createElement('div') as unknown as HTMLDivElement;
browser.document.body.append(host as never);
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
if (new URL(String(input)).pathname.endsWith('/canonical-capability')) {
return Promise.resolve(Response.json({ available: true, reason: null }));
}
const pending: Request = {
...deferred<Response>(),
path: new URL(String(input)).pathname,
@ -304,10 +334,12 @@ beforeEach(() => {
requests.push(pending);
// Deliberately ignore abort: guards must also reject a late server continuation.
return pending.promise;
}) as typeof browser.fetch;
}) as unknown 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);
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;
@ -315,16 +347,22 @@ beforeEach(() => {
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);
if (!timers.delete(id)) {
realClearTimeout(id);
}
}) as typeof clearTimeout;
globalThis.clearInterval = ((id: number) => {
if (!timers.delete(id)) realClearInterval(id);
if (!timers.delete(id)) {
realClearInterval(id);
}
}) as typeof clearInterval;
});
afterEach(async () => {
let leakedTimers = 0;
try {
if (root) await flush(() => root!.unmount());
if (root) {
await flush(() => root!.unmount());
}
leakedTimers = timers.size;
} finally {
root = undefined;
@ -343,8 +381,11 @@ afterAll(async () => {
} finally {
for (const key of globals) {
const descriptor = savedGlobals.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
if (descriptor) {
Object.defineProperty(globalThis, key, descriptor);
} else {
Reflect.deleteProperty(globalThis, key);
}
}
}
});
@ -607,6 +648,45 @@ describe('actual detail page result states', () => {
});
async function nameBacktest() {
const family = { id: 'family', name: 'Test strategy', archived: false };
const version = {
id: 'version-one',
strategyId: 'family',
ordinal: 1,
origin: 'builtin',
package: {
parameterSchema: {
type: 'object',
properties: {},
required: [],
additionalProperties: false,
},
},
};
await flush(() => reply(request('/api/v2/strategies'), { strategies: [family] }));
const choose = (label: string, value: string) => {
const select = host.querySelector(`select[aria-label="${label}"]`)!;
Object.getOwnPropertyDescriptor(browser.HTMLSelectElement.prototype, 'value')!.set!.call(
select,
value
);
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
};
await flush(() => choose('Strategy family', 'family'));
await flush(() => reply(request('/api/v2/strategies/family/versions'), { versions: [version] }));
await flush(() => choose('Immutable strategy version', 'version-one'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one'), { version, reviews: [] })
);
await flush(() => reply(request('/api/v2/strategies/family'), { strategy: family }));
await flush(() => click('Validate parameters'));
await flush(() =>
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
parameters: {},
runnable: false,
reason: 'Configure canonical settings',
})
);
await flush(() => {
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
@ -643,175 +723,109 @@ describe('explicit save and repeat-safe run submission', () => {
});
const saving = request('/api/v2/backtests', 'POST');
expect(JSON.parse(saving.body!).autoStart).toBe(false);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
).toHaveLength(1);
await flush(() => reply(saving, definition));
expect(created).toEqual([definition]);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(
requests.filter(item => item.path.endsWith('/runs') && item.method === 'POST')
).toHaveLength(0);
});
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') }]);
});
}
test('new dialog cannot submit legacy or unconfigured execution', async () => {
await mount(createElement(CreateBacktestDialog, { onClose: () => {}, onCreated: () => {} }));
expect(host.querySelector('[aria-label="Strategy mode"]')).toBeNull();
await nameBacktest();
await flush(() => click('Save and run'));
expect(requests.some(item => item.path === '/api/v2/backtests' && item.method === 'POST')).toBe(
false
);
expect(host.textContent).toContain('financial policies before running');
});
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('dialog unmount during save ignores late completion and navigation', async () => {
let navigated = false;
await mount(
createElement(CreateBacktestDialog, {
onClose: () => {},
onCreated: () => {
navigated = true;
},
})
);
await nameBacktest();
await flush(() => click('Save'));
await flush(() => root!.unmount());
root = undefined;
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
expect(navigated).toBe(false);
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
false
);
});
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
test('save rejects double clicks and close while pending, then navigates to configure', 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(LocationProbe)
)
);
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('Save');
click('Save');
click('Close backtest dialog');
click('Close');
});
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')
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'POST')
).toHaveLength(1);
expect(pageLocation).toBe('/backtests');
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();
expect(pageLocation).toBe('/backtests/definition');
expect(requests.some(item => item.path.endsWith('/runs') && item.method === 'POST')).toBe(
false
);
});
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('legacy template stays readable but never creates a new run', async () => {
await mount();
await flush(() => {
void latest.loadBacktest('definition');
});
}
await flush(() => {
reply(request('/api/v2/backtests/definition'), {
...definition,
strategy: 'sma',
strategyVersionId: null,
});
reply(request('/api/v2/backtests/definition/runs'), []);
});
await flush(() => {
void latest.createRun();
});
expect(latest.submissionError).toContain('Legacy execution is retired');
expect(requests.some(item => item.method === 'POST')).toBe(false);
expect(latest.backtest?.name).toBe('Fixture');
});
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
await mountPage('failed');
@ -852,7 +866,7 @@ describe('explicit save and repeat-safe run submission', () => {
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(submittedBody(retry)).toBe(submittedBody(submitting));
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
});
@ -880,7 +894,7 @@ describe('explicit save and repeat-safe run submission', () => {
void latest.createRun(9);
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
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);
@ -889,7 +903,7 @@ describe('explicit save and repeat-safe run submission', () => {
});
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 });
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: null });
await flush(() => reply(next, run('B', 'pending'), 202));
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
});
@ -913,7 +927,7 @@ describe('explicit save and repeat-safe run submission', () => {
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);
expect(submittedBody(retry)).toBe(submittedBody(first));
});
for (const change of ['selection', 'backtest', 'unmount'] as const) {
@ -1051,7 +1065,7 @@ describe('template archive and restore', () => {
void latest.createRun(9);
});
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'completed'), 202));
expect(latest.hasPendingSubmission).toBe(false);
@ -1074,7 +1088,7 @@ describe('template archive and restore', () => {
});
const fresh = request('/api/v2/backtests/definition/runs', 'POST');
expect(fresh.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: 9 });
expect(JSON.parse(fresh.body!)).toEqual({ speedMultiplier: null });
await flush(() => reply(fresh, run('B', 'pending'), 202));
expect(latest.runResults).toBe(savedResults);
});
@ -1090,7 +1104,7 @@ describe('template archive and restore', () => {
expect(button('Retry submission').disabled).toBe(false);
await flush(() => click('Retry submission'));
const retry = request('/api/v2/backtests/definition/runs', 'POST');
expect(retry.body).toBe(first.body);
expect(submittedBody(retry)).toBe(submittedBody(first));
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
await flush(() => reply(retry, run('A', 'running'), 202));
expect(button('Run current settings').disabled).toBe(true);
@ -1132,6 +1146,9 @@ describe('template archive and restore', () => {
409
)
);
if (typeof failure !== 'string') {
throw new Error('Expected a retained-history refusal');
}
expect(failure).toContain('Archive it');
expect(latest.error).toBe(failure);
expect(latest.backtest?.id).toBe('definition');