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

2412 lines
115 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 type {
ChronologicalValidationActionResult,
ChronologicalValidationDetail,
ChronologicalValidationPreview,
ChronologicalValidationReport,
} from '@stock-bot/stock-config/chronological-validation';
import {
costScenarioSchema,
type CostSensitivityDetail,
type CostSensitivityPreview,
} from '@stock-bot/stock-config/cost-sensitivity';
import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison';
import type {
ExperimentDetail,
ExperimentPreview,
ExperimentRetryResult,
ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import type {
WalkForwardActionResult,
WalkForwardDetail,
WalkForwardPreview,
} from '@stock-bot/stock-config/walk-forward';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import { chronologicalDataset } from '../fixtures/chronological-validation';
import { walkForwardDataset } from '../fixtures/walk-forward';
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);
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_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 version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed saved comparison fixture',
});
const definition = {
name: 'Saved comparison template',
strategy: 'catalog',
strategyVersionId: version.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,
});
const costInput = {
backtestId: backtest.id,
name: 'Older cost experiment',
scenarios: [
{ feeRate: '0.02', slippageRate: '0' },
{ feeRate: '0.01', slippageRate: '0.02' },
],
};
const { preview: costPreview } = (await f.request(
'/api/v2/experiments/cost-sensitivity/preview',
'POST',
costInput
)) as { preview: CostSensitivityPreview };
const { experiment: costs } = (await f.request(
'/api/v2/experiments/cost-sensitivity',
'POST',
{ ...costInput, previewHash: costPreview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: CostSensitivityDetail };
const parameterInput = {
backtestId: backtest.id,
name: 'Newer parameter experiment',
grid: { fastPeriod: [1, 2] },
};
const { preview } = (await f.request(
'/api/v2/experiments/preview',
'POST',
parameterInput
)) as { preview: ExperimentPreview };
const { experiment: parameters } = (await f.request(
'/api/v2/experiments',
'POST',
{ ...parameterInput, previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: ExperimentDetail };
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
.n === 5,
'five native cost and parameter trials complete'
);
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Mutable template changed after execution',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'revoke',
reason: 'Historical reads must not require current admission approval',
});
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
const durableCounts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
(SELECT count(*)::int FROM research_experiments) AS experiments,
(SELECT sum(manual_retry_count)::int FROM runs) AS retries`)
).rows[0];
const before = await durableCounts();
const query = new URLSearchParams({ leftId: costs.id, rightId: parameters.id });
const endpoint = `/api/v2/experiments/compare?${query}`;
const { comparison } = (await f.request(endpoint)) as { comparison: ExperimentComparison };
expect(comparison.selection.referenceTrialKey).toBe(costs.trials[0]!.trialKey);
expect(comparison.rows.map(row => row.differences)).toEqual([[], ['costs'], ['costs'], [], []]);
expect(comparison.rows.map(row => row.ready)).toEqual([true, false, false, true, true]);
for (const experiment of comparison.experiments) {
for (const trial of experiment.trials) {
const result = (await f.request(
`/api/v2/runs/${trial.runId}/results`
)) as CanonicalRunResult;
expect(result.financialEngine).toBe('rust');
expect(trial.metrics).toEqual(result.analytics.metrics);
expect(trial.unavailable).toEqual(result.analytics.unavailable);
}
}
await f.login();
await f.page.goto(`${f.origin}/experiments`);
// Click order, rather than the newest-first list, chooses the explicit left reference.
await f.page.getByLabel(`Select ${costs.name} for comparison`, { exact: true }).check();
await f.page.getByLabel(`Select ${parameters.name} for comparison`, { exact: true }).check();
await f.page.getByRole('link', { name: 'Compare selected experiments', exact: true }).click();
await f.page.getByRole('heading', { name: 'Compare experiments', exact: true }).waitFor();
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(new URL(f.page.url()).searchParams.get('leftId')).toBe(costs.id);
expect(new URL(f.page.url()).searchParams.get('rightId')).toBe(parameters.id);
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
costs.trials[0]!.trialKey
);
expect(await f.page.getByText('Matching settings', { exact: true }).count()).toBe(3);
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(2);
expect(await f.page.getByText('Saved summary available', { exact: true }).count()).toBe(5);
for (const experiment of comparison.experiments) {
for (const trial of experiment.trials) {
const row = f.page.locator(
`tr:has(a[href="/backtests/${backtest.id}/run/${trial.runId}"])`
);
expect(await row.count()).toBe(1);
expect(await row.innerText()).toContain(String(trial.metrics!.totalReturn));
}
}
const referenceKey = costs.trials[1]!.trialKey;
const changedRead = f.page.waitForResponse(response => {
const url = new URL(response.url());
return (
url.pathname === '/api/v2/experiments/compare' &&
url.searchParams.get('referenceTrialKey') === referenceKey
);
});
await f.page.getByLabel('Reference trial', { exact: true }).selectOption(referenceKey);
const response = await changedRead;
expect(response.status()).toBe(200);
const changed = (await response.json()) as { comparison: ExperimentComparison };
expect(changed.comparison.rows.map(row => row.differences)).toEqual([
['costs'],
[],
['costs'],
['costs'],
['costs'],
]);
await until(
async () => (await f.page.getByText('Matching settings', { exact: true }).count()) === 1,
'explicit cost reference replaces comparison'
);
expect(new URL(f.page.url()).searchParams.get('referenceTrialKey')).toBe(referenceKey);
const savedUrl = f.page.url();
await f.page.reload();
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
referenceKey
);
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(4);
await f.page
.locator(`a[href="/backtests/${backtest.id}/run/${costs.trials[1]!.runId}"]`)
.click();
await visible(f.page, 'Canonical research result');
await f.page.goto(savedUrl);
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
referenceKey
);
expect(await durableCounts()).toEqual(before);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing_experiment_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 version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed native cost sensitivity fixture',
});
const definition = {
name: 'Fixed cost study template',
strategy: 'catalog',
strategyVersionId: version.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}/experiments?backtestId=${backtest.id}`);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page
.getByLabel('Experiment name', { exact: true })
.fill('Fixed fee and slippage study');
await f.page.getByLabel('Experiment type').selectOption({ label: 'Cost sensitivity' });
expect(await f.page.getByLabel('Parameter grid').isVisible()).toBe(false);
await f.page.getByLabel('Scenario 1 fee rate', { exact: true }).fill('0.02');
await f.page.getByLabel('Scenario 1 slippage rate', { exact: true }).fill('0');
await f.page.getByRole('button', { name: 'Add cost scenario', exact: true }).click();
await f.page.getByLabel('Scenario 2 fee rate', { exact: true }).fill('0.01');
await f.page.getByLabel('Scenario 2 slippage rate', { exact: true }).fill('0.02');
const preparing = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/experiments/cost-sensitivity/preview')
);
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
const prepared = await preparing;
expect(prepared.status()).toBe(200);
const { preview } = (await prepared.json()) as { preview: CostSensitivityPreview };
expect(preview.version).toBe('cost-sensitivity-preview/v1');
expect(preview.source.input.grid).toEqual({});
expect(preview.candidates.map(candidate => candidate.costs)).toEqual([
{ feeRate: '0.01000000', slippageRate: '0.00000000' },
{ feeRate: '0.02000000', slippageRate: '0.00000000' },
{ feeRate: '0.01000000', slippageRate: '0.02000000' },
]);
expect(
preview.candidates.every(
candidate =>
JSON.stringify(candidate.parameters) === JSON.stringify(definition.strategyParameters)
)
).toBe(true);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
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/cost-sensitivity')
);
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
const submitted = await submitting;
expect(submitted.status()).toBe(202);
const { experiment } = (await submitted.json()) as { experiment: CostSensitivityDetail };
expect(submitted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
expect(experiment.preview).toEqual(preview);
expect(experiment.kind).toBe('cost-sensitivity');
expect(experiment.trialCount).toBe(3);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(3);
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Edited after cost admission',
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
initialCapital: 20000,
config: {
...definition.config,
canonical: { ...canonicalSettings, feeRate: '0.3', slippageRate: '0.4' },
},
});
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
.n === 3,
'all three fixed-input cost scenarios complete through the native runner'
);
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
await visible(f.page, /completed: 3/);
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(3);
const outcomes = f.page.locator('section[aria-label="Experiment trial outcomes"] tbody tr');
expect(await outcomes.count()).toBe(3);
for (const [index, trial] of experiment.trials.entries()) {
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
const expected = structuredClone(preview.request);
expected.runId = trial.runId!;
expected.policy.matching.risk.ledger.sessionId = trial.runId!;
expected.policy.matching.risk.ledger.accountId = `research:${trial.runId}`;
const costs = costScenarioSchema.parse(trial.costs);
expected.policy.matching.risk.feeRate = costs.feeRate;
expected.policy.matching.slippageRate = costs.slippageRate;
expect(result.request).toEqual(expected);
expect(result.financialEngine).toBe('rust');
expect(result.financial.policy).toEqual(expected.policy);
expect(result.financial.identity).toEqual({
version: 1,
sessionId: trial.runId!,
datasetHash: expected.datasetHash,
});
const text = await outcomes.nth(index).innerText();
expect(text).toContain(index === 0 ? 'Baseline' : `Scenario ${index}`);
expect(text).toContain(trial.costs.feeRate);
expect(text).toContain(trial.costs.slippageRate);
expect(text).toContain(String(result.analytics.metrics.totalReturn));
}
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
const replay = (await f.request(
'/api/v2/experiments/cost-sensitivity',
'POST',
submitted.request().postDataJSON(),
{ 'Idempotency-Key': submitted.request().headers()['idempotency-key']! }
)) as { experiment: CostSensitivityDetail };
expect(replay.experiment.id).toBe(experiment.id);
expect(replay.experiment.preview).toEqual(preview);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
await f.page.reload();
await visible(f.page, /completed: 3/);
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
await visible(f.page, /completed: 3/);
await f.page
.locator(`a[href="/backtests/${backtest.id}/run/${experiment.trials[2]!.runId}"]`)
.click();
await visible(f.page, 'Canonical research result');
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset, windows } = walkForwardDataset();
await retainResearchDataset(f.pool, dataset);
const version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed bounded walk-forward native browser fixture',
});
const definition = {
name: 'Walk-forward native template',
strategy: 'catalog',
strategyVersionId: version.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}/experiments?backtestId=${backtest.id}`);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page.getByLabel('Experiment name', { exact: true }).fill('Frozen rolling windows');
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
await f.page.getByText('Walk-forward validation', { exact: true }).click();
for (const [index, recipe] of windows.entries()) {
for (const phase of ['Train', 'Validation', 'Test'] as const) {
const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
for (const [label, value] of [
['warmup start', window.warmupStart],
['trading start', window.tradeStart],
['trading end', window.tradeEnd],
] as const) {
await f.page
.getByLabel(`Window ${index + 1} ${phase} ${label} (UTC)`, { exact: true })
.fill(new Date(value).toISOString());
}
}
}
const preparing = f.page.waitForResponse(r =>
r.url().endsWith('/api/v2/experiments/walk-forward/preview')
);
await f.page.getByRole('button', { name: 'Preview walk-forward', exact: true }).click();
const prepared = await preparing;
expect(prepared.status()).toBe(200);
const { preview } = (await prepared.json()) as { preview: WalkForwardPreview };
expect(preview.input.windows).toEqual(windows);
expect(preview.counts).toEqual({
windows: 2,
trainingRuns: 4,
holdoutRuns: 4,
totalRuns: 8,
maxRuns: 100,
});
expect((await f.pool.query('SELECT * FROM research_walk_forwards')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
const submitting = f.page.waitForResponse(
r => r.request().method() === 'POST' && r.url().endsWith('/api/v2/experiments/walk-forward')
);
await f.page.getByRole('button', { name: 'Submit walk-forward training', exact: true }).click();
const accepted = await submitting;
expect(accepted.status()).toBe(202);
const { walkForward: initial } = (await accepted.json()) as { walkForward: WalkForwardDetail };
const endpoint = `/api/v2/experiments/walk-forward/${initial.id}`;
const route = `${f.origin}/experiments/walk-forward/${initial.id}`;
expect(accepted.headers().location).toBe(endpoint);
expect(initial.preview).toEqual(preview);
expect(initial.windows.map(w => w.index)).toEqual([0, 1]);
expect(
initial.windows.every(w => w.status === 'admitted' && w.validation?.selection === null)
).toBe(true);
expect(initial.actions.finalize.available).toBe(false);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(4);
await f.page.waitForURL(route);
// Every member already owns its frozen source before any native training starts.
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Edited after frozen series',
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 ===
'4',
'all training windows complete'
);
const childReports: ChronologicalValidationReport[] = [];
for (const member of initial.windows) {
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
await f.page
.getByRole('link', { name: `Open window ${member.index + 1} validation`, exact: true })
.click();
await f.page.waitForURL(`${f.origin}/experiments/validation/${member.validationId}`);
const selecting = f.page.waitForResponse(r =>
r.url().endsWith(`/validation/${member.validationId}/select`)
);
await f.page
.getByRole('button', { name: 'Freeze selection and run holdouts', exact: true })
.click();
const selectionResponse = await selecting;
expect(selectionResponse.status()).toBe(202);
const selected = (await selectionResponse.json()) as ChronologicalValidationActionResult;
const holdoutIds = selected.validation.phases
.slice(1)
.map(p => p.experiment!.trials[0]!.runId!);
await until(
async () =>
(
await f.pool.query(
"SELECT count(*) FROM runs WHERE id=ANY($1::uuid[]) AND status='completed'",
[holdoutIds]
)
).rows[0].count === '2',
'member holdouts complete'
);
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
const finalizing = f.page.waitForResponse(r =>
r.url().endsWith(`/validation/${member.validationId}/finalize`)
);
await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click();
const memberResponse = await finalizing;
expect(memberResponse.status()).toBe(202);
const memberResult = (await memberResponse.json()) as ChronologicalValidationActionResult;
childReports.push(memberResult.validation.report!);
await visible(f.page, 'Execution complete · report saved');
await f.page.goto(route);
await visible(f.page, 'Frozen rolling windows');
const state = (await f.request(endpoint)).walkForward as WalkForwardDetail;
expect(state.reportedWindowCount).toBe(member.index + 1);
if (member.index === 0) {
expect(state.actions.finalize.available).toBe(false);
expect(
await f.page
.getByRole('button', { name: 'Save walk-forward report', exact: true })
.isDisabled()
).toBe(true);
}
}
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [backtest.id]);
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
await f.page.getByRole('button', { name: 'Refresh walk-forward', exact: true }).click();
const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`));
await f.page.getByRole('button', { name: 'Save walk-forward report', exact: true }).click();
const response = await finalizing;
expect(response.status()).toBe(202);
const completed = (await response.json()) as WalkForwardActionResult;
const report = completed.walkForward.report!;
expect(completed.receipt.id).toBe(report.id);
expect(completed.receipt.reportHash).toBe(report.reportHash);
expect(report.reset).toBe('initial-capital-empty-positions');
expect(report.segments).toHaveLength(2);
for (const [index, segment] of report.segments.entries()) {
const child = childReports[index]!;
expect(segment.index).toBe(index);
expect(segment.validationId).toBe(initial.windows[index]!.validationId);
expect(segment.reportId).toBe(child.id);
expect(segment.reportHash).toBe(child.reportHash);
expect(segment.selectionHash).toBe(child.selectionHash);
expect(segment.validation).toEqual(child.validation);
expect(segment.test).toEqual(child.test);
const result = (await f.request(
`/api/v2/runs/${segment.test.runId}/results`
)) as CanonicalRunResult;
expect(segment.test.metrics).toEqual(result.analytics.metrics);
expect(segment.test.unavailable).toEqual(result.analytics.unavailable);
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
'10000.00000000'
);
}
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(6);
await visible(f.page, 'Execution complete · walk-forward report saved');
const replay = (await f.request(
`${endpoint}/finalize`,
'POST',
response.request().postDataJSON(),
{ 'Idempotency-Key': response.request().headers()['idempotency-key']! }
)) as WalkForwardActionResult;
expect(replay.receipt).toEqual(completed.receipt);
expect(replay.walkForward.report).toEqual(report);
const submitReplay = await f.request(
'/api/v2/experiments/walk-forward',
'POST',
accepted.request().postDataJSON(),
{ 'Idempotency-Key': accepted.request().headers()['idempotency-key']! }
);
expect(submitReplay.walkForward.id).toBe(initial.id);
await f.page.reload();
await visible(f.page, 'Execution complete · walk-forward report saved');
expect((await f.request(endpoint)).walkForward.report).toEqual(report);
await f.page.goto(`${f.origin}/experiments`);
await visible(f.page, 'Saved walk-forward validations');
await f.page.locator(`a[href="/experiments/walk-forward/${initial.id}"]`).click();
await visible(f.page, 'Execution complete · walk-forward report saved');
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
}, 60_000);
test('chronological_preflight_checks_explicit_windows_without_admitting_or_saving_work_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset, recipe, start, minute } = chronologicalDataset();
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 chronological preflight fixture',
});
const backtest = await f.request('/api/v2/backtests', 'POST', {
name: 'Chronological preflight 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,
},
autoStart: false,
});
const evidence = async () =>
(
await f.pool.query(
`SELECT (SELECT count(*) FROM backtest_datasets) AS datasets,
(SELECT count(*) FROM research_experiments) AS experiments,
(SELECT count(*) FROM runs) AS runs,
(SELECT count(*) FROM backtest_dispatch) AS dispatch,
(SELECT count(*) FROM backtest_results) AS results,
(SELECT row_to_json(b) FROM backtests b WHERE id=$1) AS template`,
[backtest.id]
)
).rows[0];
const before = await evidence();
await f.login();
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('Chronological input check');
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
for (const phase of ['Train', 'Validation', 'Test'] as const) {
const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
await f.page
.getByLabel(`${phase} warmup start (UTC)`, { exact: true })
.fill(new Date(window.warmupStart).toISOString());
await f.page
.getByLabel(`${phase} trading start (UTC)`, { exact: true })
.fill(new Date(window.tradeStart).toISOString());
await f.page
.getByLabel(`${phase} trading end (UTC)`, { exact: true })
.fill(new Date(window.tradeEnd).toISOString());
}
const prepare = async () => {
const reply = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/experiments/validation/preview')
);
await f.page
.getByRole('button', { name: 'Preview chronological validation', exact: true })
.click();
return reply;
};
const response = await prepare();
expect(response.status()).toBe(200);
const { preview } = (await response.json()) as { preview: ChronologicalValidationPreview };
expect(response.request().postDataJSON().recipe).toEqual(recipe);
expect(preview.execution).toBe('preview-only');
expect(preview.source.dataset.hash).toBe(dataset.manifest.hash);
expect(preview.partitions.map(partition => partition.phase)).toEqual([
'train',
'validation',
'test',
]);
expect(preview.source.candidates).toHaveLength(2);
const preparedInputs = f.page.getByRole('region', {
name: 'Prepared chronological inputs',
exact: true,
});
await visible(f.page, 'Exact chronological preview inputs and policies');
await f.page
.getByText('Exact chronological preview inputs and policies', { exact: true })
.click();
expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
await visible(f.page, /Previewing does not save datasets, experiments or runs/);
for (const partition of preview.partitions) {
await visible(f.page, partition.dataset.hash);
expect(partition.requiredWarmup).toBe(4);
}
expect(await evidence()).toEqual(before);
// Structurally valid bounds with too few available warmup observations reject explicitly.
await f.page
.getByLabel('Train warmup start (UTC)', { exact: true })
.fill(new Date(start + 4 * minute).toISOString());
expect(await preparedInputs.count()).toBe(0);
const invalid = await prepare();
expect(invalid.status()).toBe(400);
const failure = (await invalid.json()) as { error: string };
await visible(f.page, failure.error);
await f.page
.getByLabel('Train warmup start (UTC)', { exact: true })
.fill(new Date(recipe.train.warmupStart).toISOString());
const repeated = await prepare();
expect(repeated.status()).toBe(200);
expect((await repeated.json()).preview.previewHash).toBe(preview.previewHash);
await visible(f.page, 'Exact chronological preview inputs and policies');
await f.page
.getByText('Exact chronological preview inputs and policies', { exact: true })
.click();
expect(await preparedInputs.locator('pre').textContent()).toContain(preview.previewHash);
await f.page.getByLabel('Experiment name', { exact: true }).fill('Changed input');
expect(await preparedInputs.count()).toBe(0);
await f.page.reload();
await visible(f.page, /No experiments yet/);
expect(await preparedInputs.count()).toBe(0);
expect(await evidence()).toEqual(before);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('durable_chronological_training_fixed_holdouts_report_and_reopen_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset, recipe } = chronologicalDataset();
await retainResearchDataset(f.pool, dataset);
const version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
const approve = () =>
f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed chronological durable browser fixture',
});
await approve();
const definition = {
name: 'Chronological durable template',
strategy: 'catalog',
strategyVersionId: version.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}/experiments?backtestId=${backtest.id}`);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page
.getByLabel('Experiment name', { exact: true })
.fill('Frozen chronological research');
await f.page.getByLabel('Parameter grid').fill('{"fastPeriod":[1,2]}');
for (const phase of ['Train', 'Validation', 'Test'] as const) {
const window = recipe[phase.toLowerCase() as 'train' | 'validation' | 'test'];
for (const [label, value] of [
['warmup start', window.warmupStart],
['trading start', window.tradeStart],
['trading end', window.tradeEnd],
] as const) {
await f.page
.getByLabel(`${phase} ${label} (UTC)`, { exact: true })
.fill(new Date(value).toISOString());
}
}
const previewing = f.page.waitForResponse(r =>
r.url().endsWith('/api/v2/experiments/validation/preview')
);
await f.page
.getByRole('button', { name: 'Preview chronological validation', exact: true })
.click();
const { preview } = (await (await previewing).json()) as {
preview: ChronologicalValidationPreview;
};
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
const submitting = f.page.waitForResponse(
r => r.request().method() === 'POST' && r.url().endsWith('/api/v2/experiments/validation')
);
await f.page.getByRole('button', { name: 'Submit training runs', exact: true }).click();
const accepted = await submitting;
expect(accepted.status()).toBe(202);
const { validation: admitted } = (await accepted.json()) as {
validation: ChronologicalValidationDetail;
};
const endpoint = `/api/v2/experiments/validation/${admitted.id}`;
expect(accepted.headers().location).toBe(endpoint);
expect(admitted.preview).toEqual(preview);
expect(admitted.selection).toBeNull();
expect(admitted.report).toBeNull();
expect(admitted.phases.map(p => p.status)).toEqual([
'admitted',
'not-admitted',
'not-admitted',
]);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(1);
await f.page.waitForURL(`${f.origin}/experiments/validation/${admitted.id}`);
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
// Holdouts must retain the original recipe despite subsequent template edits and approval changes.
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Changed template',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
await approve();
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
'2',
'training finishes through native durable runner'
);
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
const selecting = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/select`));
await f.page
.getByRole('button', { name: 'Freeze selection and run holdouts', exact: true })
.click();
const selectionResponse = await selecting;
expect(selectionResponse.status()).toBe(202);
const selected = (await selectionResponse.json()) as ChronologicalValidationActionResult;
expect(selected.receipt.operation).toBe('select-and-admit-holdouts');
expect(selected.receipt.id).toBe(selected.validation.selection!.id);
expect(selected.validation.selection!.training).toHaveLength(2);
expect(selected.validation.phases.map(p => p.status)).toEqual([
'admitted',
'admitted',
'admitted',
]);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(3);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(4);
const winner = [...selected.validation.selection!.training].sort(
(a, b) =>
b.metrics.totalReturn! - a.metrics.totalReturn! ||
a.sourceCandidateIndex - b.sourceCandidateIndex
)[0]!;
expect(selected.validation.selection!.winner.index).toBe(winner.sourceCandidateIndex);
await until(
async () =>
(await f.pool.query("SELECT count(*) FROM runs WHERE status='completed'")).rows[0].count ===
'4',
'both same-winner heldouts finish through native runner'
);
// Finalization saves historical evidence and does not require permission to start new work.
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [backtest.id]);
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
await f.page.getByRole('button', { name: 'Refresh validation', exact: true }).click();
const finalizing = f.page.waitForResponse(r => r.url().endsWith(`${endpoint}/finalize`));
await f.page.getByRole('button', { name: 'Save validation report', exact: true }).click();
const reportResponse = await finalizing;
expect(reportResponse.status()).toBe(202);
const completed = (await reportResponse.json()) as ChronologicalValidationActionResult;
expect(completed.receipt.operation).toBe('finalize-report');
expect(completed.receipt.id).toBe(completed.validation.report!.id);
expect(completed.validation.stage).toBe('reported');
const report = completed.validation.report!;
expect(report.training).toEqual(selected.validation.selection!.training);
expect(report.reset).toBe('initial-capital-empty-positions');
expect(report.validation.parameters).toEqual(selected.validation.selection!.winner.parameters);
expect(report.test.parameters).toEqual(report.validation.parameters);
expect(report.validation.sourceCandidateIndex).toBe(winner.sourceCandidateIndex);
expect(report.test.sourceCandidateIndex).toBe(winner.sourceCandidateIndex);
for (const evidence of [...report.training, report.validation, report.test]) {
const result = (await f.request(
`/api/v2/runs/${evidence.runId}/results`
)) as CanonicalRunResult;
expect(evidence.metrics).toEqual(result.analytics.metrics);
expect(evidence.unavailable).toEqual(result.analytics.unavailable);
expect(evidence.datasetHash).toBe(result.request.datasetHash);
expect(String(result.request.policy.matching.risk.ledger.initialCapital)).toBe(
'10000.00000000'
);
}
await visible(f.page, 'Execution complete · report saved');
const read = (await f.request(endpoint)) as { validation: ChronologicalValidationDetail };
expect(read.validation.report).toEqual(report);
const originalRuns = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
// Retrying the accepted selection after archival returns its same receipt, never finalizes again.
const replay = (await f.request(
`${endpoint}/select`,
'POST',
selectionResponse.request().postDataJSON(),
{ 'Idempotency-Key': selectionResponse.request().headers()['idempotency-key']! }
)) as ChronologicalValidationActionResult;
expect(replay.receipt).toEqual(selected.receipt);
expect(replay.validation.report).toEqual(report);
expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual(
originalRuns
);
await f.page.reload();
await visible(f.page, 'Execution complete · report saved');
expect((await f.request(endpoint)).validation.report).toEqual(report);
await f.page.getByRole('link', { name: 'Open test experiment', exact: true }).click();
await f.page.waitForURL(
`${f.origin}/experiments/${selected.validation.selection!.holdoutExperimentIds.test}`
);
await visible(f.page, /completed: 1/);
await f.page.goto(`${f.origin}/experiments`);
await visible(f.page, 'Saved chronological validations');
await f.page.locator(`a[href="/experiments/validation/${admitted.id}"]`).click();
await visible(f.page, 'Execution complete · report saved');
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_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 retained failure/retry fixture',
});
const definition = {
name: 'Retry original inputs',
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,
});
const input = { backtestId: backtest.id, name: 'Recovered experiment', grid: {} };
const { preview } = (await f.request('/api/v2/experiments/preview', 'POST', input)) as {
preview: ExperimentPreview;
};
const { experiment } = (await f.request(
'/api/v2/experiments',
'POST',
{ ...input, previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: ExperimentDetail };
const runId = experiment.trials[0]!.runId!;
f.failNextCanonical('Injected canonical worker failure before financial replay');
f.dispatcher.start();
await until(
async () =>
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status ===
'failed',
'original canonical attempt fails durably'
);
const failed = (
await f.pool.query(
`SELECT *,to_char(completed_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS completed_at_exact
FROM runs WHERE id=$1`,
[runId]
)
).rows[0];
expect(failed.attempt_number).toBe(1);
expect(failed.manual_retry_count).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(0);
// A retry uses the original request even after edits and a later approval.
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Changed template after failure',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reapproved original version for the manual retry',
});
await f.login();
await f.page.goto(`${f.origin}/experiments/${experiment.id}`);
await visible(f.page, /failed: 1/);
await f.page.getByRole('button', { name: 'Retry trial 1', exact: true }).click();
const retrying = f.page.waitForResponse(response =>
response.url().endsWith(`/experiments/${experiment.id}/trials/${runId}/retry`)
);
await f.page.getByRole('button', { name: 'Confirm retry trial 1', exact: true }).click();
const response = await retrying;
expect(response.status()).toBe(202);
expect(response.request().postDataJSON()).toEqual({
expectedAttemptNumber: 1,
expectedRetryCount: 0,
});
const accepted = (await response.json()) as ExperimentRetryResult;
expect(accepted.retry.runId).toBe(runId);
expect(accepted.retry.previousAttemptId).toBe(failed.attempt_id);
expect(accepted.retry.previousAttemptNumber).toBe(1);
expect(accepted.retry.retryNumber).toBe(1);
expect(accepted.retry.error).toBe(failed.error);
expect(accepted.retry.completedAt).toBe(failed.completed_at_exact);
expect(accepted.retry.reviewId).not.toBe(failed.request_snapshot.strategy.reviewId);
await until(
async () =>
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status ===
'completed',
'retried trial redispatches and completes in the native engine'
);
const complete = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0];
expect(complete.attempt_number).toBe(2);
expect(complete.attempt_id).not.toBe(failed.attempt_id);
expect(complete.manual_retry_count).toBe(1);
expect(complete.request_snapshot).toEqual(failed.request_snapshot);
expect(complete.dataset_hash).toBe(failed.dataset_hash);
expect(complete.trial_key).toBe(failed.trial_key);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
const replay = await f.page.evaluate(
async ({ path, key, body }) => {
const reply = await fetch(path, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': key,
},
body: JSON.stringify(body),
});
return { status: reply.status, body: await reply.json() };
},
{
path: `/api/v2/experiments/${experiment.id}/trials/${runId}/retry`,
key: response.request().headers()['idempotency-key']!,
body: response.request().postDataJSON(),
}
);
expect(replay.status).toBe(202);
expect(replay.body.retry.id).toBe(accepted.retry.id);
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
await visible(f.page, /completed: 1/);
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(1);
await f.page
.getByRole('button', { name: 'Show retry history for trial 1', exact: true })
.click();
await visible(f.page, /Injected canonical worker failure before financial replay/);
const { retries } = (await f.request(
`/api/v2/experiments/${experiment.id}/trials/${runId}/retries`
)) as {
retries: ExperimentTrialRetry[];
};
expect(retries).toEqual([accepted.retry]);
await f.page.reload();
await visible(f.page, /completed: 1/);
await f.page
.getByRole('button', { name: 'Show retry history for trial 1', exact: true })
.click();
await visible(f.page, /Injected canonical worker failure before financial replay/);
await f.page.locator(`a[href="/backtests/${backtest.id}/run/${runId}"]`).click();
await visible(f.page, 'Canonical research result');
const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
expect(result.request).toEqual(failed.request_snapshot);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
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();
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);
// Original reproduction is independent of subsequent mutable template edits.
await f.request(`/api/v2/backtests/${backtestId}`, 'PUT', {
name: 'Changed current settings',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
config: { ...sent.config, canonical: { ...sent.config.canonical, feeRate: '0.02', seed: 7 } },
});
await f.page.reload();
await visible(f.page, 'Canonical research result');
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
const reproductionDialog = f.page.getByRole('dialog', {
name: 'Reproduce original',
exact: true,
});
const originalInputs = reproductionDialog.getByRole('region', {
name: 'Original retained inputs',
exact: true,
});
await originalInputs.waitFor({ state: 'visible' });
expect(await originalInputs.textContent()).toContain(retained.hash);
expect(await originalInputs.textContent()).toContain(selected.id);
await reproductionDialog
.getByText('Exact parameters, financial policies and build', { exact: true })
.click();
expect(await originalInputs.locator('pre').textContent()).toContain(
'"initialCapital": "10000.00000000"'
);
expect(await originalInputs.locator('pre').textContent()).toContain('"fastPeriod": 2');
const reproducing = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith(`/runs/${run.id}/reproduce`)
);
await reproductionDialog
.getByRole('button', { name: 'Confirm reproduction', exact: true })
.click();
const reproducedResponse = await reproducing;
expect(reproducedResponse.status()).toBe(202);
expect(reproducedResponse.request().headers()['idempotency-key']).toBeTruthy();
expect(reproducedResponse.request().postDataJSON()).toEqual({});
const reproducedRun = await reproducedResponse.json();
expect(reproducedRun.originalRunId).toBe(run.id);
expect(reproducedRun.id).not.toBe(run.id);
expect(reproducedResponse.headers().location).toBe(`/api/v2/runs/${reproducedRun.id}`);
await f.page.waitForURL(`${f.origin}/backtests/${backtestId}/run/${reproducedRun.id}`);
const duplicate = await f.page.evaluate(
async ({ sourceId, key }) => {
const response = await fetch(`/api/v2/runs/${sourceId}/reproduce`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: '{}',
});
return { status: response.status, run: await response.json() };
},
{ sourceId: run.id, key: reproducedResponse.request().headers()['idempotency-key']! }
);
expect(duplicate.status).toBe(202);
expect(duplicate.run.id).toBe(reproducedRun.id);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
await visible(f.page, 'Economic results match the original.');
const comparison = await f.request(`/api/v2/runs/${reproducedRun.id}/reproduction-comparison`);
expect(comparison.status).toBe('match');
expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/);
expect(comparison.reproducedHash).toBe(comparison.originalHash);
const reproducedResult = (await f.request(
`/api/v2/runs/${reproducedRun.id}/results`
)) as CanonicalRunResult;
expect(reproducedResult.request.strategy.selection).toEqual(result.request.strategy.selection);
expect(reproducedResult.request.build).toEqual(result.request.build);
expect(reproducedResult.request.datasetHash).toBe(result.request.datasetHash);
expect(String(reproducedResult.request.policy.matching.risk.ledger.initialCapital)).toBe(
'10000.00000000'
);
expect(reproducedResult.financial.projection).toEqual(result.financial.projection);
expect(reproducedResult.analytics).toEqual(result.analytics);
await f.page.reload();
await visible(f.page, 'Economic results match the original.');
await f.page.getByRole('link', { name: 'Open original run', exact: true }).click();
await f.page.waitForURL(completedUrl);
await visible(f.page, '9969.30000000');
// Ordinary submission still freezes the current settings and has no reproduction lineage.
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
const currentResponse = await submitInBrowser(f.page);
expect(currentResponse.status()).toBe(202);
const currentRun = await currentResponse.json();
expect(currentRun.originalRunId).toBeNull();
await visible(f.page, 'Canonical research result');
const currentResult = (await f.request(
`/api/v2/runs/${currentRun.id}/results`
)) as CanonicalRunResult;
expect(String(currentResult.request.policy.matching.risk.ledger.initialCapital)).toBe(
'20000.00000000'
);
expect(currentResult.request.strategy.selection.parameters).toEqual({
fastPeriod: 1,
slowPeriod: 2,
});
expect(currentResult.request.strategy.selection.seed).toBe(7);
expect(String(currentResult.request.policy.matching.risk.feeRate)).toBe('0.02000000');
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
expect(
(await f.pool.query('SELECT original_run_id FROM runs WHERE id=$1', [reproducedRun.id]))
.rows[0].original_run_id
).toBe(run.id);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});