feat(research): add strategy catalog and versioned backtest setup

This commit is contained in:
Boki 2026-10-23 21:11:59 -04:00
parent 8cca0ee588
commit d929db707a
44 changed files with 4198 additions and 209 deletions

View file

@ -3,7 +3,7 @@ import { EventEmitter } from 'node:events';
import { readFileSync } from 'node:fs';
import type { ServerWebSocket } from 'bun';
import { Pool } from 'pg';
import { chromium, type Page } from 'playwright';
import type { Browser, Page } from 'playwright';
import { createHttpSecurity } from '@stock-bot/di';
import { HandlerRegistry } from '@stock-bot/handler-registry';
import type { IServiceContainer } from '@stock-bot/handlers';
@ -27,10 +27,12 @@ import {
handleWebSocketConnection,
} from '../../apps/stock/web-api/src/routes/websocket.routes';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import {
getWebSocketHandler,
type RunSocketData,
} from '../../apps/stock/web-api/src/websocket/run-updates';
import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('browser-fixture');
@ -214,7 +216,7 @@ class FixtureEngine extends EventEmitter {
}
}
export async function fixture(native = false) {
export async function fixture(browser: Browser, native = false) {
const database = process.env.PIPELINE_TEST_DATABASE_URL;
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
if (
@ -285,7 +287,9 @@ export async function fixture(native = false) {
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -399,6 +403,8 @@ export async function fixture(native = false) {
(!pathname.startsWith('/api/v2/backtests') &&
!pathname.startsWith('/api/v2/runs') &&
!pathname.startsWith('/api/v2/datasets') &&
!pathname.startsWith('/api/v2/strategies') &&
!pathname.startsWith('/api/v2/strategy-versions') &&
pathname !== '/api/auth/session') ||
/\/(pause|resume|speed)$/.test(pathname)
) {
@ -458,9 +464,8 @@ export async function fixture(native = false) {
}
});
const origin = `http://127.0.0.1:${server.port}`;
const browser = await chromium.launch({ headless: true });
cleanup.push(() => browser.close());
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
cleanup.push(() => context.close());
await context.route('**/*', route => {
const url = new URL(route.request().url());
if (url.origin !== origin && !['data:', 'blob:'].includes(url.protocol)) {
@ -520,10 +525,19 @@ export async function fixture(native = false) {
await target.getByRole('button', { name: 'Sign in', exact: true }).click();
await visible(target, 'Create and manage backtest configurations');
};
const request = async (path: string, method = 'GET', body?: unknown) => {
const request = async (
path: string,
method = 'GET',
body?: unknown,
headers: Record<string, string> = {}
) => {
const response = await fetch(origin + path, {
method,
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
...headers,
},
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) {
@ -546,6 +560,7 @@ export async function fixture(native = false) {
login,
close,
unexpectedNetwork,
seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)),
};
} catch (error) {
try {
@ -560,7 +575,7 @@ export async function fixture(native = false) {
export async function createInBrowser(page: Page, name: string, run = false) {
await page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await page.getByPlaceholder('My Strategy Backtest').fill(name);
await page.locator('select').first().selectOption('moving-average');
await page.getByLabel('Legacy strategy', { exact: true }).selectOption('moving-average');
await page.locator('input[type="date"]').nth(0).fill('2024-01-01');
await page.locator('input[type="date"]').nth(1).fill('2024-03-15');
await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click();

View file

@ -1,9 +1,9 @@
import { randomUUID } from 'node:crypto';
import { expect, test } from 'bun:test';
import type { Request } from 'playwright';
import { createHash, randomUUID } from 'node:crypto';
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
fixture as createFixture,
createInBrowser,
fixture,
gate,
retainDataset,
submitInBrowser,
@ -11,6 +11,18 @@ import {
visible,
} from './fixture';
// Repeated launch/close cycles lost Chromium's control pipe under Bun 1.2.17.
// Keep one suite-owned process; each fixture still owns
// a fresh context, server, database schema and queue. No retries hide failures.
let browser: Browser;
beforeAll(async () => {
browser = await chromium.launch({ headless: true });
});
afterAll(async () => {
await browser?.close();
});
const fixture = (native = false) => createFixture(browser, native);
// Serial by design: the production WebSocket projection has a process-local handler.
test('browser_saved_run_lifecycle', async () => {
const f = await fixture();
@ -479,3 +491,213 @@ test('browser_archive_retains_history_and_restore_admits_new_work', async () =>
await f.close();
}
});
test('browser_catalog_version_parameters_clone_and_saved_draft', async () => {
const f = await fixture();
f.page.on('dialog', dialog => void dialog.accept());
try {
await f.login();
await f.page.goto(`${f.origin}/strategies`);
await visible(f.page, /No strategies found/);
await f.page.getByRole('button', { name: 'New strategy', exact: true }).click();
await f.page.getByLabel('Strategy name', { exact: true }).fill('Browser research family');
await f.page
.getByLabel('Strategy description', { exact: true })
.fill('A hypothesis awaiting evidence.');
await f.page.getByRole('button', { name: 'Create strategy', exact: true }).click();
await f.page.waitForURL(/\/strategies\/[^/]+$/);
await visible(f.page, /No immutable versions have been published/);
await f.page
.getByLabel('Strategy description', { exact: true })
.fill('Revised hypothesis, still unvalidated.');
await f.page.getByRole('button', { name: 'Save metadata', exact: true }).click();
await until(
async () =>
(await f.request('/api/v2/strategies')).strategies[0]?.description ===
'Revised hypothesis, still unvalidated.',
'saved strategy metadata'
);
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
const versionUrl = `${f.origin}/strategies/${selected.strategyId}/versions/${selected.id}`;
await f.page.goto(versionUrl);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('20');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('10');
const invalid = f.page.waitForResponse(response =>
response.url().endsWith(`/strategy-versions/${selected.id}/validate`)
);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
expect((await invalid).status()).toBe(400);
expect(
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
).toBe(true);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('5');
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
);
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).click();
await f.page.waitForURL(
url =>
url.pathname === '/backtests' && url.searchParams.get('strategyVersionId') === selected.id
);
await f.page.getByPlaceholder('My Strategy Backtest').fill('Pinned version browser draft');
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'loaded exact immutable version selection'
);
expect(
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
).toBe(selected.id);
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
await f.page.locator('input[type="date"]').nth(1).fill('2024-03-15');
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('5');
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
);
expect(
await f.page.getByRole('button', { name: 'Save and run', exact: true }).isDisabled()
).toBe(true);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/?]+$/);
const draftUrl = f.page.url();
const draftId = draftUrl.split('/').at(-1)!;
const saved = await f.request(`/api/v2/backtests/${draftId}`);
expect(saved.strategy).toBe('catalog');
expect(saved.strategyVersionId).toBe(selected.id);
expect(saved.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 5 });
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
await expect(f.request(`/api/v2/backtests/${draftId}/runs`, 'POST', {})).rejects.toThrow('409');
// A later immutable publication must never move the saved selection to the newest version.
const { package: retained } = await f.request(
`/api/v2/strategy-versions/${selected.id}/artifact`
);
const changed = structuredClone(retained);
changed.artifact.content +=
'\n/* </pre><script>globalThis.__catalogBrowserExecuted=true</script> */\nglobalThis.__catalogBrowserExecuted=true;';
changed.artifact.sha256 = createHash('sha256').update(changed.artifact.content).digest('hex');
const revision = await f.request(
`/api/v2/strategies/${selected.strategyId}/versions`,
'POST',
{ package: changed },
{ 'Idempotency-Key': randomUUID() }
);
await f.page.reload();
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'loaded exact immutable version selection'
);
expect(
await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()
).toBe(selected.id);
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
const validateVisibleParameters = async () => {
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
await visible(
f.page,
'Parameters validated for this immutable version. Execution remains unavailable.'
);
};
const saveVisibleSettings = async () => {
const update = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${draftId}`)
);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
const response = await update;
expect(response.status()).toBe(200);
const updated = await response.json();
expect(updated.strategyVersionId).toBe(selected.id);
expect(updated.config).not.toHaveProperty('speedMultiplier');
return updated;
};
await f.page.getByLabel('fastPeriod', { exact: true }).fill('3');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('7');
await validateVisibleParameters();
expect((await saveVisibleSettings()).strategyParameters).toEqual({
fastPeriod: 3,
slowPeriod: 7,
});
// Archive/restore replaces authoritative settings; stale validated child state must reset too.
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
await validateVisibleParameters();
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
await visible(f.page, 'Restore backtest');
await f.page.getByRole('button', { name: 'Restore backtest', exact: true }).click();
await f.page.getByRole('button', { name: 'Confirm restore', exact: true }).click();
await visible(f.page, 'Archive backtest');
await until(
async () => (await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()) === '3',
'restored saved parameter state'
);
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('7');
expect(await f.page.getByRole('button', { name: 'Save', exact: true }).isDisabled()).toBe(true);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('4');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('9');
await validateVisibleParameters();
expect((await saveVisibleSettings()).strategyParameters).toEqual({
fastPeriod: 4,
slowPeriod: 9,
});
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
expect(f.page.url()).toBe(draftUrl);
await f.page.goto(
`${f.origin}/strategies/${selected.strategyId}/versions/${revision.version.id}`
);
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
await visible(f.page, 'Different artifact bytes');
expect(
await f.page.getByLabel('Selected bundled JavaScript', { exact: true }).textContent()
).toContain('__catalogBrowserExecuted');
expect(await f.page.evaluate(() => Object.hasOwn(globalThis, '__catalogBrowserExecuted'))).toBe(
false
);
await f.page.goto(versionUrl);
await f.page.getByRole('button', { name: 'Clone version', exact: true }).click();
await f.page.getByLabel('Clone name', { exact: true }).fill('Browser candidate clone');
const cloned = f.page.waitForResponse(response =>
response.url().endsWith(`/strategy-versions/${selected.id}/clone`)
);
await f.page.getByRole('button', { name: 'Create clone', exact: true }).click();
const cloneResponse = await cloned;
expect(cloneResponse.status()).toBe(201);
const clone = await cloneResponse.json();
expect(clone.version.parentVersionId).toBe(selected.id);
expect(clone.version.origin).toBe('candidate');
expect(clone.version.reviewStatus).toBe('pending');
expect(clone.version.runnable).toBe(false);
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${clone.version.id}`));
await f.page.getByLabel('Compare with version', { exact: true }).selectOption(selected.id);
await visible(f.page, 'Identical artifact bytes');
await f.page.reload();
await f.page.getByLabel('Strategy version', { exact: true }).waitFor();
expect(await f.page.getByLabel('Strategy version', { exact: true }).inputValue()).toBe(
clone.version.id
);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});