994 lines
36 KiB
TypeScript
994 lines
36 KiB
TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
import { GlobalWindow } from 'happy-dom';
|
|
import { act, createElement, type ReactElement } from 'react';
|
|
import type { Root } from 'react-dom/client';
|
|
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
|
import {
|
|
costSensitivityInputSchema,
|
|
type CostSensitivityDetail,
|
|
type CostSensitivityPreview,
|
|
} from '@stock-bot/stock-config/cost-sensitivity';
|
|
import type {
|
|
ExperimentComparison,
|
|
ExperimentComparisonInput,
|
|
} from '@stock-bot/stock-config/experiment-comparison';
|
|
import type {
|
|
ExperimentDetail,
|
|
ExperimentPreview,
|
|
ExperimentTrial,
|
|
} from '@stock-bot/stock-config/experiments';
|
|
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
|
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
let parseExperimentComparison: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').parseExperimentComparison;
|
|
let experimentComparisonApi: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').experimentComparisonApi;
|
|
let parseComparisonQuery: typeof import('../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi').parseComparisonQuery;
|
|
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
|
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
|
let createRoot: typeof import('react-dom/client').createRoot;
|
|
let router: typeof import('react-router-dom');
|
|
let ExperimentListPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentListPage;
|
|
let ExperimentComparisonPage: typeof import('../../apps/stock/web-app/src/features/experiments/ExperimentComparisonPage').ExperimentComparisonPage;
|
|
let root: Root | undefined;
|
|
let host: HTMLDivElement;
|
|
let navigate: ReturnType<typeof router.useNavigate>;
|
|
let location = '';
|
|
const backtestId = '11111111-1111-4111-8111-111111111111';
|
|
const otherBacktestId = '22222222-2222-4222-8222-222222222222';
|
|
const experimentId = '33333333-3333-4333-8333-333333333333';
|
|
const otherExperimentId = '44444444-4444-4444-8444-444444444444';
|
|
const versionId = '55555555-5555-4555-8555-555555555555';
|
|
const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`;
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (cause: Error) => void;
|
|
const promise = new Promise<T>((yes, no) => {
|
|
resolve = yes;
|
|
reject = no;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
type Pending = ReturnType<typeof deferred<Response>> & {
|
|
path: string;
|
|
method: string;
|
|
body: unknown;
|
|
rawBody: unknown;
|
|
headers: Headers;
|
|
settled: boolean;
|
|
signal?: AbortSignal | null;
|
|
credentials?: RequestCredentials;
|
|
};
|
|
const requests: Pending[] = [];
|
|
function request(path: string, method = 'GET') {
|
|
const found = requests.find(
|
|
item => item.path === path && item.method === method && !item.settled
|
|
);
|
|
if (!found) {
|
|
throw new Error(
|
|
`Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
|
);
|
|
}
|
|
return found;
|
|
}
|
|
function reply(item: Pending, value: unknown, status = 200) {
|
|
item.settled = true;
|
|
item.resolve(Response.json(value, { status }));
|
|
}
|
|
async function flush(action: () => void = () => {}) {
|
|
await act(async () => {
|
|
action();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
function button(label: string) {
|
|
const found = [...host.querySelectorAll('button')].find(
|
|
item => item.textContent?.trim() === label
|
|
);
|
|
if (!found) {
|
|
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
|
}
|
|
return found;
|
|
}
|
|
function field(label: string) {
|
|
const found = [...host.querySelectorAll('label')]
|
|
.find(
|
|
item => item.firstChild?.textContent?.trim() === label || item.textContent?.trim() === label
|
|
)
|
|
?.querySelector('input,select,textarea');
|
|
if (!found) {
|
|
throw new Error(`Missing field ${label}`);
|
|
}
|
|
return found as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
|
}
|
|
function change(label: string, value: string) {
|
|
const input = field(label);
|
|
const prototype =
|
|
input.tagName === 'SELECT'
|
|
? browser.HTMLSelectElement.prototype
|
|
: input.tagName === 'TEXTAREA'
|
|
? browser.HTMLTextAreaElement.prototype
|
|
: browser.HTMLInputElement.prototype;
|
|
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
|
input.dispatchEvent(
|
|
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
|
bubbles: true,
|
|
}) as unknown as Event
|
|
);
|
|
}
|
|
function Probe() {
|
|
navigate = router.useNavigate();
|
|
location = router.useLocation().pathname + router.useLocation().search;
|
|
return null;
|
|
}
|
|
async function render(element: ReactElement, path: string) {
|
|
root ??= createRoot(host);
|
|
await flush(() =>
|
|
root!.render(
|
|
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
|
)
|
|
);
|
|
}
|
|
const template = (id = backtestId): Backtest => ({
|
|
id,
|
|
name: 'Saved canonical template',
|
|
strategy: 'sma',
|
|
strategyVersionId: versionId,
|
|
symbols: ['X0.US'],
|
|
startDate: '2024-01-01',
|
|
endDate: '2024-01-02',
|
|
initialCapital: 100,
|
|
config: { canonical: {}, datasetHash: 'a'.repeat(64) },
|
|
archivedAt: null,
|
|
createdAt: '2026-10-24',
|
|
updatedAt: '2026-10-24',
|
|
});
|
|
function preview(count = 2, parent = backtestId): ExperimentPreview {
|
|
const owner = `strategy:${versionId}`;
|
|
const { config, dataset } = nativeReplayFixture(3, 1, [owner]);
|
|
const previewId = '00000000-0000-4000-8000-000000000001';
|
|
config.matching.risk.ledger.sessionId = previewId;
|
|
config.matching.risk.ledger.accountId = `research:${previewId}`;
|
|
const builtin = builtinCatalogDescriptors[0]!;
|
|
const candidates = Array.from({ length: count }, (_, index) => ({
|
|
index,
|
|
trialKey: String(index + 1).padStart(64, '0'),
|
|
parameters: { fastPeriod: index + 2, slowPeriod: 20 },
|
|
}));
|
|
return {
|
|
version: 'research-experiment-preview/v1',
|
|
previewHash: 'e'.repeat(64),
|
|
input: {
|
|
backtestId: parent,
|
|
name: 'Trend study',
|
|
grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
|
|
},
|
|
dataset: dataset.manifest,
|
|
candidates,
|
|
request: canonicalRunRequestSchema.parse({
|
|
kind: 'canonical-research/v1',
|
|
runId: previewId,
|
|
backtestId: parent,
|
|
name: 'Frozen template name',
|
|
strategy: {
|
|
familyId: '66666666-6666-4666-8666-666666666666',
|
|
versionId,
|
|
origin: 'builtin',
|
|
reviewId: '88888888-8888-4888-8888-888888888888',
|
|
package: {
|
|
version: 1,
|
|
program: builtin.program,
|
|
parameterSchema: builtin.parameterSchema,
|
|
artifact: {
|
|
format: 'esm-bundle/v1',
|
|
entryExport: builtin.entryExport,
|
|
content: 'Never execute fixture code',
|
|
sha256: 'a'.repeat(64),
|
|
},
|
|
dependencyLock: {
|
|
format: 'bun-lock/v1',
|
|
content: 'Retained lock',
|
|
sha256: 'b'.repeat(64),
|
|
},
|
|
source: { revision: 'c'.repeat(40), dirty: false },
|
|
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
|
},
|
|
selection: {
|
|
strategyId: builtin.program.strategyId,
|
|
strategyVersion: builtin.program.strategyVersion,
|
|
ownerId: owner,
|
|
seed: 17,
|
|
instrumentId: 'X0.US',
|
|
seriesId: 'X0.US:1m',
|
|
ownerBudget: '100',
|
|
parameters: { fastPeriod: 2, slowPeriod: 20 },
|
|
},
|
|
},
|
|
datasetHash: dataset.manifest.hash,
|
|
policy: config,
|
|
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
|
build: {
|
|
version: 1,
|
|
workerSha256: 'a'.repeat(64),
|
|
engineWrapperSha256: 'b'.repeat(64),
|
|
engineBinarySha256: 'c'.repeat(64),
|
|
dependencyLockSha256: 'd'.repeat(64),
|
|
runtime: 'bun',
|
|
runtimeVersion: '1.2.17',
|
|
platform: 'linux',
|
|
arch: 'x64',
|
|
},
|
|
modelArtifacts: [],
|
|
}),
|
|
};
|
|
}
|
|
function metrics(): NonNullable<ExperimentTrial['metrics']> {
|
|
return {
|
|
totalReturn: 0,
|
|
cagr: null,
|
|
maxDrawdown: 0,
|
|
exposureTime: 0,
|
|
volatility: null,
|
|
downsideDeviation: null,
|
|
sharpeRatio: null,
|
|
sortinoRatio: null,
|
|
var95: null,
|
|
cvar95: null,
|
|
var99: null,
|
|
alpha: null,
|
|
beta: null,
|
|
informationRatio: null,
|
|
roundTripCount: null,
|
|
winRate: null,
|
|
profitFactor: null,
|
|
avgWin: null,
|
|
avgLoss: null,
|
|
};
|
|
}
|
|
function detail(
|
|
source: ExperimentPreview | CostSensitivityPreview = preview(),
|
|
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
|
): ExperimentDetail | CostSensitivityDetail {
|
|
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
|
...structuredClone(item),
|
|
runId: statuses[index] === 'missing' ? null : runId(index),
|
|
attemptNumber: 0,
|
|
retryCount: 0,
|
|
status: statuses[index]!,
|
|
progress: statuses[index] === 'completed' ? 100 : 0,
|
|
cancelRequested: false,
|
|
error: statuses[index] === 'failed' ? 'Strategy callback failed' : null,
|
|
comparable: statuses[index] === 'completed',
|
|
diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null,
|
|
metrics: statuses[index] === 'completed' ? metrics() : null,
|
|
unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null,
|
|
limitations: [],
|
|
}));
|
|
return {
|
|
kind: source.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
|
id: experimentId,
|
|
name: source.input.name,
|
|
backtestId: source.input.backtestId,
|
|
createdAt: '2026-10-24T14:00:00Z',
|
|
cancelRequested: false,
|
|
trialCount: trials.length,
|
|
counts: {
|
|
pending: 0,
|
|
running: 0,
|
|
paused: 0,
|
|
completed: 0,
|
|
failed: 0,
|
|
cancelled: 0,
|
|
...Object.fromEntries(
|
|
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
|
status,
|
|
trials.filter(item => item.status === status).length,
|
|
])
|
|
),
|
|
},
|
|
datasetHash: source.request.datasetHash,
|
|
strategyVersionId: versionId,
|
|
previewHash: source.previewHash,
|
|
preview: source,
|
|
trials,
|
|
} as ExperimentDetail | CostSensitivityDetail;
|
|
}
|
|
function costs(
|
|
scenarios = [{ feeRate: '0.00100000', slippageRate: '0.00200000' }]
|
|
): CostSensitivityPreview {
|
|
const source = preview(1);
|
|
source.input.grid = {};
|
|
const input = costSensitivityInputSchema.parse({
|
|
backtestId: source.input.backtestId,
|
|
name: source.input.name,
|
|
scenarios,
|
|
});
|
|
const pairs = [
|
|
{
|
|
feeRate: source.request.policy.matching.risk.feeRate,
|
|
slippageRate: source.request.policy.matching.slippageRate,
|
|
},
|
|
...input.scenarios,
|
|
];
|
|
return {
|
|
version: 'cost-sensitivity-preview/v1',
|
|
previewHash: 'f'.repeat(64),
|
|
input,
|
|
source,
|
|
request: structuredClone(source.request),
|
|
dataset: structuredClone(source.dataset),
|
|
candidates: pairs.map((costs, index) => ({
|
|
index,
|
|
trialKey: String(index + 3).padStart(64, '0'),
|
|
parameters: { ...source.request.strategy.selection.parameters },
|
|
costs,
|
|
})),
|
|
};
|
|
}
|
|
beforeAll(async () => {
|
|
for (const [key, value] of Object.entries({
|
|
window: browser,
|
|
document: browser.document,
|
|
Event: browser.Event,
|
|
ResizeObserver: browser.ResizeObserver,
|
|
IS_REACT_ACT_ENVIRONMENT: true,
|
|
})) {
|
|
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
|
}
|
|
({ parseExperimentComparison, parseComparisonQuery, experimentComparisonApi } = await import(
|
|
'../../apps/stock/web-app/src/features/experiments/services/experimentComparisonApi'
|
|
));
|
|
({ createRoot } = await import('react-dom/client'));
|
|
router = await import('react-router-dom');
|
|
({ ExperimentListPage } = await import('../../apps/stock/web-app/src/features/experiments'));
|
|
({ ExperimentComparisonPage } = await import(
|
|
'../../apps/stock/web-app/src/features/experiments/ExperimentComparisonPage'
|
|
));
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = 0;
|
|
location = '';
|
|
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
|
browser.document.body.append(host as never);
|
|
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
|
Object.defineProperty(browser, 'fetch', {
|
|
configurable: true,
|
|
value: (input: unknown, init?: RequestInit) => {
|
|
const url = new URL(String(input));
|
|
const item: Pending = {
|
|
...deferred<Response>(),
|
|
path: url.pathname + url.search,
|
|
method: init?.method ?? 'GET',
|
|
rawBody: init?.body,
|
|
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
|
headers: new Headers(init?.headers),
|
|
signal: init?.signal,
|
|
credentials: init?.credentials,
|
|
settled: false,
|
|
};
|
|
requests.push(item);
|
|
return item.promise; // Deliberately ignore abort: identity fences must still reject stale responses.
|
|
},
|
|
});
|
|
});
|
|
afterEach(async () => {
|
|
if (root) {
|
|
await flush(() => root!.unmount());
|
|
}
|
|
root = undefined;
|
|
host.remove();
|
|
});
|
|
afterAll(async () => {
|
|
await browser.happyDOM.close();
|
|
for (const key of keys) {
|
|
const old = originals.get(key);
|
|
if (old) {
|
|
Object.defineProperty(globalThis, key, old);
|
|
} else {
|
|
Reflect.deleteProperty(globalThis, key);
|
|
}
|
|
}
|
|
});
|
|
|
|
const thirdExperimentId = '99999999-9999-4999-8999-999999999999';
|
|
const selection = { leftId: experimentId, rightId: otherExperimentId };
|
|
const query = (input: ExperimentComparisonInput = selection) =>
|
|
new URLSearchParams(input).toString();
|
|
const comparePath = (input: ExperimentComparisonInput = selection) =>
|
|
`/api/v2/experiments/compare?${query(input)}`;
|
|
const compareRoute = (input: ExperimentComparisonInput = selection) =>
|
|
`/experiments/compare?${query(input)}`;
|
|
function comparison(
|
|
statuses: ExperimentTrial['status'][] = ['completed', 'completed']
|
|
): ExperimentComparison {
|
|
const left = detail(preview(statuses.length), statuses);
|
|
const right = detail(costs(), ['completed', 'completed']);
|
|
right.id = otherExperimentId;
|
|
right.name = right.preview.input.name = 'Cost study';
|
|
if (right.preview.version === 'cost-sensitivity-preview/v1') {
|
|
right.preview.source.input.name = 'Cost study';
|
|
}
|
|
right.trials.forEach((trial, index) => {
|
|
trial.runId = runId(index + 20);
|
|
});
|
|
const reference = left.trials[0]!;
|
|
return {
|
|
version: 'experiment-comparison/v1',
|
|
policy: 'retained-input-compatibility/v1',
|
|
selection: { ...selection, referenceTrialKey: reference.trialKey },
|
|
reference: {
|
|
experimentId: left.id,
|
|
trialKey: reference.trialKey,
|
|
index: reference.index,
|
|
runId: reference.runId,
|
|
summaryAvailable: reference.comparable,
|
|
diagnostic: reference.diagnostic,
|
|
},
|
|
experiments: [left, right],
|
|
rows: [left, right].flatMap(experiment =>
|
|
experiment.trials.map(trial => {
|
|
const differs = experiment.id === right.id && trial.index > 0;
|
|
return {
|
|
experimentId: experiment.id,
|
|
trialKey: trial.trialKey,
|
|
inputCompatibility: differs ? 'mismatch' : 'match',
|
|
differences: differs ? ['costs'] : [],
|
|
summaryAvailable: trial.comparable,
|
|
ready: !differs && trial.comparable && reference.comparable,
|
|
};
|
|
})
|
|
),
|
|
limitations: ['Retained-input comparison is not a full financial reconciliation.'],
|
|
};
|
|
}
|
|
function referenceTo(value: ExperimentComparison, index: number) {
|
|
const trial = value.experiments[0].trials[index]!;
|
|
value.selection.referenceTrialKey = trial.trialKey;
|
|
value.reference = {
|
|
experimentId: value.experiments[0].id,
|
|
trialKey: trial.trialKey,
|
|
index,
|
|
runId: trial.runId,
|
|
summaryAvailable: trial.comparable,
|
|
diagnostic: trial.diagnostic,
|
|
};
|
|
for (const row of value.rows) {
|
|
row.ready = row.inputCompatibility === 'match' && row.summaryAvailable && trial.comparable;
|
|
}
|
|
return value;
|
|
}
|
|
function routes() {
|
|
return createElement(
|
|
router.Routes,
|
|
null,
|
|
createElement(router.Route, {
|
|
path: '/experiments',
|
|
element: createElement(ExperimentListPage),
|
|
}),
|
|
createElement(router.Route, {
|
|
path: '/experiments/compare',
|
|
element: createElement(ExperimentComparisonPage),
|
|
}),
|
|
createElement(router.Route, { path: '*', element: createElement('p', null, 'Other page') })
|
|
);
|
|
}
|
|
async function show(value?: ExperimentComparison, input: ExperimentComparisonInput = selection) {
|
|
await render(routes(), compareRoute(input));
|
|
if (value) {
|
|
await flush(() => reply(request(comparePath(input)), { comparison: value }));
|
|
}
|
|
}
|
|
const summary = (id: string, name: string) => ({ ...detail(), id, name });
|
|
const saved = () => [
|
|
summary(experimentId, 'First study'),
|
|
summary(otherExperimentId, 'Second study'),
|
|
summary(thirdExperimentId, 'Third study'),
|
|
];
|
|
async function list() {
|
|
await render(routes(), `/experiments?backtestId=${backtestId}`);
|
|
await flush(() => {
|
|
reply(request('/api/v2/backtests?limit=50&offset=0'), [template()]);
|
|
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: saved() });
|
|
});
|
|
}
|
|
function checkbox(name: string) {
|
|
const item = host.querySelector<HTMLInputElement>(
|
|
`input[aria-label="Select ${name} for comparison"]`
|
|
);
|
|
if (!item) {
|
|
throw new Error(`Missing comparison choice ${name}`);
|
|
}
|
|
return item;
|
|
}
|
|
function link(text: string) {
|
|
const item = [...host.querySelectorAll('a')].find(item => item.textContent?.trim() === text);
|
|
if (!item) {
|
|
throw new Error(`Missing link ${text}`);
|
|
}
|
|
return item;
|
|
}
|
|
async function selectTwo() {
|
|
await flush(() => checkbox('Second study').click());
|
|
await flush(() => checkbox('First study').click());
|
|
}
|
|
|
|
describe('saved experiment comparison selection', () => {
|
|
test('uses click order, caps at two, and follows a real comparison link', async () => {
|
|
await list();
|
|
expect(button('Compare selected experiments').disabled).toBe(true);
|
|
await selectTwo();
|
|
expect(checkbox('Third study').disabled).toBe(true);
|
|
const href = compareRoute({ leftId: otherExperimentId, rightId: experimentId });
|
|
expect(link('Compare selected experiments').getAttribute('href')).toBe(href);
|
|
await flush(() => checkbox('Second study').click());
|
|
expect(checkbox('Third study').disabled).toBe(false);
|
|
await flush(() => checkbox('Third study').click());
|
|
expect(link('Compare selected experiments').getAttribute('href')).toBe(
|
|
compareRoute({ leftId: experimentId, rightId: thirdExperimentId })
|
|
);
|
|
await flush(() => link('Compare selected experiments').click());
|
|
expect(location).toBe(compareRoute({ leftId: experimentId, rightId: thirdExperimentId }));
|
|
});
|
|
test('reconciles disappeared selections after refresh and clears on source-filter change', async () => {
|
|
await list();
|
|
await selectTwo();
|
|
await flush(() => button('Refresh experiments').click());
|
|
await flush(() =>
|
|
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
|
experiments: saved().slice(1),
|
|
})
|
|
);
|
|
expect(button('Compare selected experiments').disabled).toBe(true);
|
|
expect(checkbox('Second study').checked).toBe(true);
|
|
await flush(() => checkbox('Third study').click());
|
|
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
|
await flush(() =>
|
|
reply(request(`/api/v2/experiments?backtestId=${otherBacktestId}`), {
|
|
experiments: saved().map(item => ({ ...item, backtestId: otherBacktestId })),
|
|
})
|
|
);
|
|
expect(checkbox('Second study').checked).toBe(false);
|
|
expect(checkbox('Third study').checked).toBe(false);
|
|
});
|
|
test('late list response cannot restore a previous filter or selection', async () => {
|
|
await list();
|
|
await selectTwo();
|
|
await flush(() => button('Refresh experiments').click());
|
|
const old = request(`/api/v2/experiments?backtestId=${backtestId}`);
|
|
await flush(() => navigate('/experiments'));
|
|
await flush(() =>
|
|
reply(request('/api/v2/experiments'), {
|
|
experiments: [summary(thirdExperimentId, 'Only current')],
|
|
})
|
|
);
|
|
await flush(() => reply(old, { experiments: saved() }));
|
|
expect(old.signal?.aborted).toBe(true);
|
|
expect(host.textContent).not.toContain('First study');
|
|
expect(button('Compare selected experiments').disabled).toBe(true);
|
|
});
|
|
test('comparison Link respects ordinary draft navigation refusal', async () => {
|
|
await list();
|
|
await selectTwo();
|
|
await flush(() => change('Experiment name', 'Unsaved hypothesis'));
|
|
let prompts = 0;
|
|
Object.defineProperty(browser, 'confirm', {
|
|
configurable: true,
|
|
value: () => {
|
|
prompts++;
|
|
return false;
|
|
},
|
|
});
|
|
await flush(() => link('Compare selected experiments').click());
|
|
expect(prompts).toBe(1);
|
|
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
|
expect(field('Experiment name').value).toBe('Unsaved hypothesis');
|
|
});
|
|
test('comparison Link cannot discard an ambiguous create key without consent', async () => {
|
|
await list();
|
|
await selectTwo();
|
|
const value = preview();
|
|
await flush(() => {
|
|
change('Experiment name', value.input.name);
|
|
change('Parameter grid (JSON)', JSON.stringify(value.input.grid));
|
|
});
|
|
await flush(() => button('Preview experiment').click());
|
|
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
|
await flush(() => button('Confirm experiment').click());
|
|
const first = request('/api/v2/experiments', 'POST');
|
|
await flush(() => {
|
|
first.settled = true;
|
|
first.reject(new Error('Response lost'));
|
|
});
|
|
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
|
await flush(() => link('Compare selected experiments').click());
|
|
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
|
await flush(() => button('Retry experiment submission').click());
|
|
const retry = request('/api/v2/experiments', 'POST');
|
|
expect(retry.rawBody).toBe(first.rawBody);
|
|
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
|
});
|
|
});
|
|
|
|
describe('read-only comparison outcomes and route identity', () => {
|
|
test('shows original ordered outcomes, effective costs, zero and null reasons, and exact run links', async () => {
|
|
const value = comparison();
|
|
value.experiments[0].cancelRequested = true;
|
|
await show(value);
|
|
const left = host.querySelector('[aria-label="Left experiment outcomes"]')!;
|
|
const right = host.querySelector('[aria-label="Right experiment outcomes"]')!;
|
|
expect(left.querySelectorAll(':scope > div > table > tbody > tr')).toHaveLength(2);
|
|
expect(right.querySelectorAll(':scope > div > table > tbody > tr')).toHaveLength(2);
|
|
expect(right.textContent).toContain('Fee: 0.00100000');
|
|
expect(right.textContent).toContain('Slippage: 0.00200000');
|
|
expect(right.textContent).toContain('Half-spread:');
|
|
expect(right.textContent).toContain('Settings differ');
|
|
expect(left.textContent).toContain('Matching settings');
|
|
expect(left.textContent).toContain('Saved summary available');
|
|
expect(left.textContent).toContain('insufficient-periods');
|
|
expect(
|
|
left.querySelectorAll(':scope > div > table > tbody > tr')[0]!.children[5]!.textContent
|
|
).toBe('0');
|
|
expect(link('Open left trial 1 run').getAttribute('href')).toBe(
|
|
`/backtests/${backtestId}/run/${runId(0)}`
|
|
);
|
|
expect(link('Open right trial 2 run').getAttribute('href')).toBe(
|
|
`/backtests/${backtestId}/run/${runId(21)}`
|
|
);
|
|
expect(host.textContent).toContain('statistical significance');
|
|
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
|
});
|
|
test.each(['failed', 'missing'] as const)(
|
|
'retains %s frozen first reference instead of choosing a completed trial',
|
|
async status => {
|
|
const value = comparison([status, 'completed']);
|
|
await show(value);
|
|
expect(field('Reference trial').value).toBe(value.experiments[0].trials[0]!.trialKey);
|
|
expect(host.querySelector('select[aria-label="Reference trial"]')).not.toBeNull();
|
|
expect(host.textContent).toContain('Reference saved summary unavailable');
|
|
expect(host.textContent).not.toContain(
|
|
'Matching settings and both saved summaries available'
|
|
);
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(4);
|
|
expect(host.textContent).toContain(
|
|
status === 'missing' ? 'Expected run missing' : 'Strategy callback failed'
|
|
);
|
|
}
|
|
);
|
|
test('keeps pending/running/paused/cancelled/incomparable outcomes alongside valid summaries', async () => {
|
|
const value = comparison(['pending', 'running', 'paused', 'cancelled', 'completed']);
|
|
const incomparable = value.experiments[0].trials[4]!;
|
|
incomparable.comparable = false;
|
|
incomparable.diagnostic = 'Retained result identity does not match';
|
|
incomparable.metrics = null;
|
|
incomparable.unavailable = null;
|
|
value.rows[4]!.summaryAvailable = false;
|
|
await show(value);
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(7);
|
|
for (const status of ['pending', 'running', 'paused', 'cancelled']) {
|
|
expect(host.textContent).toContain(status);
|
|
}
|
|
expect(host.textContent).toContain('Retained result identity does not match');
|
|
expect(host.textContent).toContain('Saved summary available');
|
|
});
|
|
test('reference URL changes clear old data, ignore late reads, and reopen the exact reference', async () => {
|
|
const initial = comparison();
|
|
await show(initial);
|
|
await flush(() => button('Refresh comparison').click());
|
|
const old = request(comparePath());
|
|
const key = initial.experiments[0].trials[1]!.trialKey;
|
|
await flush(() => change('Reference trial', key));
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(0);
|
|
expect(location).toBe(compareRoute({ ...selection, referenceTrialKey: key }));
|
|
await flush(() => reply(old, { comparison: initial }));
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(0);
|
|
expect(old.signal?.aborted).toBe(true);
|
|
await flush(() =>
|
|
reply(request(comparePath({ ...selection, referenceTrialKey: key })), {
|
|
comparison: referenceTo(comparison(), 1),
|
|
})
|
|
);
|
|
expect(field('Reference trial').value).toBe(key);
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
await show(referenceTo(comparison(), 1), { ...selection, referenceTrialKey: key });
|
|
expect(field('Reference trial').value).toBe(key);
|
|
});
|
|
test('pair changes clear loaded data immediately and fence old successes and failures', async () => {
|
|
await show(comparison());
|
|
await flush(() => button('Refresh comparison').click());
|
|
const old = request(comparePath());
|
|
const next = { leftId: experimentId, rightId: thirdExperimentId };
|
|
await flush(() => navigate(compareRoute(next)));
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(0);
|
|
await flush(() => {
|
|
old.settled = true;
|
|
old.reject(new Error('Old pair read failed'));
|
|
});
|
|
expect(host.textContent).not.toContain('Old pair read failed');
|
|
await flush(() => reply(request(comparePath(next)), { error: 'Next experiment missing' }, 404));
|
|
expect(host.textContent).toContain('Next experiment missing');
|
|
expect(host.textContent).not.toContain('Cost study');
|
|
});
|
|
test('same-selection refresh failure labels retained evidence and refresh retries only reads', async () => {
|
|
await show(comparison());
|
|
await flush(() => {
|
|
button('Refresh comparison').click();
|
|
button('Refresh comparison').click();
|
|
});
|
|
expect(requests.filter(item => item.path === comparePath())).toHaveLength(2);
|
|
await flush(() => reply(request(comparePath()), { error: 'Database unavailable' }, 500));
|
|
expect(host.textContent).toContain(
|
|
'Showing the last loaded comparison for this same selection.'
|
|
);
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(4);
|
|
await flush(() => button('Refresh comparison').click());
|
|
await flush(() => reply(request(comparePath()), { comparison: comparison() }));
|
|
expect(host.querySelector('[role="alert"]')).toBeNull();
|
|
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
|
});
|
|
test.each([400, 404, 409, 500])(
|
|
'shows %i read errors without stale success, then permits explicit retry',
|
|
async status => {
|
|
await show();
|
|
await flush(() =>
|
|
reply(request(comparePath()), { error: `Read rejected ${status}` }, status)
|
|
);
|
|
expect(host.textContent).toContain(`Read rejected ${status}`);
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(0);
|
|
await flush(() => button('Refresh comparison').click());
|
|
await flush(() => reply(request(comparePath()), { comparison: comparison() }));
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(4);
|
|
}
|
|
);
|
|
test('malformed successful envelope never displays partial comparison', async () => {
|
|
await show();
|
|
const bad = comparison();
|
|
bad.rows.pop();
|
|
await flush(() => reply(request(comparePath()), { comparison: bad }));
|
|
expect(host.textContent).toContain('could not be verified');
|
|
expect(
|
|
host.querySelectorAll('[aria-label$="experiment outcomes"] > div > table > tbody > tr')
|
|
).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe('strict comparison identity decoding', () => {
|
|
test('direct API normalizes uppercase IDs for both request and response identity', async () => {
|
|
const leftId = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
|
|
const rightId = 'bcdefabc-bcde-4bcd-8bcd-bcdefabcdefa';
|
|
const value = comparison();
|
|
value.selection.leftId = value.experiments[0].id = value.reference.experimentId = leftId;
|
|
value.selection.rightId = value.experiments[1].id = rightId;
|
|
for (const row of value.rows) {
|
|
row.experimentId = row.experimentId === experimentId ? leftId : rightId;
|
|
}
|
|
const upper = { leftId: leftId.toUpperCase(), rightId: rightId.toUpperCase() };
|
|
expect(parseComparisonQuery(new URLSearchParams(upper))).toEqual({ leftId, rightId });
|
|
const pending = experimentComparisonApi.get(upper);
|
|
reply(request(comparePath({ leftId, rightId })), { comparison: value });
|
|
const result = await pending;
|
|
expect(result.selection).toEqual(value.selection);
|
|
expect(result.experiments.map(item => item.id)).toEqual([leftId, rightId]);
|
|
expect(upper.leftId).toBe(leftId.toUpperCase());
|
|
expect(requests).toHaveLength(1);
|
|
});
|
|
test('mixed-case aliases of the same UUID cannot select one experiment twice', async () => {
|
|
const id = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
|
|
const duplicate = { leftId: id, rightId: id.toUpperCase() };
|
|
expect(() => parseComparisonQuery(new URLSearchParams(duplicate))).toThrow();
|
|
await expect(experimentComparisonApi.get(duplicate)).rejects.toThrow();
|
|
expect(requests).toHaveLength(0);
|
|
});
|
|
|
|
test.each([
|
|
'',
|
|
`leftId=${experimentId}`,
|
|
`leftId=${experimentId}&rightId=${experimentId}`,
|
|
`leftId=bad&rightId=${otherExperimentId}`,
|
|
`${query()}&referenceTrialKey=bad`,
|
|
`${query()}&leftId=${experimentId}`,
|
|
`${query()}&unexpected=true`,
|
|
`${query()}&referenceTrialKey=${'a'.repeat(64)}&referenceTrialKey=${'b'.repeat(64)}`,
|
|
])('malformed query %s rejects without a request', async search => {
|
|
expect(() => parseComparisonQuery(new URLSearchParams(search))).toThrow();
|
|
await render(routes(), `/experiments/compare?${search}`);
|
|
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
|
expect(requests).toHaveLength(0);
|
|
});
|
|
const mutations: [string, (value: ExperimentComparison) => void][] = [
|
|
[
|
|
'foreign left',
|
|
value => {
|
|
value.experiments[0].id = thirdExperimentId;
|
|
},
|
|
],
|
|
[
|
|
'swapped envelopes',
|
|
value => {
|
|
value.experiments.reverse();
|
|
},
|
|
],
|
|
[
|
|
'selection identity',
|
|
value => {
|
|
value.selection.rightId = thirdExperimentId;
|
|
},
|
|
],
|
|
[
|
|
'implicit reference fallback',
|
|
value => {
|
|
referenceTo(value, 1);
|
|
},
|
|
],
|
|
[
|
|
'reference run',
|
|
value => {
|
|
value.reference.runId = runId(25);
|
|
},
|
|
],
|
|
[
|
|
'reference index',
|
|
value => {
|
|
value.reference.index = 1;
|
|
},
|
|
],
|
|
[
|
|
'reference parent',
|
|
value => {
|
|
value.reference.experimentId = otherExperimentId;
|
|
},
|
|
],
|
|
[
|
|
'reference diagnostic',
|
|
value => {
|
|
value.reference.diagnostic = 'Made up';
|
|
},
|
|
],
|
|
[
|
|
'reference availability',
|
|
value => {
|
|
value.reference.summaryAvailable = false;
|
|
},
|
|
],
|
|
[
|
|
'missing row',
|
|
value => {
|
|
value.rows.pop();
|
|
},
|
|
],
|
|
[
|
|
'duplicate row',
|
|
value => {
|
|
value.rows[1] = { ...value.rows[0]! };
|
|
},
|
|
],
|
|
[
|
|
'wrong order',
|
|
value => {
|
|
value.rows.reverse();
|
|
},
|
|
],
|
|
[
|
|
'foreign row',
|
|
value => {
|
|
value.rows[0]!.experimentId = thirdExperimentId;
|
|
},
|
|
],
|
|
[
|
|
'unknown key',
|
|
value => {
|
|
value.rows[0]!.trialKey = 'a'.repeat(64);
|
|
},
|
|
],
|
|
[
|
|
'empty mismatch',
|
|
value => {
|
|
value.rows[0]!.inputCompatibility = 'mismatch';
|
|
},
|
|
],
|
|
[
|
|
'difference with match',
|
|
value => {
|
|
value.rows[0]!.differences = ['costs'];
|
|
},
|
|
],
|
|
[
|
|
'duplicate dimension',
|
|
value => {
|
|
value.rows[3]!.differences = ['costs', 'costs'];
|
|
},
|
|
],
|
|
[
|
|
'unordered dimensions',
|
|
value => {
|
|
value.rows[3]!.differences = ['risk', 'costs'];
|
|
},
|
|
],
|
|
[
|
|
'availability mismatch',
|
|
value => {
|
|
value.rows[0]!.summaryAvailable = false;
|
|
},
|
|
],
|
|
[
|
|
'false ready',
|
|
value => {
|
|
value.rows[0]!.ready = false;
|
|
},
|
|
],
|
|
[
|
|
'mismatched ready',
|
|
value => {
|
|
value.rows[3]!.ready = true;
|
|
},
|
|
],
|
|
[
|
|
'invalid child count',
|
|
value => {
|
|
value.experiments[0].counts.completed = 1;
|
|
},
|
|
],
|
|
[
|
|
'child parameters changed',
|
|
value => {
|
|
value.experiments[0].trials[0]!.parameters = {};
|
|
},
|
|
],
|
|
[
|
|
'cost trial changed',
|
|
value => {
|
|
const trial = value.experiments[1].trials[1]!;
|
|
if ('costs' in trial) {
|
|
trial.costs.feeRate = '0.50000000';
|
|
}
|
|
},
|
|
],
|
|
];
|
|
test.each(mutations)('rejects %s', (_label, mutate) => {
|
|
const value = comparison();
|
|
mutate(value);
|
|
expect(() => parseExperimentComparison(value, selection)).toThrow();
|
|
});
|
|
test('accepts intended strategy differences and server-owned compatibility without comparing finance in browser', () => {
|
|
const value = comparison();
|
|
const request = value.experiments[1].preview.request;
|
|
request.strategy.selection.parameters = { fastPeriod: 7, slowPeriod: 20 };
|
|
if (value.experiments[1].preview.version === 'cost-sensitivity-preview/v1') {
|
|
value.experiments[1].preview.source.request.strategy.selection.parameters = {
|
|
fastPeriod: 7,
|
|
slowPeriod: 20,
|
|
};
|
|
for (const candidate of value.experiments[1].preview.candidates) {
|
|
candidate.parameters.fastPeriod = 7;
|
|
}
|
|
value.experiments[1].preview.source.candidates[0]!.parameters.fastPeriod = 7;
|
|
}
|
|
for (const trial of value.experiments[1].trials) {
|
|
trial.parameters.fastPeriod = 7;
|
|
}
|
|
expect(parseExperimentComparison(value, selection).rows[2]!.inputCompatibility).toBe('match');
|
|
});
|
|
test('explicit unknown reference is never replaced by the default', () => {
|
|
expect(() =>
|
|
parseExperimentComparison(comparison(), { ...selection, referenceTrialKey: 'f'.repeat(64) })
|
|
).toThrow();
|
|
});
|
|
});
|