feat(research): add retained-input parameter sweep workbench

This commit is contained in:
Boki 2026-10-24 10:33:05 -04:00
parent 30accfcf43
commit 6f64ef62ba
41 changed files with 4469 additions and 34 deletions

View file

@ -5,6 +5,7 @@ import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { ExperimentDetail, ExperimentPreview } from '@stock-bot/stock-config/experiments';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -30,6 +31,189 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
test('retained_experiment_preview_submit_compare_cancel_and_reopen_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset } = canonicalSmaFixture();
await retainResearchDataset(f.pool, dataset);
const selected = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed canonical fixture for bounded experiments',
});
const definition = {
name: 'Retained sweep template',
strategy: 'catalog',
strategyVersionId: selected.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const backtest = await f.request('/api/v2/backtests', 'POST', {
...definition,
autoStart: false,
});
await f.login();
await f.page.goto(`${f.origin}/backtests/${backtest.id}`);
await f.page.getByRole('link', { name: 'Create experiment', exact: true }).click();
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page.getByLabel('Experiment name', { exact: true }).fill('Retained SMA sweep');
await f.page.getByLabel('Parameter grid (JSON)').fill('{"fastPeriod":[1,2],"slowPeriod":[3]}');
const previewing = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/experiments/preview')
);
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
const previewResponse = await previewing;
expect(previewResponse.status()).toBe(200);
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
expect(preview.candidates).toHaveLength(2);
expect(preview.dataset.hash).toBe(dataset.manifest.hash);
expect(preview.dataset.bounds).toEqual(dataset.manifest.bounds);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
const submitting = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
);
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
const accepted = await submitting;
expect(accepted.status()).toBe(202);
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
expect(accepted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
expect(experiment.trialCount).toBe(2);
expect(experiment.counts.pending).toBe(2);
expect(experiment.trials.map(trial => trial.parameters)).toEqual(
preview.candidates.map(candidate => candidate.parameters)
);
await f.page.waitForURL(`${f.origin}/experiments/${experiment.id}`);
const replay = await f.page.evaluate(
async ({ body, key }) => {
const response = await fetch('/api/v2/experiments', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify(body),
});
return { status: response.status, body: await response.json() };
},
{
body: accepted.request().postDataJSON(),
key: accepted.request().headers()['idempotency-key']!,
}
);
expect(replay.status).toBe(202);
expect(replay.body.experiment.id).toBe(experiment.id);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2);
// Edits after atomic admission cannot change either candidate's economics.
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Changed after sweep admission',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
'2',
'both retained canonical experiment trials complete'
);
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
await visible(f.page, /completed: 2/);
const outcomes = f.page.getByRole('region', { name: 'Experiment trial outcomes' });
expect(await outcomes.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(2);
const completed = (await f.request(`/api/v2/experiments/${experiment.id}`))
.experiment as ExperimentDetail;
expect(completed.counts.completed).toBe(2);
expect(completed.trials.every(trial => trial.comparable && trial.metrics !== null)).toBe(true);
expect(JSON.stringify(completed.trials)).not.toMatch(/"financial"|"sessionReturns"|"fills"/);
for (const [index, trial] of completed.trials.entries()) {
const cell = outcomes.locator('tbody tr').nth(index).locator('td').nth(3);
expect(await cell.textContent()).toBe(String(trial.metrics!.totalReturn));
}
for (const trial of completed.trials) {
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
expect(trial.parameters).toEqual(result.request.strategy.selection.parameters);
expect(result.request.datasetHash).toBe(dataset.manifest.hash);
expect(result.request.build).toEqual(preview.request.build);
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
'10000.00000000'
);
expect(trial.metrics).toEqual(result.analytics.metrics);
expect(trial.unavailable).toEqual(result.analytics.unavailable);
}
const firstRunId = completed.trials[0]!.runId!;
await f.page.locator(`a[href="/backtests/${backtest.id}/run/${firstRunId}"]`).click();
await visible(f.page, 'Canonical research result');
// Experiment linkage belongs to the trial; a standalone reproduction has
// only original-run lineage and retains that trial's frozen parameters.
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
const reproducing = f.page.waitForResponse(response =>
response.url().endsWith(`/runs/${firstRunId}/reproduce`)
);
await f.page.getByRole('button', { name: 'Confirm reproduction', exact: true }).click();
const reproducedResponse = await reproducing;
expect(reproducedResponse.status()).toBe(202);
const reproduced = await reproducedResponse.json();
await f.page.waitForURL(`${f.origin}/backtests/${backtest.id}/run/${reproduced.id}`);
await visible(f.page, 'Economic results match the original.');
expect(
(
await f.pool.query('SELECT experiment_id,original_run_id FROM runs WHERE id=$1', [
reproduced.id,
])
).rows[0]
).toEqual({ experiment_id: null, original_run_id: firstRunId });
await f.page.getByRole('link', { name: 'Experiments', exact: true }).click();
await f.page.getByRole('link', { name: 'Retained SMA sweep', exact: true }).click();
await f.page.reload();
await f.page.getByRole('heading', { name: 'Retained SMA sweep', exact: true }).waitFor();
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
// A second pending batch can be cancelled without touching completed evidence.
await f.dispatcher.shutdown();
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page.getByLabel('Experiment name', { exact: true }).fill('Cancelled sweep');
await f.page.getByLabel('Parameter grid (JSON)').fill('{"slowPeriod":[2,3]}');
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
const cancellingBatch = f.page.waitForResponse(
response =>
response.request().method() === 'POST' && response.url().endsWith('/api/v2/experiments')
);
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
const cancellationBatch = (await (await cancellingBatch).json()).experiment as ExperimentDetail;
await f.page.waitForURL(`${f.origin}/experiments/${cancellationBatch.id}`);
const cancelling = f.page.waitForResponse(response =>
response.url().endsWith(`/experiments/${cancellationBatch.id}/cancel`)
);
await f.page.getByRole('button', { name: 'Cancel remaining trials', exact: true }).click();
expect((await cancelling).status()).toBe(200);
await visible(f.page, /cancelled: 2/);
const cancelled = (await f.request(`/api/v2/experiments/${cancellationBatch.id}`))
.experiment as ExperimentDetail;
expect(cancelled.cancelRequested).toBe(true);
expect(cancelled.counts.cancelled).toBe(2);
expect(cancelled.trials.every(trial => trial.metrics === null)).toBe(true);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
expect((await f.request(`/api/v2/experiments/${experiment.id}`)).experiment).toEqual(completed);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
// Serial by design: the production WebSocket projection has a process-local handler.
test('browser_saved_run_lifecycle', async () => {
const f = await fixture();