3975 lines
183 KiB
TypeScript
3975 lines
183 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { afterAll, beforeAll, expect, test } from 'bun:test';
|
|
import { chromium, type Browser, type Request } from 'playwright';
|
|
import {
|
|
canonicalResearchSettingsSchema,
|
|
type CanonicalDatasetPreparation,
|
|
type CanonicalRunResult,
|
|
type CanonicalStoredSourcePreparation,
|
|
} 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 { ResearchAgentRecord } from '@stock-bot/stock-config/research-agents';
|
|
import type {
|
|
WalkForwardActionResult,
|
|
WalkForwardDetail,
|
|
WalkForwardPreview,
|
|
} from '@stock-bot/stock-config/walk-forward';
|
|
import type {
|
|
HistoricalDatasetInputV2,
|
|
HistoricalDatasetV2,
|
|
ResearchArtifact,
|
|
ResearchFindingSource,
|
|
} from '@stock-bot/types';
|
|
import {
|
|
createDatasetV2,
|
|
validateDatasetV2,
|
|
} from '../../apps/stock/orchestrator/src/data/historical-dataset-v2';
|
|
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,
|
|
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);
|
|
|
|
async function downloadDatasetInBrowser(
|
|
f: Awaited<ReturnType<typeof fixture>>,
|
|
expected: HistoricalDatasetV2
|
|
) {
|
|
const hash = expected.manifest.hash;
|
|
const responding = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/api/v2/datasets/canonical/${hash}/export`)
|
|
);
|
|
const downloading = f.page.waitForEvent('download');
|
|
await f.page.getByRole('button', { name: 'Download retained dataset', exact: true }).click();
|
|
const response = await responding;
|
|
expect(response.status()).toBe(200);
|
|
expect(response.headers()['cache-control']).toBe('no-store');
|
|
expect(response.headers()['content-disposition']).toBe(
|
|
`attachment; filename="dataset-${hash}.json"`
|
|
);
|
|
const download = await downloading;
|
|
expect(download.suggestedFilename()).toBe(`dataset-${hash}.json`);
|
|
expect(await download.failure()).toBeNull();
|
|
const path = await download.path();
|
|
if (!path) {
|
|
throw new Error('Expected a downloaded fixture file');
|
|
}
|
|
expect(validateDatasetV2(JSON.parse(readFileSync(path, 'utf8')))).toEqual(expected);
|
|
}
|
|
|
|
test('operator_provisions_bounded_agent_views_usage_and_revokes_without_corrupting_accepted_work_browser', async () => {
|
|
const f = await fixture(true);
|
|
try {
|
|
await f.login();
|
|
const { id: backtestId } = await createCanonicalInBrowser(f, 'Agent baseline');
|
|
const { project } = await f.request('/api/v2/research-projects', 'POST', {
|
|
title: 'Agent research',
|
|
});
|
|
await f.page.goto(`${f.origin}/research/agents?projectId=${project.id}`);
|
|
await visible(f.page, 'No research agents configured.');
|
|
await f.page.getByLabel('Agent name', { exact: true }).fill('Bounded browser researcher');
|
|
await f.page.getByLabel('Allowed backtest IDs', { exact: true }).fill(backtestId);
|
|
await f.page.getByLabel('Maximum active trials', { exact: true }).fill('1');
|
|
await f.page.getByLabel('Maximum trials per experiment', { exact: true }).fill('2');
|
|
await f.page.getByLabel('Maximum attempt time (ms)', { exact: true }).fill('30000');
|
|
const creating = f.page.waitForResponse(
|
|
response =>
|
|
response.request().method() === 'POST' && response.url().endsWith('/api/v2/research-agents')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Create credential', exact: true }).click();
|
|
const response = await creating;
|
|
expect(response.status()).toBe(201);
|
|
const created = (await response.json()) as { agent: ResearchAgentRecord; token: string };
|
|
expect(await f.page.getByLabel('New research token', { exact: true }).inputValue()).toBe(
|
|
created.token
|
|
);
|
|
expect(created.agent.allowedProjectIds).toEqual([project.id]);
|
|
expect(created.agent.grants.map(grant => grant.backtestId)).toEqual([backtestId]);
|
|
const agentRequest = (path: string, method = 'GET', body?: unknown, key?: string) =>
|
|
fetch(`${f.origin}${path}`, {
|
|
method,
|
|
headers: {
|
|
Authorization: `Bearer ${created.token}`,
|
|
'Content-Type': 'application/json',
|
|
...(key ? { 'Idempotency-Key': key } : {}),
|
|
},
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
const hypothesis = await agentRequest(
|
|
`/api/v2/research-projects/${project.id}/hypotheses`,
|
|
'POST',
|
|
{
|
|
title: 'Agent proposal awaiting validation',
|
|
proposition: 'A controlled hypothesis, not proof of profitability.',
|
|
contentOrigin: 'ai',
|
|
}
|
|
);
|
|
expect(hypothesis.status).toBe(201);
|
|
expect(JSON.stringify(await hypothesis.json())).toContain(created.agent.id);
|
|
const input = {
|
|
backtestId,
|
|
name: 'Bounded existing strategy experiment',
|
|
grid: { fastPeriod: [2] },
|
|
};
|
|
const previewResponse = await agentRequest('/api/v2/experiments/preview', 'POST', input);
|
|
expect(previewResponse.status).toBe(200);
|
|
const { preview } = (await previewResponse.json()) as { preview: ExperimentPreview };
|
|
const body = { ...input, previewHash: preview.previewHash };
|
|
const accepted = await agentRequest('/api/v2/experiments', 'POST', body, randomUUID());
|
|
expect(accepted.status).toBe(202);
|
|
const { experiment } = (await accepted.json()) as { experiment: ExperimentDetail };
|
|
expect((await agentRequest('/api/v2/experiments', 'POST', body, randomUUID())).status).toBe(
|
|
429
|
|
);
|
|
expect(
|
|
(await agentRequest(`/api/v2/backtests/${backtestId}`, 'PUT', { initialCapital: 999999 }))
|
|
.status
|
|
).toBe(403);
|
|
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
|
const row = (
|
|
await f.pool.query('SELECT * FROM research_agents WHERE id=$1', [created.agent.id])
|
|
).rows[0];
|
|
expect(JSON.stringify(row)).not.toContain(created.token);
|
|
await f.page.getByRole('button', { name: 'I have saved the credential', exact: true }).click();
|
|
await f.page
|
|
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
|
|
.click();
|
|
await visible(f.page, 'Active trials: 1; available slots: 0');
|
|
await f.page
|
|
.getByRole('button', { name: 'Disable Bounded browser researcher', exact: true })
|
|
.click();
|
|
await visible(f.page, /Disabled · Revision 2/);
|
|
expect((await agentRequest('/api/v2/research-agent/budget')).status).toBe(401);
|
|
// Revocation denies new access. Previously accepted bounded work retains its frozen owner/budget.
|
|
f.dispatcher.start();
|
|
const trial = experiment.trials[0];
|
|
if (!trial?.runId) {
|
|
throw new Error('Expected admitted agent trial');
|
|
}
|
|
await until(
|
|
async () =>
|
|
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [trial.runId])).rows[0]
|
|
?.status === 'completed',
|
|
'accepted agent trial completes on canonical Rust'
|
|
);
|
|
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
|
|
expect(result.financialEngine).toBe('rust');
|
|
expect(result.request).toMatchObject({
|
|
datasetHash: preview.request.datasetHash,
|
|
strategy: { versionId: preview.request.strategy.versionId },
|
|
});
|
|
await f.page
|
|
.getByRole('button', { name: 'Check budget for Bounded browser researcher', exact: true })
|
|
.click();
|
|
await visible(f.page, 'Active trials: 0; available slots: 1');
|
|
await f.page.reload();
|
|
await visible(f.page, /Disabled · Revision 2/);
|
|
expect(await f.page.getByLabel('New research token', { exact: true }).count()).toBe(0);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
/** Lifecycle tests create via the real catalog UI; policy setup is seeded through
|
|
* the same public API. The full setup UI is exercised by the research workflow below. */
|
|
async function createCanonicalInBrowser(
|
|
f: Awaited<ReturnType<typeof fixture>>,
|
|
name: string,
|
|
run = false
|
|
) {
|
|
const { dataset } = canonicalSmaFixture();
|
|
await retainResearchDataset(f.pool, dataset);
|
|
const version = (await f.seedCatalog()).find(
|
|
item => item.package.program.strategyId === 'sma_crossover'
|
|
)!;
|
|
if (version.reviewStatus !== 'approved') {
|
|
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
|
decision: 'approve',
|
|
reason: 'Reviewed canonical lifecycle fixture',
|
|
});
|
|
}
|
|
await f.page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
|
await f.page.getByPlaceholder('My Strategy Backtest').fill(name);
|
|
await f.page.getByLabel('Strategy family', { exact: true }).selectOption(version.strategyId);
|
|
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
|
|
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
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 id = f.page.url().split('/').at(-1)!;
|
|
await f.request(`/api/v2/backtests/${id}`, 'PUT', {
|
|
strategy: 'catalog',
|
|
strategyVersionId: version.id,
|
|
strategyParameters: { fastPeriod: 2, slowPeriod: f.controlled.mode === 'empty' ? 100 : 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: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
});
|
|
await f.page.reload();
|
|
await visible(f.page, /Canonical execution is available/);
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
if (run) {
|
|
await submitInBrowser(f.page);
|
|
}
|
|
return { id, dataset, version };
|
|
}
|
|
|
|
/** Uses real retained native measurements, then reopens the exact source from immutable history. */
|
|
async function saveSourceFindingInBrowser(
|
|
f: Awaited<ReturnType<typeof fixture>>,
|
|
source: ResearchFindingSource,
|
|
choices: { runId: string; metricPath: string }[],
|
|
title: string
|
|
) {
|
|
const sourceUrl = f.page.url();
|
|
await f.page.getByRole('heading', { name: 'Regime evidence unavailable', exact: true }).waitFor();
|
|
const counts = async () =>
|
|
(
|
|
await f.pool.query(`SELECT
|
|
(SELECT count(*)::int FROM runs) AS runs,
|
|
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
|
).rows[0];
|
|
const before = await counts();
|
|
const { project } = await f.request('/api/v2/research-projects', 'POST', {
|
|
title: `${title} project`,
|
|
});
|
|
await f.page.getByRole('button', { name: 'Save research 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 title', { exact: true }).fill(title);
|
|
await dialog
|
|
.getByLabel('Finding body', { exact: true })
|
|
.fill(
|
|
'Selected retained measurements support further investigation; this narrative is not validated alpha.'
|
|
);
|
|
expect(await dialog.getByRole('button', { name: 'Save finding', exact: true }).isDisabled()).toBe(
|
|
true
|
|
);
|
|
for (const choice of choices) {
|
|
await dialog
|
|
.locator(`input[data-run-id="${choice.runId}"][data-metric-path="${choice.metricPath}"]`)
|
|
.check();
|
|
}
|
|
const creating = 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 response = await creating;
|
|
expect(response.status()).toBe(201);
|
|
expect(response.request().postDataJSON().source).toEqual(source);
|
|
const { artifact } = (await response.json()) as { artifact: ResearchArtifact };
|
|
expect(artifact.latestRevision.source).toEqual(source);
|
|
expect(artifact.latestRevision.validationState).toBe('unvalidated');
|
|
expect(artifact.latestRevision.evidence).toHaveLength(choices.length);
|
|
for (const choice of choices) {
|
|
const item = artifact.latestRevision.evidence.find(
|
|
evidence => evidence.runId === choice.runId && evidence.metricPath === choice.metricPath
|
|
)!;
|
|
const result = (await f.request(`/api/v2/runs/${choice.runId}/results`)) as CanonicalRunResult;
|
|
const key = choice.metricPath.slice(
|
|
'analytics.metrics.'.length
|
|
) as keyof typeof result.analytics.metrics;
|
|
expect(item.value).toBe(result.analytics.metrics[key]);
|
|
expect(item.unavailableReason).toBe(
|
|
item.value === null ? (result.analytics.unavailable[key] ?? 'not-reported') : null
|
|
);
|
|
expect(item.financialEngine).toBe('rust');
|
|
expect(item.datasetHash).toBe(result.request.datasetHash);
|
|
}
|
|
await dialog.getByRole('link', { name: 'Open saved finding', exact: true }).click();
|
|
const findingUrl = `${f.origin}/research/${project.id}?artifact=${artifact.id}`;
|
|
await f.page.waitForURL(findingUrl);
|
|
const sourceLink = f.page.getByRole('link', { name: 'Open cited source', exact: true });
|
|
await sourceLink.waitFor();
|
|
expect(await sourceLink.getAttribute('href')).toBe(new URL(sourceUrl).pathname);
|
|
await f.page.getByRole('button', { name: 'Edit latest revision', exact: true }).click();
|
|
await f.page.getByLabel('Revision title', { exact: true }).fill(`${title} revised`);
|
|
const revising = f.page.waitForResponse(
|
|
reply =>
|
|
reply.request().method() === 'POST' &&
|
|
reply.url().endsWith(`/analysis-artifacts/${artifact.id}/revisions`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Save new revision', exact: true }).click();
|
|
const revised = await revising;
|
|
expect(revised.status()).toBe(201);
|
|
expect(revised.request().postDataJSON().source).toEqual(source);
|
|
const updated = (await revised.json()) as { artifact: ResearchArtifact };
|
|
expect(updated.artifact.latestRevision.ordinal).toBe(2);
|
|
expect(updated.artifact.latestRevision.source).toEqual(source);
|
|
expect(updated.artifact.latestRevision.evidence).toEqual(artifact.latestRevision.evidence);
|
|
await f.page.getByRole('button', { name: 'View revision 1', exact: true }).click();
|
|
await visible(f.page, 'Immutable history: this revision is read-only.');
|
|
await f.page.reload();
|
|
await visible(f.page, 'Immutable history: this revision is read-only.');
|
|
await sourceLink.click();
|
|
await f.page.waitForURL(sourceUrl);
|
|
await f.page.getByRole('button', { name: 'Save research finding', exact: true }).waitFor();
|
|
expect(await counts()).toEqual(before);
|
|
}
|
|
|
|
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.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 saveSourceFindingInBrowser(
|
|
f,
|
|
{
|
|
kind: 'experiment/v1',
|
|
experimentId: experiment.id,
|
|
previewHash: preview.previewHash,
|
|
},
|
|
[
|
|
{ runId: experiment.trials[0]!.runId!, metricPath: 'analytics.metrics.totalReturn' },
|
|
{ runId: experiment.trials[2]!.runId!, metricPath: 'analytics.metrics.sharpeRatio' },
|
|
],
|
|
'Retained cost comparison finding'
|
|
);
|
|
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.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');
|
|
await saveSourceFindingInBrowser(
|
|
f,
|
|
{
|
|
kind: 'walk-forward-report/v1',
|
|
walkForwardId: initial.id,
|
|
previewHash: report.previewHash,
|
|
reportId: report.id,
|
|
reportHash: report.reportHash,
|
|
},
|
|
[
|
|
{
|
|
runId: report.segments[0]!.validation.runId,
|
|
metricPath: 'analytics.metrics.totalReturn',
|
|
},
|
|
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.maxDrawdown' },
|
|
{ runId: report.segments[1]!.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
|
|
],
|
|
'Retained walk-forward finding'
|
|
);
|
|
await f.page.getByRole('link', { name: 'Open window 1 validation', exact: true }).click();
|
|
const child = childReports[0]!;
|
|
await visible(f.page, 'Execution complete · report saved');
|
|
await saveSourceFindingInBrowser(
|
|
f,
|
|
{
|
|
kind: 'chronological-report/v1',
|
|
validationId: child.validationId,
|
|
previewHash: child.previewHash,
|
|
reportId: child.id,
|
|
reportHash: child.reportHash,
|
|
},
|
|
[
|
|
{ runId: child.training[0]!.runId, metricPath: 'analytics.metrics.totalReturn' },
|
|
{ runId: child.test.runId, metricPath: 'analytics.metrics.sharpeRatio' },
|
|
],
|
|
'Retained chronological finding'
|
|
);
|
|
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(8);
|
|
expect((await f.pool.query('SELECT * FROM analysis_artifacts')).rowCount).toBe(2);
|
|
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.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.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.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();
|
|
// A stale link must not hide the valid saved template in the catalog.
|
|
const missingBacktestId = randomUUID();
|
|
const missingLookup = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/api/v2/backtests/${missingBacktestId}`)
|
|
);
|
|
await f.page.goto(`${f.origin}/experiments?backtestId=${missingBacktestId}`);
|
|
expect((await missingLookup).status()).toBe(404);
|
|
await visible(f.page, /Could not load the selected backtest:/);
|
|
expect(await f.page.getByLabel('Saved backtest').inputValue()).toBe(missingBacktestId);
|
|
await f.page
|
|
.getByLabel('Saved backtest')
|
|
.locator(`option[value="${backtest.id}"]`)
|
|
.waitFor({ state: 'attached' });
|
|
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]}');
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
|
|
expect(await f.page.getByLabel('Experiment name', { exact: true }).inputValue()).toBe(
|
|
'Retained SMA sweep'
|
|
);
|
|
expect(await f.page.getByLabel('Parameter grid (JSON)').inputValue()).toBe(
|
|
'{"fastPeriod":[1,2],"slowPeriod":[3]}'
|
|
);
|
|
expect(await f.request(`/api/v2/backtests/${backtest.id}`)).toEqual(backtest);
|
|
expect(
|
|
(await f.pool.query('SELECT count(*)::int AS n FROM research_experiments')).rows[0].n
|
|
).toBe(0);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
|
0
|
|
);
|
|
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.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);
|
|
const { dataset } = await createCanonicalInBrowser(f, '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(10000);
|
|
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('dl[aria-label="Canonical dataset bounds"]').textContent()
|
|
).toContain(new Date(dataset.manifest.bounds.tradeStart).toISOString());
|
|
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, /Pinned dataset hash/);
|
|
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, 'Canonical research result');
|
|
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
|
|
const result = await f.request(`/api/v2/runs/${run.id}/results`);
|
|
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
|
|
await visible(f.page, result.request.datasetHash);
|
|
expect(await f.page.locator('pre').textContent()).toContain(
|
|
'"initialCapital": "10000.00000000"'
|
|
);
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, 'buy');
|
|
await visible(f.page, '5.00000000');
|
|
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\s*Canonical$/).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 createCanonicalInBrowser(f, '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 createCanonicalInBrowser(f, '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 createCanonicalInBrowser(f, '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 fills were executed in this completed run.');
|
|
const emptyId = f.page.url().split('/').at(-1)!;
|
|
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).financial.projection.fills).toEqual(
|
|
[]
|
|
);
|
|
// A saved completed row whose result is unavailable must not appear as zero trades.
|
|
const missingResultId = randomUUID();
|
|
const missingDefinitionId = randomUUID();
|
|
await f.pool.query(
|
|
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital) VALUES ($1,'Historical missing result','moving-average','["AAPL.US"]','2024-01-01','2024-02-01',10000)`,
|
|
[missingDefinitionId]
|
|
);
|
|
await f.pool.query(
|
|
"INSERT INTO runs(id,backtest_id,run_number,status) VALUES ($1,$2,1,'completed')",
|
|
[missingResultId, missingDefinitionId]
|
|
);
|
|
await f.page.goto(`${f.origin}/backtests/${missingDefinitionId}/run/${missingResultId}`);
|
|
await visible(f.page, 'Run completed, but saved results are unavailable.');
|
|
await visible(f.page, 'Retry results');
|
|
expect(
|
|
await f.page
|
|
.getByText('No fills were executed in this completed run.', { 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 createCanonicalInBrowser(f, '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\s*Canonical$/);
|
|
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\s*Canonical$/).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\s*Canonical$/).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('Immutable configuration and reporting policy', { 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);
|
|
// Optional history metrics must not hide saved runs while one result is delayed.
|
|
const beforeHistorySelection = (
|
|
await f.pool.query('SELECT id, status FROM runs WHERE backtest_id=$1 ORDER BY id', [
|
|
definitionId,
|
|
])
|
|
).rows;
|
|
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
await delayed.captured.wait('delayed history metrics');
|
|
await visible(f.page, /^#1$/);
|
|
await visible(f.page, /^#2\s*Canonical$/);
|
|
await f.page.getByText(/^#2\s*Canonical$/).click();
|
|
await visible(f.page, 'Completed');
|
|
expect(f.page.url()).toBe(secondUrl);
|
|
delayed.release.resolve();
|
|
await delayed.delivered.wait('history metrics released after selection');
|
|
expect(
|
|
(
|
|
await f.pool.query('SELECT id, status FROM runs WHERE backtest_id=$1 ORDER BY id', [
|
|
definitionId,
|
|
])
|
|
).rows
|
|
).toEqual(beforeHistorySelection);
|
|
// 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('canonical_native_smoke', async () => {
|
|
const f = await fixture(true);
|
|
try {
|
|
await f.login();
|
|
const { id, dataset } = await createCanonicalInBrowser(f, 'Actual Rust browser smoke');
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await f.page.getByLabel('Backtest name', { exact: true }).fill('Unsaved native research draft');
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
await submitInBrowser(f.page);
|
|
const runId = f.page.url().split('/').at(-1)!;
|
|
f.dispatcher.start();
|
|
await visible(f.page, 'Completed');
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
expect(await f.page.getByLabel('Backtest name', { exact: true }).inputValue()).toBe(
|
|
'Unsaved native research draft'
|
|
);
|
|
expect((await f.request(`/api/v2/backtests/${id}`)).name).toBe('Actual Rust browser smoke');
|
|
await f.page.getByRole('button', { name: 'Details', exact: true }).click();
|
|
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
|
expect(result.financialEngine).toBe('rust');
|
|
expect(result.request.strategy.origin).toBe('builtin');
|
|
expect(result.request.datasetHash).toMatch(/^[a-f0-9]{64}$/);
|
|
expect(result.financial.projection.fills.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, 'Canonical research result');
|
|
const interval = f.page.locator('[aria-label="Evaluation horizon"]');
|
|
await interval.waitFor({ state: 'visible' });
|
|
expect(await interval.textContent()).toContain(
|
|
new Date(result.financial.reporting.tradeStart).toISOString()
|
|
);
|
|
expect(await interval.textContent()).toContain(
|
|
new Date(result.financial.reporting.tradeEnd).toISOString()
|
|
);
|
|
await visible(f.page, /CAGR extrapolates this evaluation interval to a 365-calendar-day year/);
|
|
await visible(f.page, /Annualization for periodic statistics:/);
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, result.financial.projection.fills[0].side);
|
|
await visible(f.page, result.financial.projection.fills[0].price);
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Download retained dataset', exact: true }).count()
|
|
).toBe(0);
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Download run result', exact: true }).count()
|
|
).toBe(0);
|
|
// The editable template moves to a different retained source; this run's
|
|
// export must still resolve its immutable original request hash.
|
|
const replacement = canonicalSmaFixture(['A'], { volume: 2000 }).dataset;
|
|
await retainResearchDataset(f.pool, replacement);
|
|
const template = await f.request(`/api/v2/backtests/${id}`);
|
|
await f.request(`/api/v2/backtests/${id}`, 'PUT', {
|
|
config: { ...template.config, datasetHash: replacement.manifest.hash },
|
|
});
|
|
await f.page.reload();
|
|
await visible(f.page, 'Completed');
|
|
await f.page.getByText('Immutable configuration and reporting policy', { exact: true }).click();
|
|
await visible(f.page, result.request.datasetHash);
|
|
await downloadDatasetInBrowser(f, dataset);
|
|
const exportRequests: string[] = [];
|
|
const recordExportRequest = (request: Request) => {
|
|
if (new URL(request.url()).pathname.startsWith('/api/')) {
|
|
exportRequests.push(request.url());
|
|
}
|
|
};
|
|
f.page.on('request', recordExportRequest);
|
|
const downloadingResult = f.page.waitForEvent('download');
|
|
await f.page.getByRole('button', { name: 'Download run result', exact: true }).click();
|
|
const downloadedResult = await downloadingResult;
|
|
expect(downloadedResult.suggestedFilename()).toBe(`run-${runId}.json`);
|
|
expect(await downloadedResult.failure()).toBeNull();
|
|
const resultPath = await downloadedResult.path();
|
|
if (!resultPath) {
|
|
throw new Error('Expected a downloaded canonical result file');
|
|
}
|
|
expect(JSON.parse(readFileSync(resultPath, 'utf8'))).toEqual(result);
|
|
f.page.off('request', recordExportRequest);
|
|
expect(exportRequests).toEqual([]);
|
|
expect((await f.request(`/api/v2/backtests/${id}`)).config.datasetHash).toBe(
|
|
replacement.manifest.hash
|
|
);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(1);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
|
1
|
|
);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('browser_legacy_frozen_history_reopens_without_reactivating_retired_execution', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
const dataset = await retainDataset(f.pool);
|
|
const hash = dataset.manifest.hash;
|
|
const backtestId = randomUUID(),
|
|
runId = randomUUID();
|
|
const config = {
|
|
name: 'Historical frozen dataset',
|
|
strategy: 'moving-average',
|
|
symbols: ['AAPL.US'],
|
|
startDate: '2024-01-01T00:00:00.000Z',
|
|
endDate: '2024-03-15T00:00:00.000Z',
|
|
initialCapital: 100000,
|
|
commission: 0,
|
|
slippage: 0,
|
|
dataFrequency: '1d',
|
|
parameters: {},
|
|
dataset: dataset.manifest,
|
|
};
|
|
// Explicit pre-cutover history fixture, never an alternative simulator.
|
|
await f.pool.query(
|
|
`INSERT INTO backtests(id,name,strategy,symbols,start_date,end_date,initial_capital,config)
|
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
|
|
[
|
|
backtestId,
|
|
config.name,
|
|
config.strategy,
|
|
JSON.stringify(config.symbols),
|
|
config.startDate,
|
|
config.endDate,
|
|
config.initialCapital,
|
|
JSON.stringify({ datasetHash: hash, dataFrequency: '1d' }),
|
|
]
|
|
);
|
|
await f.pool.query(
|
|
`INSERT INTO runs(id,backtest_id,run_number,status,dataset_hash)
|
|
VALUES ($1,$2,1,'completed',$3)`,
|
|
[runId, backtestId, hash]
|
|
);
|
|
await f.pool.query(
|
|
`INSERT INTO backtest_results(run_id,completed_at,engine,configuration,metrics,equity_curve,ohlc_data,trades,positions,analytics,execution_time)
|
|
VALUES ($1,NOW(),'native',$2,$3,'[]','{}',$4,'[]','{}',1)`,
|
|
[
|
|
runId,
|
|
JSON.stringify(config),
|
|
JSON.stringify({
|
|
totalReturn: 0,
|
|
sharpeRatio: null,
|
|
maxDrawdown: 0,
|
|
winRate: 0,
|
|
totalTrades: 0,
|
|
profitFactor: null,
|
|
avgWin: 0,
|
|
avgLoss: 0,
|
|
}),
|
|
JSON.stringify([
|
|
{
|
|
kind: 'fill',
|
|
id: 'historical-fill',
|
|
symbol: 'AAPL.US',
|
|
timestamp: '2024-01-02T00:00:00.000Z',
|
|
side: 'buy',
|
|
price: 100,
|
|
quantity: 1,
|
|
commission: 0,
|
|
},
|
|
]),
|
|
]
|
|
);
|
|
await f.login();
|
|
await f.page.goto(`${f.origin}/backtests/${backtestId}/run/${runId}`);
|
|
await visible(f.page, 'Completed');
|
|
await visible(f.page, 'Research only · Unverified economics');
|
|
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
|
expect(result.config.dataset.hash).toBe(hash);
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, 'BUY');
|
|
await f.page.reload();
|
|
await visible(f.page, 'Completed');
|
|
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/${backtestId}/runs`,
|
|
'POST',
|
|
{},
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)
|
|
).rejects.toThrow('409');
|
|
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
|
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
|
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
|
|
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;
|
|
const version = (await f.seedCatalog()).find(
|
|
item => item.package.program.strategyId === 'sma_crossover'
|
|
)!;
|
|
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('Strategy family', { exact: true }).selectOption(version.strategyId);
|
|
await f.page.getByLabel('Immutable strategy version', { exact: true }).selectOption(version.id);
|
|
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
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
|
|
);
|
|
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
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();
|
|
expect(await f.page.getByRole('button', { name: 'New Run', exact: true }).isDisabled()).toBe(
|
|
true
|
|
);
|
|
await expect(
|
|
f.request(
|
|
`/api/v2/backtests/${backtestId}/runs`,
|
|
'POST',
|
|
{},
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)
|
|
).rejects.toThrow('409');
|
|
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 createCanonicalInBrowser(f, '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.getByLabel('Backtest name', { exact: true }).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.request.datasetHash).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\s*Canonical$/).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.getByLabel('Backtest name', { exact: true }).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());
|
|
let releaseCloneResponse: (() => void) | undefined;
|
|
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 validateVisibleParameters();
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isEnabled()
|
|
).toBe(true);
|
|
await f.page.getByRole('button', { name: 'Clone version', exact: true }).click();
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
expect(await f.page.getByLabel('Candidate package (JSON)', { exact: true }).isDisabled()).toBe(
|
|
true
|
|
);
|
|
await f.page.getByLabel('Clone name', { exact: true }).fill('Browser candidate clone');
|
|
const clonePath = `/api/v2/strategy-versions/${selected.id}/clone`;
|
|
const parentVersionCount = async () =>
|
|
(
|
|
await f.pool.query(
|
|
'SELECT count(*)::int AS n FROM strategy_versions WHERE parent_version_id=$1',
|
|
[selected.id]
|
|
)
|
|
).rows[0].n as number;
|
|
const versionsBeforeClone = await parentVersionCount();
|
|
const cloneAttempts: { key: string | undefined; body: string | null }[] = [];
|
|
let originalCloneId: string | undefined;
|
|
await f.page.route(`${f.origin}${clonePath}`, async route => {
|
|
cloneAttempts.push({
|
|
key: route.request().headers()['idempotency-key'],
|
|
body: route.request().postData(),
|
|
});
|
|
const response = await route.fetch();
|
|
if (cloneAttempts.length === 1) {
|
|
expect(response.status()).toBe(201);
|
|
originalCloneId = (await response.json()).version.id;
|
|
await route.abort('failed'); // The server committed; only its response is lost.
|
|
} else {
|
|
await route.fulfill({ response });
|
|
}
|
|
});
|
|
const delayedClone = f.delayResponse(clonePath);
|
|
releaseCloneResponse = () => delayedClone.release.resolve();
|
|
await f.page.getByRole('button', { name: 'Create clone', exact: true }).click();
|
|
await delayedClone.captured.wait('committed clone response');
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
expect(f.page.url()).toBe(versionUrl);
|
|
releaseCloneResponse();
|
|
await f.page.getByRole('button', { name: 'Retry clone', exact: true }).waitFor();
|
|
expect(originalCloneId).toBeDefined();
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Use in backtest', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
const cloned = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/strategy-versions/${selected.id}/clone`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Retry clone', exact: true }).click();
|
|
const cloneResponse = await cloned;
|
|
expect(cloneResponse.status()).toBe(201);
|
|
const clone = await cloneResponse.json();
|
|
expect(clone.version.id).toBe(originalCloneId);
|
|
expect(cloneAttempts).toHaveLength(2);
|
|
expect(cloneAttempts[1]!).toEqual(cloneAttempts[0]!);
|
|
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);
|
|
expect(await parentVersionCount()).toBe(versionsBeforeClone + 1);
|
|
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 {
|
|
releaseCloneResponse?.();
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('canonical_dataset_browser_reuses_older_pages_and_known_hash_without_new_runs', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.login();
|
|
const { id, dataset } = await createCanonicalInBrowser(f, 'Retained dataset reuse');
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
|
dataset.manifest;
|
|
const snapshots = [];
|
|
for (let index = 0; index < 52; index++) {
|
|
const snapshot = createDatasetV2({
|
|
metadata: {
|
|
calendars,
|
|
series: series.map(value => ({
|
|
...value,
|
|
source: { ...value.source, revision: `catalog-browser-fixture-${index}` },
|
|
})),
|
|
executionSeries,
|
|
bounds,
|
|
universe,
|
|
corporateActions,
|
|
},
|
|
bars: dataset.bars.map(bar => ({
|
|
seriesId: bar.seriesId,
|
|
timestamp: bar.intervalStart,
|
|
availableAt: bar.availableAt,
|
|
sourceSequence: bar.sourceSequence,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
})),
|
|
});
|
|
// Set fixture ordering on initial insertion; retained evidence is immutable.
|
|
await f.pool.query(
|
|
'INSERT INTO backtest_datasets(hash,payload,created_at) VALUES($1,$2::jsonb,$3)',
|
|
[
|
|
snapshot.manifest.hash,
|
|
JSON.stringify(snapshot),
|
|
new Date(Date.parse('2020-01-01T00:00:00Z') + index * 60_000),
|
|
]
|
|
);
|
|
await retainResearchDataset(f.pool, snapshot);
|
|
snapshots.push(snapshot);
|
|
}
|
|
const older = snapshots[0]!,
|
|
known = snapshots[1]!;
|
|
const before = await f.request(`/api/v2/backtests/${id}`);
|
|
const listResponses: string[] = [];
|
|
f.page.on('request', request => {
|
|
const url = new URL(request.url());
|
|
if (url.pathname === '/api/v2/datasets/canonical') {
|
|
listResponses.push(url.search);
|
|
}
|
|
});
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
const choice = f.page.getByLabel('Canonical dataset', { exact: true });
|
|
await f.page
|
|
.getByRole('button', { name: 'Load more canonical datasets', exact: true })
|
|
.waitFor();
|
|
expect(await choice.locator(`option[value="${older.manifest.hash}"]`).count()).toBe(0);
|
|
expect(await choice.locator(`option[value="${known.manifest.hash}"]`).count()).toBe(0);
|
|
await f.page.getByLabel('Retained dataset hash', { exact: true }).fill(known.manifest.hash);
|
|
const lookup = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/api/v2/datasets/canonical/${known.manifest.hash}`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Use dataset hash', exact: true }).click();
|
|
expect((await lookup).status()).toBe(200);
|
|
await until(
|
|
() => choice.inputValue().then(value => value === known.manifest.hash),
|
|
'known hash selection'
|
|
);
|
|
await downloadDatasetInBrowser(f, known);
|
|
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(before);
|
|
await f.page.getByRole('button', { name: 'Load more canonical datasets', exact: true }).click();
|
|
await choice.locator(`option[value="${older.manifest.hash}"]`).waitFor({ state: 'attached' });
|
|
expect(listResponses).toContain('?limit=50&offset=50');
|
|
expect(await choice.inputValue()).toBe(known.manifest.hash);
|
|
const values = await choice
|
|
.locator('option')
|
|
.evaluateAll(options => options.map(option => (option as HTMLOptionElement).value));
|
|
expect(new Set(values).size).toBe(values.length);
|
|
await choice.selectOption(older.manifest.hash);
|
|
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
await until(
|
|
() => f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).isEnabled(),
|
|
'older dataset verified and ready to save'
|
|
);
|
|
const saving = f.page.waitForResponse(
|
|
response =>
|
|
response.request().method() === 'PUT' && response.url().endsWith(`/api/v2/backtests/${id}`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).click();
|
|
const saved = await saving;
|
|
expect(saved.status()).toBe(200);
|
|
expect(saved.request().postDataJSON()).toMatchObject({
|
|
config: { datasetHash: older.manifest.hash },
|
|
startDate: new Date(bounds.tradeStart).toISOString(),
|
|
endDate: new Date(bounds.tradeEnd).toISOString(),
|
|
});
|
|
await f.page.reload();
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await until(
|
|
() => choice.inputValue().then(value => value === older.manifest.hash),
|
|
'saved older hash reopens outside first catalog page'
|
|
);
|
|
await f.page.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
await until(
|
|
() => f.page.getByRole('button', { name: 'Save canonical setup', exact: true }).isEnabled(),
|
|
'reopened retained metadata verified'
|
|
);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
|
0
|
|
);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('declared_session_source_browser_preserves_capture_and_retention_retry_across_tabs', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.login();
|
|
const { id, dataset } = await createCanonicalInBrowser(f, 'Declared session preparation');
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } =
|
|
dataset.manifest;
|
|
const start = bounds.warmupStart;
|
|
const end = dataset.bars.at(-1)!.intervalEnd;
|
|
const day = 86_400_000;
|
|
const metadata = {
|
|
calendars: calendars.map(calendar => ({
|
|
...calendar,
|
|
endDate: new Date(end + 2 * day).toISOString().slice(0, 10),
|
|
sessions: [
|
|
{ date: new Date(start).toISOString().slice(0, 10), open: start, close: end },
|
|
{
|
|
date: new Date(start + day).toISOString().slice(0, 10),
|
|
open: start + day,
|
|
close: end + day,
|
|
},
|
|
],
|
|
})),
|
|
series: series.map(value => ({
|
|
...value,
|
|
source: { provider: 'eod', revision: 'declared-two-session-browser-fixture' },
|
|
availability: 'interval-end-assumption',
|
|
})),
|
|
executionSeries,
|
|
bounds: { ...bounds, tradeEnd: end + day },
|
|
universe,
|
|
corporateActions: corporateActions.map(value => ({ ...value, end: end + day })),
|
|
};
|
|
const firstRows = dataset.bars.map(bar => ({
|
|
eodSearchCode: 'X0.US',
|
|
symbol: 'X0',
|
|
exchange: 'US',
|
|
timestamp: bar.intervalStart / 1000,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
}));
|
|
f.setStoredEodBars('eodIntraday1M', [
|
|
...firstRows,
|
|
{ ...firstRows[0]!, timestamp: end / 1000, volume: -1 },
|
|
...firstRows.map(row => ({ ...row, timestamp: row.timestamp + day / 1000 })),
|
|
]);
|
|
const before = await f.request(`/api/v2/backtests/${id}`);
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
|
|
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod-sessions');
|
|
await f.page.getByLabel('Source metadata JSON', { exact: true }).setInputFiles({
|
|
name: 'two-declared-sessions.json',
|
|
mimeType: 'application/json',
|
|
buffer: Buffer.from(JSON.stringify(metadata)),
|
|
});
|
|
const windows = f.page.getByRole('list', { name: 'Declared UTC query windows', exact: true });
|
|
await windows.waitFor({ state: 'visible' });
|
|
expect(await windows.getByRole('listitem').count()).toBe(2);
|
|
for (const offset of [0, day]) {
|
|
expect(await windows.textContent()).toContain(new Date(start + offset).toISOString());
|
|
expect(await windows.textContent()).toContain(new Date(end + offset).toISOString());
|
|
}
|
|
const previewing = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/canonical/stored-source')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
|
|
const response = await previewing;
|
|
expect(response.status()).toBe(200);
|
|
expect(response.request().postDataJSON()).toEqual({ metadata, selection: 'declared-sessions' });
|
|
const captured = (await response.json()) as CanonicalStoredSourcePreparation;
|
|
expect(captured.selection).toBe('declared-sessions');
|
|
expect(captured.input.bars).toHaveLength(2 * firstRows.length);
|
|
expect(f.storedSourceReads).toEqual(
|
|
[start, start + day].map(windowStart => ({
|
|
collection: 'eodIntraday1M',
|
|
filter: {
|
|
eodSearchCode: 'X0.US',
|
|
timestamp: { $gte: windowStart / 1000, $lt: (windowStart + end - start) / 1000 },
|
|
},
|
|
}))
|
|
);
|
|
await visible(f.page, `Dataset hash: ${captured.preparation.hash}`);
|
|
await f.page.getByLabel('Backtest name', { exact: true }).fill('Unsaved session research');
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
expect(await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).count()).toBe(
|
|
0
|
|
);
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await visible(f.page, `Dataset hash: ${captured.preparation.hash}`);
|
|
expect(await f.page.getByLabel('Backtest name', { exact: true }).inputValue()).toBe(
|
|
'Unsaved session research'
|
|
);
|
|
f.setStoredEodBars('eodIntraday1M', []);
|
|
// Commit through the real route, then lose its response. Navigating within
|
|
// this backtest must preserve the exact retry even after source deletion.
|
|
let lostInput: unknown;
|
|
const committed = gate();
|
|
const retentionPath = '**/api/v2/datasets/canonical/retain';
|
|
await f.page.route(retentionPath, async route => {
|
|
lostInput = route.request().postDataJSON();
|
|
const response = await route.fetch();
|
|
if (response.status() !== 200) {
|
|
throw new Error(`Expected committed fixture retention, got ${response.status()}`);
|
|
}
|
|
committed.resolve();
|
|
await route.abort('failed');
|
|
});
|
|
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
|
await committed.wait('retention committed before lost response');
|
|
await visible(f.page, /Retention is unconfirmed/);
|
|
await f.page.unroute(retentionPath);
|
|
expect(lostInput).toEqual({
|
|
input: captured.input,
|
|
expectedHash: captured.preparation.hash,
|
|
});
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
expect(
|
|
await f.page
|
|
.getByRole('button', { name: 'Retry retaining same dataset', exact: true })
|
|
.count()
|
|
).toBe(0);
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await visible(f.page, /Retention is unconfirmed/);
|
|
expect(await f.page.getByLabel('Dataset input', { exact: true }).isDisabled()).toBe(true);
|
|
const retaining = f.page.waitForResponse(result =>
|
|
result.url().endsWith('/api/v2/datasets/canonical/retain')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Retry retaining same dataset', exact: true }).click();
|
|
const retained = await retaining;
|
|
expect(retained.status()).toBe(200);
|
|
expect(retained.request().postDataJSON()).toEqual({
|
|
input: captured.input,
|
|
expectedHash: captured.preparation.hash,
|
|
});
|
|
await until(
|
|
async () =>
|
|
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
|
|
captured.preparation.hash,
|
|
'declared-session snapshot selection'
|
|
);
|
|
expect(f.storedSourceReads).toHaveLength(2);
|
|
expect(
|
|
(
|
|
await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
|
|
captured.preparation.hash,
|
|
])
|
|
).rows[0].payload
|
|
).toEqual(createDatasetV2(captured.input));
|
|
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(before);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM runs')).rows[0].n).toBe(0);
|
|
expect((await f.pool.query('SELECT count(*)::int AS n FROM backtest_dispatch')).rows[0].n).toBe(
|
|
0
|
|
);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('stored_source_inspection_browser_keeps_utc_scope_and_research_state_unchanged', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.login();
|
|
const { id, dataset } = await createCanonicalInBrowser(f, 'Stored source inspection');
|
|
const rows = dataset.bars.map((bar, index) => ({
|
|
eodSearchCode: 'X0.US',
|
|
symbol: 'X0',
|
|
exchange: 'US',
|
|
timestamp: bar.intervalStart / 1000,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: index === 0 ? -1 : bar.volume,
|
|
}));
|
|
f.setStoredEodBars('eodIntraday1M', rows);
|
|
const first = Math.min(...rows.map(row => row.timestamp)) * 1000;
|
|
const last = Math.max(...rows.map(row => row.timestamp)) * 1000;
|
|
const coverageRequests: URL[] = [];
|
|
// Mongo aggregation has separate real-server coverage. This response fixture
|
|
// drives the browser picker; the following inspection uses the real HTTP API.
|
|
await f.page.route(/\/api\/v2\/datasets\/stored-eod\/coverage(?:\?.*)?$/, route => {
|
|
coverageRequests.push(new URL(route.request().url()));
|
|
return route.fulfill({
|
|
json: {
|
|
version: 'stored-eod-coverage/v1',
|
|
observedAt: first,
|
|
query: { instrumentId: 'X0.US', interval: '1m' },
|
|
series: [
|
|
{
|
|
instrumentId: 'X0.US',
|
|
interval: '1m',
|
|
rowCount: rows.length,
|
|
firstTimestamp: first,
|
|
lastTimestamp: last,
|
|
invalidTimestampRows: 0,
|
|
},
|
|
],
|
|
},
|
|
});
|
|
});
|
|
const template = await f.request(`/api/v2/backtests/${id}`);
|
|
const templateWrites: string[] = [];
|
|
f.page.on('request', request => {
|
|
if (
|
|
request.method() === 'PUT' &&
|
|
new URL(request.url()).pathname === `/api/v2/backtests/${id}`
|
|
) {
|
|
templateWrites.push(request.url());
|
|
}
|
|
});
|
|
const counts = async () =>
|
|
(
|
|
await f.pool.query(`SELECT
|
|
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
|
|
(SELECT count(*)::int FROM runs) AS runs,
|
|
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
|
).rows[0];
|
|
const before = await counts();
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
|
|
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod');
|
|
const inspector = f.page.getByRole('region', { name: 'Stored source inspection', exact: true });
|
|
await inspector.waitFor();
|
|
expect(coverageRequests).toHaveLength(0);
|
|
await inspector.getByLabel('Inspect instrument', { exact: true }).fill('X0.US');
|
|
await inspector.getByLabel('Inspect timeframe', { exact: true }).selectOption('1m');
|
|
await inspector.getByLabel('Inspect instrument', { exact: true }).press('Enter');
|
|
expect(coverageRequests).toHaveLength(0);
|
|
await inspector.getByRole('button', { name: 'Load selected coverage', exact: true }).click();
|
|
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).waitFor();
|
|
expect(coverageRequests).toHaveLength(1);
|
|
expect(Object.fromEntries(coverageRequests[0]!.searchParams)).toEqual({
|
|
instrumentId: 'X0.US',
|
|
interval: '1m',
|
|
});
|
|
expect(await inspector.getByLabel('Inspect start UTC', { exact: true }).inputValue()).toBe('');
|
|
expect(await inspector.getByLabel('Inspect end UTC', { exact: true }).inputValue()).toBe('');
|
|
await inspector.getByRole('button', { name: 'Use coverage dates', exact: true }).click();
|
|
expect(await inspector.getByLabel('Inspect instrument', { exact: true }).inputValue()).toBe(
|
|
'X0.US'
|
|
);
|
|
expect(await inspector.getByLabel('Inspect timeframe', { exact: true }).inputValue()).toBe(
|
|
'1m'
|
|
);
|
|
const inspecting = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/stored-eod/inspect')
|
|
);
|
|
await inspector.getByRole('button', { name: 'Inspect source window', exact: true }).click();
|
|
const response = await inspecting;
|
|
expect(response.status()).toBe(200);
|
|
expect(response.request().postDataJSON()).toEqual({
|
|
instrumentId: 'X0.US',
|
|
interval: '1m',
|
|
start: first,
|
|
end: last + 60000,
|
|
});
|
|
const inspected = await response.json();
|
|
expect(inspected.invalidRows).toBe(1);
|
|
expect(inspected.rowCount).toBe(rows.length);
|
|
await inspector.getByText('Invalid volume: 1 rows', { exact: true }).waitFor();
|
|
await visible(f.page, /No rows were changed or excluded/);
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
expect(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()).toBe(
|
|
dataset.manifest.hash
|
|
);
|
|
expect(await counts()).toEqual(before);
|
|
expect(await f.request(`/api/v2/backtests/${id}`)).toEqual(template);
|
|
expect(templateWrites).toEqual([]);
|
|
expect(f.storedSourceReads).toEqual([
|
|
{
|
|
collection: 'eodIntraday1M',
|
|
filter: {
|
|
eodSearchCode: 'X0.US',
|
|
timestamp: { $gte: first / 1000, $lt: (last + 60000) / 1000 },
|
|
},
|
|
},
|
|
]);
|
|
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();
|
|
let retained = oracle.dataset.manifest;
|
|
const { calendars, series, executionSeries, bounds, universe, corporateActions } = retained;
|
|
// Explicit synthetic source export, with the same reviewed next-open oracle.
|
|
// The browser submits raw source rows; only the server normalizes/hashes them.
|
|
const source: HistoricalDatasetInputV2 = {
|
|
metadata: { calendars, series, executionSeries, bounds, universe, corporateActions },
|
|
bars: oracle.dataset.bars.map(bar => ({
|
|
seriesId: bar.seriesId,
|
|
timestamp: bar.intervalStart,
|
|
availableAt: bar.availableAt,
|
|
sourceSequence: bar.sourceSequence,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
vwap: bar.vwap,
|
|
})),
|
|
};
|
|
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('Initial capital (USD)', { exact: true }).fill('10000');
|
|
const templateBeforePreparation = await f.request(`/api/v2/backtests/${backtestId}`);
|
|
const preparationCounts = async () =>
|
|
(
|
|
await f.pool.query(`SELECT
|
|
(SELECT count(*)::int FROM backtest_datasets) AS datasets,
|
|
(SELECT count(*)::int FROM runs) AS runs,
|
|
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
|
).rows[0];
|
|
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
|
|
await f.page.getByText('Prepare dataset from source export', { exact: true }).click();
|
|
await f.page.getByLabel('Source dataset JSON', { exact: true }).setInputFiles({
|
|
name: 'reviewed-synthetic-source.json',
|
|
mimeType: 'application/json',
|
|
buffer: Buffer.from(JSON.stringify(source)),
|
|
});
|
|
const previewingDataset = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/canonical/preview')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
|
|
const previewedDataset = await previewingDataset;
|
|
expect(previewedDataset.status()).toBe(200);
|
|
expect(previewedDataset.request().postDataJSON()).toEqual({ input: source });
|
|
const preview = (await previewedDataset.json()) as {
|
|
preparation: CanonicalDatasetPreparation;
|
|
};
|
|
expect(preview.preparation.manifest).toEqual(retained);
|
|
expect(preview.preparation.hash).toBe(retained.hash);
|
|
expect(preview.preparation.available).toBe(true);
|
|
// Exercise real HTTP JSON consumption above the former web-server 1 MiB cap.
|
|
// Whitespace changes transport size without changing the economic oracle.
|
|
const largePreview = await f.page.evaluate(async input => {
|
|
const body = JSON.stringify({ input }) + ' '.repeat(1_048_576);
|
|
const response = await fetch('/api/v2/datasets/canonical/preview', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body,
|
|
});
|
|
return {
|
|
bytes: new TextEncoder().encode(body).byteLength,
|
|
status: response.status,
|
|
cacheControl: response.headers.get('Cache-Control'),
|
|
result: await response.json(),
|
|
};
|
|
}, source);
|
|
expect(largePreview.bytes).toBeGreaterThan(1_048_576);
|
|
expect(largePreview.status).toBe(200);
|
|
expect(largePreview.cacheControl).toBe('no-store');
|
|
expect(largePreview.result).toEqual(preview);
|
|
await visible(f.page, `Dataset hash: ${retained.hash}`);
|
|
const calendarDetails = f.page
|
|
.getByRole('region', { name: 'Prepared dataset metadata', exact: true })
|
|
.getByText(/^Calendar:/);
|
|
await calendarDetails.waitFor();
|
|
expect(await calendarDetails.textContent()).toContain(
|
|
`Revision: ${retained.calendars[0]!.revision}`
|
|
);
|
|
expect(await preparationCounts()).toEqual({ datasets: 0, runs: 0, dispatch: 0 });
|
|
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
|
|
const retainingDataset = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/canonical/retain')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
|
const retainedDataset = await retainingDataset;
|
|
expect(retainedDataset.status()).toBe(200);
|
|
const retainedRequest = retainedDataset.request().postDataJSON();
|
|
expect(retainedRequest).toEqual({ input: source, expectedHash: retained.hash });
|
|
expect(await retainedDataset.json()).toEqual(preview);
|
|
// Exact replay is safe after a lost response: one immutable row, no new jobs.
|
|
expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', retainedRequest)).toEqual(
|
|
preview
|
|
);
|
|
expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 });
|
|
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
|
|
expect(
|
|
(await f.pool.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [retained.hash]))
|
|
.rows[0].payload
|
|
).toEqual(oracle.dataset);
|
|
await until(
|
|
async () =>
|
|
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
|
|
retained.hash,
|
|
'retained source dataset selected in canonical setup'
|
|
);
|
|
expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe(
|
|
'10000'
|
|
);
|
|
// Materialize an actual stored EOD source through the same panel, then edit
|
|
// the mutable store. Retention and execution must keep the displayed bytes.
|
|
const storedMetadata = {
|
|
...source.metadata,
|
|
series: source.metadata.series.map(series => ({
|
|
...series,
|
|
source: { provider: 'eod', revision: 'declared-browser-source-v1' },
|
|
availability: 'interval-end-assumption' as const,
|
|
})),
|
|
};
|
|
const storedRows = oracle.dataset.bars.map(bar => ({
|
|
eodSearchCode: 'X0.US',
|
|
symbol: 'X0',
|
|
exchange: 'US',
|
|
timestamp: bar.intervalStart / 1000,
|
|
open: bar.open,
|
|
high: bar.high,
|
|
low: bar.low,
|
|
close: bar.close,
|
|
volume: bar.volume,
|
|
}));
|
|
f.setStoredEodBars('eodIntraday1M', storedRows);
|
|
await f.page.getByLabel('Dataset input', { exact: true }).selectOption('stored-eod');
|
|
await f.page.getByLabel('Source metadata JSON', { exact: true }).setInputFiles({
|
|
name: 'declared-stored-eod-metadata.json',
|
|
mimeType: 'application/json',
|
|
buffer: Buffer.from(JSON.stringify(storedMetadata)),
|
|
});
|
|
const loadingStored = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/canonical/stored-source')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Preview dataset', exact: true }).click();
|
|
const storedResponse = await loadingStored;
|
|
expect(storedResponse.status()).toBe(200);
|
|
expect(storedResponse.headers()['cache-control']).toBe('no-store');
|
|
expect(storedResponse.request().postDataJSON()).toEqual({ metadata: storedMetadata });
|
|
const materialized = (await storedResponse.json()) as CanonicalStoredSourcePreparation;
|
|
expect(materialized.input.metadata).toEqual(storedMetadata);
|
|
expect(materialized.input.bars).toHaveLength(oracle.dataset.bars.length);
|
|
expect(materialized.input.bars.every(bar => bar.availableAt === undefined)).toBe(true);
|
|
const expectedStored = createDatasetV2(materialized.input);
|
|
expect(materialized.preparation.manifest).toEqual(expectedStored.manifest);
|
|
expect(expectedStored.bars).toEqual(oracle.dataset.bars);
|
|
expect(materialized.preparation.hash).not.toBe(retained.hash);
|
|
expect(f.storedSourceReads).toEqual([
|
|
{
|
|
collection: 'eodIntraday1M',
|
|
filter: {
|
|
eodSearchCode: 'X0.US',
|
|
timestamp: { $gte: bounds.warmupStart / 1000, $lt: bounds.tradeEnd / 1000 },
|
|
},
|
|
},
|
|
]);
|
|
await visible(f.page, `Dataset hash: ${materialized.preparation.hash}`);
|
|
await visible(f.page, /Availability is explicitly assumed at interval end/);
|
|
expect(await preparationCounts()).toEqual({ datasets: 1, runs: 0, dispatch: 0 });
|
|
// A fresh preview observes corrected provider history; the current UI
|
|
// preview and its retention payload must remain the previously captured one.
|
|
f.setStoredEodBars(
|
|
'eodIntraday1M',
|
|
storedRows.map(row => ({
|
|
...row,
|
|
open: row.open + 100,
|
|
high: row.high + 100,
|
|
low: row.low + 100,
|
|
close: row.close + 100,
|
|
}))
|
|
);
|
|
const refreshedSource = (await f.request('/api/v2/datasets/canonical/stored-source', 'POST', {
|
|
metadata: storedMetadata,
|
|
})) as CanonicalStoredSourcePreparation;
|
|
expect(refreshedSource.preparation.hash).not.toBe(materialized.preparation.hash);
|
|
expect(f.storedSourceReads).toHaveLength(2);
|
|
const retainingStored = f.page.waitForResponse(response =>
|
|
response.url().endsWith('/api/v2/datasets/canonical/retain')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Retain dataset', exact: true }).click();
|
|
const storedRetention = await retainingStored;
|
|
expect(storedRetention.status()).toBe(200);
|
|
const capturedRequest = storedRetention.request().postDataJSON();
|
|
expect(capturedRequest).toEqual({
|
|
input: materialized.input,
|
|
expectedHash: materialized.preparation.hash,
|
|
});
|
|
expect(await storedRetention.json()).toEqual({ preparation: materialized.preparation });
|
|
expect(await f.request('/api/v2/datasets/canonical/retain', 'POST', capturedRequest)).toEqual({
|
|
preparation: materialized.preparation,
|
|
});
|
|
expect(f.storedSourceReads).toHaveLength(2);
|
|
expect(await preparationCounts()).toEqual({ datasets: 2, runs: 0, dispatch: 0 });
|
|
expect(await f.request(`/api/v2/backtests/${backtestId}`)).toEqual(templateBeforePreparation);
|
|
retained = expectedStored.manifest;
|
|
await until(
|
|
async () =>
|
|
(await f.page.getByLabel('Canonical dataset', { exact: true }).inputValue()) ===
|
|
retained.hash,
|
|
'captured stored source selected for canonical execution'
|
|
);
|
|
expect(await f.page.getByLabel('Initial capital (USD)', { exact: true }).inputValue()).toBe(
|
|
'10000'
|
|
);
|
|
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.');
|
|
// Move the cited hypothesis forward so the exact link requires history resolution.
|
|
await f.request(`/api/v2/hypotheses/${hypothesis.id}/revisions`, 'POST', {
|
|
expectedRevision: 1,
|
|
title: 'Revised AI trend hypothesis',
|
|
proposition: 'A revised hypothesis, still not validated alpha.',
|
|
validationCriteria: 'Out-of-sample evidence required.',
|
|
contentOrigin: 'ai',
|
|
});
|
|
const { hypothesis: unrelatedHypothesis } = await f.request(
|
|
`/api/v2/research-projects/${project.id}/hypotheses`,
|
|
'POST',
|
|
{ title: 'Unrelated hypothesis', proposition: 'Separate future investigation.' }
|
|
);
|
|
const unrelatedHistoryPath = `**/api/v2/hypotheses/${unrelatedHypothesis.id}/revisions`;
|
|
await f.page.route(unrelatedHistoryPath, route =>
|
|
route.fulfill({ status: 503, json: { error: 'Unrelated history unavailable' } })
|
|
);
|
|
const unrelatedHistoryFailure = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/hypotheses/${unrelatedHypothesis.id}/revisions`)
|
|
);
|
|
await f.page.reload();
|
|
expect((await unrelatedHistoryFailure).status()).toBe(503);
|
|
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 f.page.unroute(unrelatedHistoryPath);
|
|
await visible(f.page, 'A hypothesis, not validated alpha.');
|
|
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.storedSourceReads).toHaveLength(2);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('isolated_candidate_publication_research_validation_and_reviewed_paper_history_browser', async () => {
|
|
const f = await fixture(true);
|
|
try {
|
|
const data = chronologicalDataset();
|
|
await retainResearchDataset(f.pool, data.dataset);
|
|
const builtin = (await f.seedCatalog()).find(
|
|
item => item.package.program.strategyId === 'sma_crossover'
|
|
)!;
|
|
await f.request(`/api/v2/strategy-versions/${builtin.id}/reviews`, 'POST', {
|
|
decision: 'approve',
|
|
reason: 'Disposable template baseline',
|
|
});
|
|
const retained = (await f.request(`/api/v2/strategy-versions/${builtin.id}/artifact`)).package;
|
|
const pkg = { ...retained, execution: { kind: 'isolated-candidate/v1', warmupBars: 3 } };
|
|
const family = (
|
|
await f.request('/api/v2/strategies', 'POST', {
|
|
name: 'Browser isolated candidate',
|
|
description: 'Retained controlled parity program',
|
|
})
|
|
).strategy;
|
|
await f.login();
|
|
await f.page.goto(`${f.origin}/strategies/${family.id}`);
|
|
await f.page.getByLabel('Candidate package (JSON)').setInputFiles({
|
|
name: 'candidate.json',
|
|
mimeType: 'application/json',
|
|
buffer: Buffer.from(JSON.stringify(pkg)),
|
|
});
|
|
await visible(f.page, pkg.artifact.sha256);
|
|
const published = f.page.waitForResponse(
|
|
response =>
|
|
response.request().method() === 'POST' &&
|
|
response.url().endsWith(`/strategies/${family.id}/versions`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Publish immutable candidate', exact: true }).click();
|
|
const publication = await published;
|
|
expect(publication.status()).toBe(201);
|
|
const version = (await publication.json()).version;
|
|
expect(version.origin).toBe('candidate');
|
|
await f.page.waitForURL(url => url.pathname.endsWith(`/versions/${version.id}`));
|
|
expect((await f.pool.query('SELECT count(*)::int AS count FROM runs')).rows[0].count).toBe(0);
|
|
const draft = await f.request('/api/v2/backtests', 'POST', {
|
|
name: 'Browser candidate template',
|
|
autoStart: false,
|
|
strategy: 'catalog',
|
|
strategyVersionId: builtin.id,
|
|
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
symbols: ['X0.US'],
|
|
startDate: new Date(data.dataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(data.dataset.manifest.bounds.tradeEnd).toISOString(),
|
|
initialCapital: 10000,
|
|
config: {
|
|
datasetHash: data.dataset.manifest.hash,
|
|
dataFrequency: '1m',
|
|
canonical: canonicalSettings,
|
|
},
|
|
});
|
|
await f.page.goto(`${f.origin}/experiments?backtestId=${draft.id}`);
|
|
await f.page.getByLabel('Experiment name', { exact: true }).fill('Isolated browser experiment');
|
|
await f.page.getByLabel('Use an isolated candidate version', { exact: true }).check();
|
|
const section = f.page.getByRole('region', {
|
|
name: 'Candidate experiment strategy',
|
|
exact: true,
|
|
});
|
|
await section.getByLabel('Strategy family', { exact: true }).selectOption(family.id);
|
|
await section
|
|
.getByLabel('Immutable strategy version', { exact: true })
|
|
.selectOption(version.id);
|
|
await section.getByLabel('fastPeriod', { exact: true }).fill('2');
|
|
await section.getByLabel('slowPeriod', { exact: true }).fill('3');
|
|
await section.getByRole('button', { name: 'Validate parameters', exact: true }).click();
|
|
await visible(f.page, /Parameters validated/);
|
|
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
|
|
await visible(f.page, /Isolated TypeScript candidate/);
|
|
const submitted = 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 experiment = (await (await submitted).json()).experiment as ExperimentDetail;
|
|
expect(experiment.preview.input.candidate).toEqual({
|
|
versionId: version.id,
|
|
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
|
});
|
|
expect(experiment.preview.request.strategy.reviewId).toBeNull();
|
|
await f.dispatcher.start();
|
|
const completeExperiment = async (id: string) => {
|
|
await until(
|
|
async () =>
|
|
(await f.request(`/api/v2/experiments/${id}`)).experiment.trials.every(
|
|
(trial: { status: string }) =>
|
|
['completed', 'failed', 'cancelled', 'missing'].includes(trial.status)
|
|
),
|
|
'candidate trials finish',
|
|
45000
|
|
);
|
|
const result = (await f.request(`/api/v2/experiments/${id}`)).experiment;
|
|
expect(result.trials.every((trial: { status: string }) => trial.status === 'completed')).toBe(
|
|
true
|
|
);
|
|
return result;
|
|
};
|
|
const completed = await completeExperiment(experiment.id);
|
|
const runId = completed.trials[0].runId;
|
|
const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
|
|
expect(result.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
|
expect(result.request.strategy.origin).toBe('candidate');
|
|
await f.page.goto(`${f.origin}/backtests/${draft.id}/run/${runId}`);
|
|
await visible(f.page, /isolated TypeScript candidate/);
|
|
await f.page.reload();
|
|
await visible(f.page, result.request.datasetHash);
|
|
|
|
// Reproduction of an isolated candidate does not require inventing a human review.
|
|
const candidateReviewCount = async () =>
|
|
(
|
|
await f.pool.query(
|
|
'SELECT count(*)::int AS count FROM strategy_review_events WHERE version_id=$1',
|
|
[version.id]
|
|
)
|
|
).rows[0].count;
|
|
expect(await candidateReviewCount()).toBe(0);
|
|
const previewingReproduction = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/runs/${runId}/reproduction`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
|
|
const reproductionPreview = await previewingReproduction;
|
|
expect(reproductionPreview.status()).toBe(200);
|
|
expect(await reproductionPreview.json()).toMatchObject({
|
|
originalRunId: runId,
|
|
available: true,
|
|
currentReviewId: null,
|
|
request: { strategy: { origin: 'candidate', reviewId: null } },
|
|
});
|
|
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(result.request.datasetHash);
|
|
expect(await originalInputs.textContent()).toContain(version.id);
|
|
const reproducing = f.page.waitForResponse(
|
|
response =>
|
|
response.request().method() === 'POST' &&
|
|
response.url().endsWith(`/runs/${runId}/reproduce`)
|
|
);
|
|
await reproductionDialog
|
|
.getByRole('button', { name: 'Confirm reproduction', exact: true })
|
|
.click();
|
|
const reproducedResponse = await reproducing;
|
|
expect(reproducedResponse.status()).toBe(202);
|
|
expect(reproducedResponse.request().postDataJSON()).toEqual({});
|
|
const receipt = reproducedResponse.request().headers()['idempotency-key']!;
|
|
expect(receipt).toBeTruthy();
|
|
const reproducedRun = await reproducedResponse.json();
|
|
expect(reproducedRun.originalRunId).toBe(runId);
|
|
expect(reproducedRun.id).not.toBe(runId);
|
|
await f.page.waitForURL(`${f.origin}/backtests/${draft.id}/run/${reproducedRun.id}`);
|
|
const duplicate = await f.request(
|
|
`/api/v2/runs/${runId}/reproduce`,
|
|
'POST',
|
|
{},
|
|
{
|
|
'Idempotency-Key': receipt,
|
|
}
|
|
);
|
|
expect(duplicate.id).toBe(reproducedRun.id);
|
|
await visible(f.page, 'Economic results match the original.');
|
|
const reproducedResult = (await f.request(
|
|
`/api/v2/runs/${reproducedRun.id}/results`
|
|
)) as CanonicalRunResult;
|
|
expect(reproducedResult.strategyExecution).toBe('typescript-isolated-candidate/v1');
|
|
expect(reproducedResult.request.strategy).toEqual(result.request.strategy);
|
|
expect(reproducedResult.request.build).toEqual(result.request.build);
|
|
expect(reproducedResult.request.datasetHash).toBe(result.request.datasetHash);
|
|
expect(reproducedResult.financial.projection.valuation).toEqual(
|
|
result.financial.projection.valuation
|
|
);
|
|
expect(reproducedResult.analytics).toEqual(result.analytics);
|
|
expect(await f.request(`/api/v2/runs/${runId}/results`)).toEqual(result);
|
|
expect(await candidateReviewCount()).toBe(0);
|
|
expect(
|
|
(await f.pool.query('SELECT id FROM runs WHERE original_run_id=$1', [runId])).rowCount
|
|
).toBe(1);
|
|
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(`${f.origin}/backtests/${draft.id}/run/${runId}`);
|
|
|
|
// Real immutable validation and cost evidence prepare the human promotion screen.
|
|
const candidate = { versionId: version.id, parameters: { fastPeriod: 2, slowPeriod: 3 } };
|
|
const validationInput = {
|
|
backtestId: draft.id,
|
|
name: 'Browser candidate holdouts',
|
|
grid: {},
|
|
recipe: data.recipe,
|
|
candidate,
|
|
};
|
|
const previewResponse = await f.request(
|
|
'/api/v2/experiments/validation/preview',
|
|
'POST',
|
|
validationInput
|
|
);
|
|
const preview = previewResponse.preview as ChronologicalValidationPreview;
|
|
const validation = (
|
|
await f.request(
|
|
'/api/v2/experiments/validation',
|
|
'POST',
|
|
{ ...validationInput, previewHash: preview.previewHash },
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)
|
|
).validation as ChronologicalValidationDetail;
|
|
expect(preview.policy.model).toBe('unverified-candidate');
|
|
await completeExperiment(validation.phases[0]!.experimentId!);
|
|
const selected = (await f.request(
|
|
`/api/v2/experiments/validation/${validation.id}/select`,
|
|
'POST',
|
|
{ previewHash: preview.previewHash },
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)) as ChronologicalValidationActionResult;
|
|
for (const phase of selected.validation.phases.slice(1)) {
|
|
await completeExperiment(phase.experimentId!);
|
|
}
|
|
const finished = (await f.request(
|
|
`/api/v2/experiments/validation/${validation.id}/finalize`,
|
|
'POST',
|
|
{
|
|
previewHash: preview.previewHash,
|
|
selectionHash: selected.validation.selection!.selectionHash,
|
|
},
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)) as ChronologicalValidationActionResult;
|
|
expect(finished.validation.report).not.toBeNull();
|
|
const costInput = {
|
|
backtestId: draft.id,
|
|
name: 'Browser candidate costs',
|
|
scenarios: [{ feeRate: '0.02', slippageRate: '0.01' }],
|
|
candidate,
|
|
};
|
|
const costPreview = (
|
|
await f.request('/api/v2/experiments/cost-sensitivity/preview', 'POST', costInput)
|
|
).preview as CostSensitivityPreview;
|
|
const cost = (
|
|
await f.request(
|
|
'/api/v2/experiments/cost-sensitivity',
|
|
'POST',
|
|
{ ...costInput, previewHash: costPreview.previewHash },
|
|
{ 'Idempotency-Key': randomUUID() }
|
|
)
|
|
).experiment as CostSensitivityDetail;
|
|
await completeExperiment(cost.id);
|
|
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
|
|
decision: 'approve',
|
|
reason: 'Human reviewed controlled candidate bytes and actual held-out/cost evidence',
|
|
});
|
|
await f.page.goto(`${f.origin}/paper`);
|
|
await visible(f.page, /No paper deployments/);
|
|
await f.page.getByLabel('Deployment name', { exact: true }).fill('Reviewed browser candidate');
|
|
await f.page.getByLabel('Report owner ID', { exact: true }).fill(validation.id);
|
|
await f.page.getByLabel('Cost experiment ID', { exact: true }).fill(cost.id);
|
|
await f.page.getByRole('button', { name: 'Load evidence', exact: true }).click();
|
|
await f.page
|
|
.getByLabel('Paper cost scenario', { exact: true })
|
|
.selectOption(cost.trials[1]!.runId!);
|
|
const start = Date.parse('2030-01-01T14:30:00Z');
|
|
await f.page.getByLabel('Paper transport', { exact: true }).fill(
|
|
JSON.stringify({
|
|
accountId: `paper:${randomUUID()}`,
|
|
sessionId: `paper:${randomUUID()}`,
|
|
quoteSeriesId: 'X0.US:quote',
|
|
riskSession: {
|
|
calendarId: 'paper-risk',
|
|
calendarRevision: 'v1',
|
|
sessionId: 'paper-day',
|
|
startsAt: start,
|
|
},
|
|
policy: {
|
|
version: 1,
|
|
sourceId: 'disposable-browser-feed',
|
|
priceBasis: 'raw',
|
|
maxFeedAgeMs: 300000,
|
|
observations: [
|
|
{
|
|
instrumentId: 'X0.US',
|
|
seriesId: 'X0.US:1m',
|
|
intervalMs: 60000,
|
|
staleAfterMs: 300000,
|
|
},
|
|
],
|
|
cadence: [{ ownerId: `strategy:${version.id}`, seriesIds: ['X0.US:1m'] }],
|
|
calendars: [
|
|
{
|
|
instrumentId: 'X0.US',
|
|
calendarId: 'explicit-venue',
|
|
revision: 'v1',
|
|
sessions: [{ sessionId: 'paper-day', opensAt: start, closesAt: start + 3600000 }],
|
|
},
|
|
],
|
|
riskBoundaries: [],
|
|
},
|
|
})
|
|
);
|
|
await f.page
|
|
.getByLabel('Review rationale', { exact: true })
|
|
.fill(
|
|
'Controlled fixture evidence and code reviewed; no profitability claim or real activation.'
|
|
);
|
|
await f.page.getByLabel('Authorize trusted paper code', { exact: true }).check();
|
|
await f.page.getByRole('button', { name: 'Preview promotion', exact: true }).click();
|
|
await visible(f.page, 'Exact promotion preview');
|
|
const promotionResponse = f.page.waitForResponse(
|
|
response =>
|
|
response.request().method() === 'POST' &&
|
|
response.url().endsWith('/api/v2/paper-deployments')
|
|
);
|
|
await f.page.getByRole('button', { name: 'Create halted deployment', exact: true }).click();
|
|
const promoted = await promotionResponse;
|
|
expect(promoted.status()).toBe(201);
|
|
const deployment = await promoted.json();
|
|
await f.page.waitForURL(url => url.pathname.endsWith(`/paper/${deployment.id}`));
|
|
await visible(f.page, 'Reviewed browser candidate');
|
|
await visible(f.page, /Paper orchestrator origin is not configured/);
|
|
expect(
|
|
(await f.pool.query('SELECT count(*)::int AS count FROM simulation_accounts')).rows[0].count
|
|
).toBe(0);
|
|
await f.page.reload();
|
|
await visible(f.page, 'Reviewed browser candidate');
|
|
expect(
|
|
(await f.request(`/api/v2/paper-deployments/${deployment.id}`)).preview.strategy.versionId
|
|
).toBe(version.id);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
}, 180000);
|