stock-bot/test/e2e/workbench.test.ts

1057 lines
51 KiB
TypeScript

import { createHash, randomUUID } from 'node:crypto';
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { chromium, type Browser, type Request } from 'playwright';
import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import {
fixture as createFixture,
createInBrowser,
gate,
retainDataset,
submitInBrowser,
until,
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();
try {
await f.login();
expect(await f.page.locator('tbody tr').count()).toBe(0);
await createInBrowser(f.page, 'Saved browser lifecycle');
const definition = (await f.pool.query('SELECT * FROM backtests')).rows[0];
expect(definition.name).toBe('Saved browser lifecycle');
expect(Number(definition.initial_capital)).toBe(100000);
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: 'Settings', exact: true }).click();
expect(await f.page.locator('input[type="date"]').first().inputValue()).toBe('2024-01-01');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const response = await submitInBrowser(f.page);
expect(response.status()).toBe(202);
const run = await response.json();
expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`);
expect(response.request().headers()['idempotency-key']).toBeTruthy();
await visible(f.page, 'Pending');
await visible(f.page, /Source request \(auto\) — unpinned/);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0);
expect(await f.page.getByRole('combobox').count()).toBe(0);
f.dispatcher.start();
await visible(f.page, 'Running');
await visible(f.page, '25%');
expect(
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
).toContain('Pinned dataset hash');
await until(
() =>
f.frames.some(
frame =>
frame.runId === run.id && frame.type === 'progress' && frame.data?.progress === 25
),
'committed progress WebSocket frame'
);
expect(
Number(
(await f.pool.query('SELECT progress FROM runs WHERE id=$1', [run.id])).rows[0].progress
)
).toBe(25);
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
await visible(f.page, 'Research only · Unverified economics');
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
const result = await f.request(`/api/v2/runs/${run.id}/results`);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
await visible(f.page, result.config.dataset.hash);
expect(await f.page.locator('pre').textContent()).toContain('"initialCapital": 100000');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await visible(f.page, '$100.00');
const savedUrl = f.page.url();
await f.page.reload();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await f.page.getByText('Saved browser lifecycle', { exact: true }).click();
await f.page.getByText('#1', { exact: true }).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
expect(
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])).rowCount
).toBe(1);
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_cancel_failure', async () => {
const f = await fixture();
try {
await f.login();
await createInBrowser(f.page, 'Cancel browser run', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Running');
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');
const acknowledged = f.page.waitForResponse(response =>
response.url().endsWith(`/runs/${runId}/cancel`)
);
await f.page.getByRole('button', { name: 'Cancel run', exact: true }).click();
expect((await acknowledged).status()).toBe(202);
await visible(f.page, 'Cancellation requested. Waiting for the worker to stop.');
expect(
await f.page.getByRole('button', { name: 'Cancellation requested', exact: true }).isDisabled()
).toBe(true);
await f.controlled.stopped.wait('worker cancellation observation');
expect(
(await f.pool.query('SELECT status,cancel_requested FROM runs WHERE id=$1', [runId])).rows[0]
).toEqual({ status: 'running', cancel_requested: true });
f.controlled.cancellation.resolve();
await visible(f.page, 'Run cancelled. No completed results are available.');
expect(
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [runId])).rowCount
).toBe(0);
f.controlled.mode = 'fail';
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await createInBrowser(f.page, 'Failed browser run', true);
await visible(f.page, 'Run failed: Injected fixture worker failure');
const failedId = f.page.url().split('/').at(-1)!;
expect(
(await f.pool.query('SELECT status,error FROM runs WHERE id=$1', [failedId])).rows[0]
).toEqual({ status: 'failed', error: 'Injected fixture worker failure' });
expect(
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [failedId])).rowCount
).toBe(0);
f.controlled.mode = 'empty';
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await createInBrowser(f.page, 'Empty completed browser run', true);
await visible(f.page, 'Completed');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'No trades executed in this backtest.');
const emptyId = f.page.url().split('/').at(-1)!;
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).trades).toEqual([]);
// A saved completed row whose result is unavailable must not appear as zero trades.
const missingResultId = randomUUID();
const definitionId = f.page.url().split('/')[4]!;
await f.pool.query(
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,2,'completed')",
[missingResultId, definitionId]
);
await f.page.goto(f.page.url().replace(emptyId, missingResultId));
await visible(f.page, 'Run completed, but saved results are unavailable.');
await visible(f.page, 'Retry results');
expect(
await f.page.getByText('No trades executed in this backtest.', { exact: true }).count()
).toBe(0);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_reopen_and_switch', async () => {
const f = await fixture();
let delayed: ReturnType<typeof f.delayResponse> | undefined;
const settledRequests = new WeakSet<Request>();
const settled = (request: Request) => {
settledRequests.add(request);
};
f.page.on('requestfinished', settled);
f.page.on('requestfailed', settled);
try {
await f.login();
await createInBrowser(f.page, 'Selection and reconnect', true);
const firstUrl = f.page.url();
const firstId = firstUrl.split('/').at(-1)!;
const definitionId = firstUrl.split('/')[4]!;
f.dispatcher.start();
await visible(f.page, '25%');
await until(
() => f.frames.some(frame => frame.type === 'connected' && frame.runId === firstId),
'initial real WebSocket connection'
);
// Close the actual client socket, then observe an authenticated reconnect and projection.
// Bun 1.2.17 leaks its pending-WebSocket counter on server-initiated close; client close
// exercises the real hook without leaving the fixture listener unable to shut down.
const connections = f.frames.filter(frame => frame.type === 'connected').length;
const reconnectIndex = f.frames.length;
await f.page.evaluate(() =>
(window as unknown as { __disconnectFixtureSockets: () => void }).__disconnectFixtureSockets()
);
await until(
() => f.frames.filter(frame => frame.type === 'connected').length > connections,
'WebSocket reconnect',
15000
);
await until(
() =>
f.frames
.slice(reconnectIndex)
.some(
frame =>
frame.runId === firstId && frame.type === 'progress' && frame.data?.progress === 25
),
'reconnected persisted progress'
);
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
f.controlled.completion = gate();
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await submitInBrowser(f.page);
const secondUrl = f.page.url();
const secondId = secondUrl.split('/').at(-1)!;
expect(secondId).not.toBe(firstId);
await until(
() => f.frames.some(frame => frame.type === 'connected' && frame.runId === secondId),
'second run subscription'
);
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await visible(f.page, '#1');
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
const selectionRequest = f.page.waitForRequest(
request => new URL(request.url()).pathname === `/api/v2/runs/${firstId}/results`
);
await f.page.getByText('#1', { exact: true }).click();
const requested = await selectionRequest;
await delayed.captured.wait('selected run A result request');
await visible(f.page, 'Loading run data...');
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await f.page.getByText('#2', { exact: true }).click();
await visible(f.page, 'Completed');
delayed.release.resolve();
await delayed.delivered.wait('delayed result response settlement');
await until(
() => settledRequests.has(requested),
'browser finished or aborted the old result request'
);
await f.page.evaluate(
() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))
);
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
await visible(f.page, secondId);
expect(f.page.url()).toBe(secondUrl);
expect(await f.page.getByText(firstId, { exact: true }).count()).toBe(0);
// A real missing row, not an invented empty result.
await f.page.goto(`${f.origin}/backtests/${definitionId}/run/${randomUUID()}`);
await visible(f.page, 'Failed to get run: Not Found');
await visible(f.page, 'Retry run');
// Transport failure has a visible retry; restoring the real endpoint recovers.
await f.page.route(`**/api/v2/runs/${secondId}`, route => route.abort('failed'));
await f.page.goto(secondUrl);
await visible(f.page, /Failed to fetch|Load failed/);
await f.page.unroute(`**/api/v2/runs/${secondId}`);
await f.page.getByRole('button', { name: 'Retry run', exact: true }).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(secondUrl);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
f.page.off('requestfinished', settled);
f.page.off('requestfailed', settled);
delayed?.release.resolve();
await f.close();
}
});
test('native_smoke', async () => {
const f = await fixture(true);
try {
await f.login();
await createInBrowser(f.page, 'Actual Rust browser smoke', true);
const runId = f.page.url().split('/').at(-1)!;
f.dispatcher.start();
await visible(f.page, 'Completed');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.engine).toBe('native');
expect(result.config.dataset.barCount).toBe(70);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
expect(result.trades.length).toBeGreaterThan(0);
expect(
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [runId])).rows[0]
).toEqual({ status: 'completed', attempt_number: 1 });
expect(
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])).rowCount
).toBe(1);
await visible(f.page, 'Research only · Unverified economics');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, result.trades[0].side.toUpperCase());
await visible(f.page, `$${result.trades[0].price.toFixed(2)}`);
await f.page.reload();
await visible(f.page, 'Completed');
await f.page
.getByText('Configuration, provenance and simulation limitations', { exact: true })
.click();
await visible(f.page, result.config.dataset.hash);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_frozen_dataset_native_run_and_reopen', async () => {
const f = await fixture(true);
try {
const dataset = await retainDataset(f.pool);
const hash = dataset.manifest.hash;
await f.login();
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await f.page.getByPlaceholder('My Strategy Backtest').fill('Frozen dataset browser run');
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).inputValue()).toBe(
'2024-01-01'
);
expect(await f.page.getByLabel('Start date (UTC)', { exact: true }).isDisabled()).toBe(true);
await f.page.getByRole('button', { name: 'Save and run', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/]+\/run\/[^/]+$/);
const runId = f.page.url().split('/').at(-1)!;
await visible(f.page, 'Pending');
const pending = await f.request(`/api/v2/runs/${runId}`);
expect(pending.dataset).toMatchObject({
requestedHash: hash,
pinnedHash: null,
state: 'requested',
});
expect(
await f.page.getByRole('region', { name: 'Run dataset', exact: true }).textContent()
).toContain(hash);
f.dispatcher.start();
await visible(f.page, 'Completed');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.config.dataset.hash).toBe(hash);
expect(result.engine).toBe('native');
expect(result.trades.length).toBeGreaterThan(0);
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
await visible(f.page, 'Research only · Unverified economics');
const runDataset = f.page.getByRole('region', { name: 'Run dataset', exact: true });
expect(await runDataset.textContent()).toContain('Pinned dataset hash');
await f.page.reload();
await visible(f.page, 'Completed');
expect(await runDataset.textContent()).toContain(hash);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, result.trades[0].side.toUpperCase());
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_intraday_dataset_exact_settings_and_incompatible_submission', async () => {
const f = await fixture();
try {
const startDate = '2024-01-02T13:30:00.123Z';
const endDate = '2024-01-02T15:30:00.456Z';
const dataset = await retainDataset(f.pool, { startDate, endDate, dataFrequency: '1m' });
const hash = dataset.manifest.hash;
await f.login();
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
await f.page.getByPlaceholder('My Strategy Backtest').fill('Exact intraday frozen settings');
await f.page.getByLabel('Historical data input', { exact: true }).selectOption('frozen');
await f.page.getByLabel('Frozen dataset', { exact: true }).selectOption(hash);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
await f.page.waitForURL(/\/backtests\/[^/]+$/);
const backtestId = f.page.url().split('/').at(-1)!;
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe(
startDate
);
expect(await f.page.getByLabel('End instant (UTC)', { exact: true }).inputValue()).toBe(
endDate
);
const saved = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' &&
response.url().endsWith(`/api/v2/backtests/${backtestId}`)
);
await f.page.getByRole('button', { name: 'Save', exact: true }).click();
expect((await saved).status()).toBe(200);
const stored = (
await f.pool.query('SELECT start_date,end_date,config FROM backtests WHERE id=$1', [
backtestId,
])
).rows[0];
expect(stored.start_date.toISOString()).toBe(startDate);
expect(stored.end_date.toISOString()).toBe(endDate);
expect(stored.config.datasetHash).toBe(hash);
expect(stored.config.dataFrequency).toBe('1m');
await f.page.reload();
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByLabel('Start instant (UTC)', { exact: true }).inputValue()).toBe(
startDate
);
// Simulate a template changed outside this browser; API must reject before durable dispatch.
await f.pool.query(
"UPDATE backtests SET config=jsonb_set(config,'{dataFrequency}','\"5m\"') WHERE id=$1",
[backtestId]
);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await f.page.getByRole('button', { name: 'New Run', exact: true }).click();
const rejected = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/api/v2/backtests/${backtestId}/runs`)
);
await f.page.getByRole('button', { name: 'Run current settings', exact: true }).click();
expect((await rejected).status()).toBe(400);
await visible(f.page, /Frozen dataset does not match/);
expect((await f.pool.query('SELECT count(*) FROM runs')).rows[0].count).toBe('0');
expect((await f.pool.query('SELECT count(*) FROM backtest_dispatch')).rows[0].count).toBe('0');
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('browser_archive_retains_history_and_restore_admits_new_work', async () => {
const f = await fixture();
try {
await f.login();
await createInBrowser(f.page, 'Retained browser evidence', true);
const savedUrl = f.page.url();
const runId = savedUrl.split('/').at(-1)!;
const definitionId = savedUrl.split('/')[4]!;
await f.page.getByRole('button', { name: 'Archive backtest', exact: true }).click();
await visible(f.page, 'Confirm archive');
await f.page.getByRole('button', { name: 'Confirm archive', exact: true }).click();
await visible(f.page, 'Restore backtest');
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByPlaceholder('My Strategy Backtest').isDisabled()).toBe(true);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
true
);
await expect(f.request(`/api/v2/backtests/${definitionId}`, 'DELETE')).rejects.toThrow('409');
// Already admitted work still starts, binds its dataset, and completes after archival.
f.dispatcher.start();
await visible(f.page, '25%');
expect(await f.page.getByRole('button', { name: 'Cancel run', exact: true }).isEnabled()).toBe(
true
);
f.controlled.completion.resolve();
await visible(f.page, 'Completed');
const result = await f.request(`/api/v2/runs/${runId}/results`);
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
await f.page.reload();
await visible(f.page, 'Restore backtest');
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'BUY');
expect(f.page.url()).toBe(savedUrl);
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).waitFor();
await until(
async () => (await f.page.locator('tbody tr').count()) === 0,
'default list hides archived template'
);
await f.page.getByRole('checkbox', { name: 'Show archived backtests', exact: true }).check();
await f.page.getByText('Retained browser evidence').click();
await visible(f.page, 'Restore backtest');
await f.page.getByText('#1', { exact: true }).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(savedUrl);
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 f.page.getByRole('button', { name: 'Settings', exact: true }).click();
expect(await f.page.getByPlaceholder('My Strategy Backtest').isEnabled()).toBe(true);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const accepted = await submitInBrowser(f.page);
expect(accepted.status()).toBe(202);
expect((await accepted.json()).id).not.toBe(runId);
expect(
(await f.pool.query('SELECT * FROM runs WHERE backtest_id=$1', [definitionId])).rowCount
).toBe(2);
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
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 eligibility depends on the saved dataset, policy and reviewed executable.'
);
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 eligibility depends on the saved dataset, policy and reviewed executable.'
);
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 eligibility depends on the saved dataset, policy and reviewed executable.'
);
};
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();
}
});
test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_reopen', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const oracle = canonicalSmaFixture();
const retained = await retainResearchDataset(f.pool, oracle.dataset);
const seeded = await f.seedCatalog();
const selected = seeded.find(item => item.package.program.strategyId === 'sma_crossover')!;
expect(selected.reviewStatus).toBe('pending');
await f.login();
await f.page.getByRole('link', { name: 'Research', exact: true }).click();
await visible(f.page, 'No research projects yet. Create a project to begin.');
await f.page.getByRole('button', { name: 'New project', exact: true }).click();
await f.page.getByLabel('Project title', { exact: true }).fill('Trend research');
await f.page.getByLabel('Project description', { exact: true }).fill('Retained SMA evidence');
const creatingProject = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/research-projects')
);
await f.page.getByRole('button', { name: 'Create project', exact: true }).click();
const projectResponse = await creatingProject;
expect(projectResponse.status()).toBe(201);
const { project } = await projectResponse.json();
await f.page.waitForURL(`${f.origin}/research/${project.id}`);
await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).click();
await f.page.getByLabel('Hypothesis title', { exact: true }).fill('AI trend hypothesis');
await f.page
.getByLabel('Proposition', { exact: true })
.fill('A hypothesis, not validated alpha.');
await f.page
.getByLabel('Validation criteria', { exact: true })
.fill('Out-of-sample evidence required.');
await f.page.getByLabel('Declared content origin', { exact: true }).selectOption('ai');
const creatingHypothesis = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/hypotheses`)
);
await f.page.getByRole('button', { name: 'Create hypothesis', exact: true }).click();
const hypothesisResponse = await creatingHypothesis;
expect(hypothesisResponse.status()).toBe(201);
const { hypothesis } = await hypothesisResponse.json();
await visible(f.page, /AI-authored \(declared\).*Submitted by operator.*Unvalidated narrative/);
await f.page.getByLabel('Strategy to link', { exact: true }).selectOption(selected.strategyId);
const linking = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' &&
response
.url()
.endsWith(`/research-projects/${project.id}/strategies/${selected.strategyId}`)
);
await f.page.getByRole('button', { name: 'Link strategy', exact: true }).click();
expect((await linking).status()).toBe(204);
await f.page.locator(`a[href="/strategies/${selected.strategyId}"]`).click();
await f.page.getByLabel('Strategy version', { exact: true }).selectOption(selected.id);
// Approval is an authenticated human review of an immutable built-in, not a run bypass.
await f.page
.getByLabel('Review reason', { exact: true })
.fill('Reviewed retained SMA fixture and next-open oracle.');
const approval = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/strategy-versions/${selected.id}/reviews`)
);
await f.page.getByRole('button', { name: 'Approve built-in version', exact: true }).click();
expect((await approval).status()).toBe(201);
await visible(f.page, /This immutable built-in version has an approval record/);
await f.page.getByLabel('fastPeriod', { exact: true }).fill('2');
await f.page.getByLabel('slowPeriod', { exact: true }).fill('3');
const validate = async () => {
const response = f.page.waitForResponse(
reply =>
reply.request().method() === 'POST' &&
reply.url().endsWith(`/strategy-versions/${selected.id}/validate`)
);
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
expect((await response).status()).toBe(200);
await visible(f.page, /Parameters validated for this immutable version/);
};
await validate();
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('Reviewed canonical browser oracle');
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical draft immutable version'
);
await f.page.locator('input[type="date"]').nth(0).fill('2024-01-01');
await f.page.locator('input[type="date"]').nth(1).fill('2024-01-02');
expect(await f.page.getByLabel('fastPeriod', { exact: true }).inputValue()).toBe('2');
expect(await f.page.getByLabel('slowPeriod', { exact: true }).inputValue()).toBe('3');
await validate();
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 backtestId = f.page.url().split('/').at(-1)!;
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
);
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
await f.page.getByRole('button', { name: 'Configure canonical research', exact: true }).click();
await f.page.getByLabel('Canonical dataset', { exact: true }).selectOption(retained.hash);
await visible(f.page, new Date(retained.bounds.tradeStart).toISOString());
await visible(f.page, new Date(retained.bounds.tradeEnd).toISOString());
await f.page.getByLabel('Initial capital (USD)', { exact: true }).fill('10000');
const policyFields = [
['Owner budget', canonicalSettings.ownerBudget],
['Fee rate', canonicalSettings.feeRate],
['Half-spread rate', canonicalSettings.halfSpreadRate],
['Slippage rate', canonicalSettings.slippageRate],
['Volume participation rate', canonicalSettings.participationRate],
['Order latency (ms)', canonicalSettings.latencyMs],
['Maximum order quantity', canonicalSettings.maxOrderQuantity],
['Maximum position quantity', canonicalSettings.maxPositionQuantity],
['Maximum asset exposure', canonicalSettings.maxSymbolExposure],
['Maximum gross exposure', canonicalSettings.maxGrossExposure],
['Maximum risk-period loss', canonicalSettings.maxDailyLoss],
['Maximum drawdown amount', canonicalSettings.maxDrawdownAmount],
['Maximum mark age (ms)', canonicalSettings.maxMarkAgeMs],
['Random seed', canonicalSettings.seed],
['Reporting periods per year', canonicalSettings.periodsPerYear],
['Annual risk-free rate', canonicalSettings.annualRiskFreeRate],
] as const;
for (const [label, value] of policyFields) {
await f.page.getByLabel(label, { exact: true }).fill(value === null ? '' : String(value));
}
await until(
async () =>
(await f.page.getByLabel('Immutable strategy version', { exact: true }).inputValue()) ===
selected.id,
'canonical setup immutable version'
);
await validate();
const saving = f.page.waitForResponse(
response =>
response.request().method() === 'PUT' && response.url().endsWith(`/backtests/${backtestId}`)
);
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
const savedResponse = await saving;
expect(savedResponse.status()).toBe(200);
const sent = savedResponse.request().postDataJSON();
expect(sent.config).toEqual({
datasetHash: retained.hash,
dataFrequency: '1m',
canonical: canonicalResearchSettingsSchema.parse(canonicalSettings),
});
expect(sent.symbols).toEqual(['X0.US']);
expect(sent.initialCapital).toBe(10000);
expect(sent.startDate).toBe(new Date(retained.bounds.tradeStart).toISOString());
expect(sent.endDate).toBe(new Date(retained.bounds.tradeEnd).toISOString());
expect(sent.strategyVersionId).toBe(selected.id);
expect(sent.strategyParameters).toEqual({ fastPeriod: 2, slowPeriod: 3 });
await visible(f.page, /Canonical execution is available for this saved configuration/);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const accepted = await submitInBrowser(f.page);
expect(accepted.status()).toBe(202);
expect(accepted.request().postDataJSON()).toEqual({ speedMultiplier: null });
const run = await accepted.json();
const admitted = (
await f.pool.query('SELECT request_snapshot,dataset_hash FROM runs WHERE id=$1', [run.id])
).rows[0];
expect(admitted.dataset_hash).toBe(retained.hash);
expect(admitted.request_snapshot.kind).toBe('canonical-research/v1');
expect(admitted.request_snapshot.strategy.versionId).toBe(selected.id);
expect(admitted.request_snapshot.strategy.selection.parameters).toEqual({
fastPeriod: 2,
slowPeriod: 3,
});
expect(admitted.request_snapshot.strategy.package.artifact.sha256).toBe(
selected.package.artifact.sha256
);
await visible(f.page, 'Pending');
f.dispatcher.start();
await visible(f.page, 'Canonical research result');
await visible(f.page, 'Completed');
const result = (await f.request(`/api/v2/runs/${run.id}/results`)) as CanonicalRunResult;
expect(result.kind).toBe('canonical-result/v1');
expect(result.request).toEqual(admitted.request_snapshot);
expect(result.financialEngine).toBe('rust');
expect(String(result.financial.projection.valuation.equity)).toBe('9969.30000000');
expect(String(result.financial.projection.valuation.fees)).toBe('0.70000000');
expect(
result.financial.projection.fills.map(fill => [
fill.side,
String(fill.quantity),
String(fill.price),
String(fill.fee.amount),
])
).toEqual([
['buy', '10.00000000', '5.00000000', '0.50000000'],
['sell', '10.00000000', '2.00000000', '0.20000000'],
]);
expect(result.analytics.metrics.roundTripCount).toBeNull();
await visible(f.page, '9969.30000000');
await visible(f.page, 'Unavailable — unsupported round trips');
const provenance = f.page.getByRole('region', {
name: 'Canonical result provenance',
exact: true,
});
expect(await provenance.textContent()).toContain(selected.id);
expect(await provenance.textContent()).toContain(retained.hash);
expect(await provenance.textContent()).toContain(selected.package.artifact.sha256);
expect(await provenance.textContent()).toContain(result.request.build.engineBinarySha256);
expect(
await f.page.getByText('Research only · Unverified economics', { exact: true }).count()
).toBe(0);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.page.locator('tbody tr').count()).toBe(2);
await visible(f.page, '0.50000000');
await visible(f.page, '0.20000000');
const completedUrl = f.page.url();
await f.page.reload();
await visible(f.page, 'Canonical research result');
await visible(f.page, '9969.30000000');
expect(f.page.url()).toBe(completedUrl);
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
await visible(f.page, 'Canonical fills (2)');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
const stored = (
await f.pool.query(
'SELECT canonical_result,metrics,trades FROM backtest_results WHERE run_id=$1',
[run.id]
)
).rows[0];
expect(stored.canonical_result).toEqual(result);
expect(stored.metrics).toBeNull();
expect(stored.trades).toBeNull();
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
// Citations are resolved from the persisted canonical result, never copied browser metrics.
await f.page.getByRole('button', { name: 'Save finding', exact: true }).click();
const dialog = f.page.getByRole('dialog', { name: 'Save finding', exact: true });
await dialog.getByLabel('Finding project', { exact: true }).selectOption(project.id);
await dialog
.getByLabel('Finding hypothesis', { exact: true })
.selectOption(hypothesis.latestRevision.id);
await dialog.getByLabel('Finding title', { exact: true }).fill('SMA fixture finding');
await dialog
.getByLabel('Finding body', { exact: true })
.fill('Costs and losses require further validation.');
await dialog.getByLabel('Round Trip Count', { exact: true }).check();
const creatingFinding = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/research-projects/${project.id}/analysis-artifacts`)
);
await dialog.getByRole('button', { name: 'Save finding', exact: true }).click();
const findingResponse = await creatingFinding;
expect(findingResponse.status()).toBe(201);
const submitted = findingResponse.request().postDataJSON();
expect(submitted.evidence).toEqual([
{
runId: run.id,
metricsVersion: 'canonical-analytics/v1',
strategyVersionId: selected.id,
metricPath: 'analytics.metrics.totalReturn',
},
{
runId: run.id,
metricsVersion: 'canonical-analytics/v1',
strategyVersionId: selected.id,
metricPath: 'analytics.metrics.roundTripCount',
},
]);
const { artifact } = await findingResponse.json();
expect(artifact.hypothesisRevisionId).toBe(hypothesis.latestRevision.id);
expect(artifact.latestRevision.evidence[0].value).toBe(result.analytics.metrics.totalReturn);
expect(artifact.latestRevision.evidence[1].value).toBeNull();
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
await f.page.waitForURL(`${f.origin}/research/${project.id}?artifact=${artifact.id}`);
const evidence = f.page.getByRole('region', { name: 'Referenced measurements', exact: true });
await evidence.waitFor({ state: 'visible' });
expect(await evidence.textContent()).toContain('Unavailable — unsupported round trips');
expect(await evidence.textContent()).toContain('Unit: fraction');
expect(await evidence.textContent()).toContain(
`Raw value: ${result.analytics.metrics.totalReturn}`
);
expect(await evidence.textContent()).toContain(retained.hash);
expect(
await evidence
.getByRole('link', { name: 'Open cited run', exact: true })
.first()
.getAttribute('href')
).toBe(`/backtests/${backtestId}/run/${run.id}`);
expect(
await evidence
.getByRole('link', { name: 'Open cited strategy version', exact: true })
.first()
.getAttribute('href')
).toBe(`/strategies/versions/${selected.id}`);
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
await f.page
.getByLabel('Revision body', { exact: true })
.fill('Revised conclusion; original evidence retained.');
const revising = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
);
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
expect((await revising).status()).toBe(201);
await f.page.getByRole('button', { name: 'View revision 2', exact: true }).waitFor();
await visible(f.page, 'Revised conclusion; original evidence retained.');
const history = await f.request(`/api/v2/analysis-artifacts/${artifact.id}/revisions`);
expect(history.revisions).toHaveLength(2);
expect(history.revisions[0].evidence).toEqual(history.revisions[1].evidence);
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
await visible(f.page, 'Costs and losses require further validation.');
await visible(f.page, 'Immutable history: this revision is read-only.');
await f.page.reload();
await visible(f.page, 'Costs and losses require further validation.');
await f.page.getByRole('link', { name: 'Open exact hypothesis revision', exact: true }).click();
await f.page.waitForURL(
`${f.origin}/research/${project.id}?hypothesis=${hypothesis.id}&revision=${hypothesis.latestRevision.id}`
);
await visible(f.page, /AI-authored \(declared\).*Unvalidated narrative/);
await f.page.getByRole('button', { name: 'Archive project', exact: true }).click();
await visible(f.page, 'Archived project: research entries are read-only.');
expect(await f.page.getByRole('button', { name: 'New note', exact: true }).count()).toBe(0);
expect(await f.page.getByRole('button', { name: 'New hypothesis', exact: true }).count()).toBe(
0
);
await f.page.getByRole('button', { name: 'SMA fixture finding', exact: true }).click();
await visible(f.page, 'Revised conclusion; original evidence retained.');
await evidence.getByRole('link', { name: 'Open cited run', exact: true }).first().click();
await f.page.waitForURL(completedUrl);
await visible(f.page, '9969.30000000');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});