feat(research): add retained-input parameter sweep workbench
This commit is contained in:
parent
30accfcf43
commit
6f64ef62ba
41 changed files with 4469 additions and 34 deletions
347
test/integration/experiments-api.test.ts
Normal file
347
test/integration/experiments-api.test.ts
Normal file
|
|
@ -0,0 +1,347 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
experimentCandidates,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const tokens = {
|
||||
operator: 'experiment-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'experiment-service-fixture-not-a-real-secret-1234',
|
||||
read: 'experiment-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const backtestId = randomUUID(),
|
||||
experimentId = randomUUID();
|
||||
const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } };
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => ({ rows: [] })
|
||||
) {
|
||||
const client = { query: mock(query) };
|
||||
const database = {
|
||||
...client,
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (mode !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: mode === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
|
||||
return {
|
||||
database,
|
||||
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
||||
return app.request(`/api/v2/experiments${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
...(key === undefined ? {} : { 'Idempotency-Key': key }),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
function retainedPreview() {
|
||||
const version = randomUUID(),
|
||||
owner = `strategy:${version}`;
|
||||
const fixture = canonicalSmaFixture([owner]);
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(fixture.config);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId: version,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
selection: fixture.selections[0],
|
||||
},
|
||||
datasetHash: fixture.dataset.manifest.hash,
|
||||
policy,
|
||||
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: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return buildExperimentPreview(input, request, fixture.dataset.manifest);
|
||||
}
|
||||
|
||||
describe('experiment HTTP contract', () => {
|
||||
test('mutations require authenticated credential proof including preview/cancel and development bypass', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of [
|
||||
['/preview', JSON.stringify(input)],
|
||||
['', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) })],
|
||||
[`/${experimentId}/cancel`, '{}'],
|
||||
]) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('read role lists and inspects but cannot mutate; anonymous reads reject', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request()).status).toBe(401);
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
expect((await f.request(`/${experimentId}`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
for (const path of ['/preview', '', `/${experimentId}/cancel`]) {
|
||||
expect((await f.request(path, 'POST', '{}', 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
});
|
||||
test('strict bodies, malformed IDs, raw reserved parameters and receipt keys reject before storage', async () => {
|
||||
const submission = { ...input, previewHash: 'a'.repeat(64) };
|
||||
for (const [path, body, key] of [
|
||||
['/preview', '{', 'key'],
|
||||
['/preview', '[]', 'key'],
|
||||
['/preview', JSON.stringify({ ...input, feeRate: '0' }), 'key'],
|
||||
['/preview', `{"backtestId":"${backtestId}","name":"bad","grid":{"__proto__":[1]}}`, 'key'],
|
||||
['', JSON.stringify(submission), undefined],
|
||||
['', JSON.stringify(submission), 'contains space'],
|
||||
['', JSON.stringify(submission), 'x'.repeat(201)],
|
||||
['', JSON.stringify({ ...submission, previewHash: 'bad' }), 'key'],
|
||||
[`/${experimentId}/cancel`, '{"restart":true}', 'key'],
|
||||
['/bad/cancel', '{}', 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
expect((await f.request('/bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
expect((await f.request('?backtestId=bad', 'GET', undefined, 'read')).status).toBe(400);
|
||||
});
|
||||
test('accepted experiment receipts replay with202/Location and compact missing children before template eligibility', async () => {
|
||||
const preview = retainedPreview(),
|
||||
submission = { ...input, previewHash: preview.previewHash },
|
||||
key = 'accepted';
|
||||
const hash = experimentHash({ version: 1, operation: 'create-experiment', submission });
|
||||
for (const principal of ['operator', 'service'] as const) {
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('submission_principal=$1')) {
|
||||
expect(values).toEqual([principal, key]);
|
||||
return { rows: [{ id: experimentId, submission_hash: hash }] };
|
||||
}
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return { rows: [] };
|
||||
}
|
||||
expect(sql).not.toContain('FROM backtests');
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: true,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { completed: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request('', 'POST', JSON.stringify(submission), principal, key);
|
||||
expect(response.status).toBe(202);
|
||||
expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const value = await response.json();
|
||||
expect(value.experiment).toMatchObject({
|
||||
id: experimentId,
|
||||
cancelRequested: true,
|
||||
trialCount: 2,
|
||||
counts: { completed: 0 },
|
||||
});
|
||||
expect(value.experiment.trials.map((t: { status: string }) => t.status)).toEqual([
|
||||
'missing',
|
||||
'missing',
|
||||
]);
|
||||
}
|
||||
});
|
||||
test('receipt conflicts and unavailable templates are409, missing is404, unexpected storage/schema errors remain sanitized500', async () => {
|
||||
const conflict = fixture('enabled', async () => ({
|
||||
rows: [{ id: experimentId, submission_hash: 'other' }],
|
||||
}));
|
||||
expect(
|
||||
(
|
||||
await conflict.request(
|
||||
'',
|
||||
'POST',
|
||||
JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }),
|
||||
'operator',
|
||||
'key'
|
||||
)
|
||||
).status
|
||||
).toBe(409);
|
||||
const archived = fixture('enabled', async () => ({
|
||||
rows: [{ id: backtestId, archived_at: '2026-10-24T00:00:00Z' }],
|
||||
}));
|
||||
expect(
|
||||
(await archived.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(409);
|
||||
const missing = fixture();
|
||||
expect(
|
||||
(await missing.request('/preview', 'POST', JSON.stringify(input), 'operator')).status
|
||||
).toBe(404);
|
||||
expect(
|
||||
(await missing.request(`/${experimentId}/cancel`, 'POST', '{}', 'operator')).status
|
||||
).toBe(404);
|
||||
for (const error of [new Error('private database detail'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
for (const [path, method, body, key] of [
|
||||
['', 'GET', undefined, undefined],
|
||||
[`/${experimentId}`, 'GET', undefined, undefined],
|
||||
['/preview', 'POST', JSON.stringify(input), undefined],
|
||||
['', 'POST', JSON.stringify({ ...input, previewHash: 'a'.repeat(64) }), 'key'],
|
||||
[`/${experimentId}/cancel`, 'POST', '{}', undefined],
|
||||
]) {
|
||||
const response = await f.request(path, method, body, 'operator', key);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.text()).not.toContain('private');
|
||||
}
|
||||
}
|
||||
});
|
||||
test('detail counts use child rows when statuses change after the earlier metadata query', async () => {
|
||||
const preview = retainedPreview();
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return {
|
||||
rows: preview.candidates.map((candidate, index) => {
|
||||
const id = randomUUID();
|
||||
return {
|
||||
id,
|
||||
backtest_id: backtestId,
|
||||
trial_index: index,
|
||||
trial_key: candidate.trialKey,
|
||||
status: index === 0 ? 'completed' : 'failed',
|
||||
progress: index === 0 ? 100 : 50,
|
||||
cancel_requested: false,
|
||||
error: index === 1 ? 'failure' : null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
request_snapshot: experimentTrialRequest(preview, candidate, id),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: false,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: { pending: 2 },
|
||||
preview,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(200);
|
||||
const { experiment } = await response.json();
|
||||
expect(experiment.counts).toEqual({
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 1,
|
||||
failed: 1,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(experiment.trials.map((trial: { status: string }) => trial.status)).toEqual([
|
||||
'completed',
|
||||
'failed',
|
||||
]);
|
||||
expect(experiment.trials.every((trial: { comparable: boolean }) => !trial.comparable)).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
test('normalized duplicate parameter sets cannot create duplicate trial identity', () => {
|
||||
const preview = retainedPreview();
|
||||
const descriptor = builtinCatalogDescriptors[1]!;
|
||||
const request = structuredClone(preview.request);
|
||||
request.strategy.package.program = descriptor.program;
|
||||
request.strategy.package.parameterSchema = descriptor.parameterSchema;
|
||||
request.strategy.selection = {
|
||||
...request.strategy.selection,
|
||||
strategyId: 'mean_reversion',
|
||||
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
||||
parameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.1,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: parseFinancialDecimal('0'),
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
};
|
||||
expect(() =>
|
||||
experimentCandidates({ ...input, grid: { minNotionalVolume: ['1', '1.0'] } }, request)
|
||||
).toThrow('Duplicate normalized');
|
||||
});
|
||||
});
|
||||
24
test/integration/experiments-contracts.test.ts
Normal file
24
test/integration/experiments-contracts.test.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import {
|
||||
experimentInputSchema,
|
||||
experimentSubmissionSchema,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
|
||||
test('reserved raw grid keys cannot silently become a baseline experiment', () => {
|
||||
for (const key of ['__proto__', 'constructor', 'prototype']) {
|
||||
const input = JSON.parse(
|
||||
`{"backtestId":"00000000-0000-4000-8000-000000000001","name":"Sweep","grid":{"${key}":[1]}}`
|
||||
);
|
||||
expect(experimentInputSchema.safeParse(input).success).toBe(false);
|
||||
expect(
|
||||
experimentSubmissionSchema.safeParse({ ...input, previewHash: 'a'.repeat(64) }).success
|
||||
).toBe(false);
|
||||
}
|
||||
expect(
|
||||
experimentInputSchema.parse({
|
||||
backtestId: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Baseline',
|
||||
grid: {},
|
||||
}).grid
|
||||
).toEqual({});
|
||||
});
|
||||
732
test/integration/experiments-ui.test.tsx
Normal file
732
test/integration/experiments-ui.test.tsx
Normal file
|
|
@ -0,0 +1,732 @@
|
|||
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 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';
|
||||
|
||||
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 ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage;
|
||||
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)
|
||||
?.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 = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
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 {
|
||||
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,
|
||||
};
|
||||
}
|
||||
async function list(parent = backtestId) {
|
||||
await render(createElement(ExperimentListPage), `/experiments?backtestId=${parent}`);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), [template(parent)]);
|
||||
reply(request(`/api/v2/experiments?backtestId=${parent}`), { experiments: [] });
|
||||
});
|
||||
}
|
||||
async function ready(value = preview()) {
|
||||
await list(value.input.backtestId);
|
||||
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 }));
|
||||
return value;
|
||||
}
|
||||
async function showDetail(value?: ExperimentDetail) {
|
||||
const routes = createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/experiments/:experimentId',
|
||||
element: createElement(ExperimentDetailPage),
|
||||
})
|
||||
);
|
||||
await render(routes, `/experiments/${value?.id ?? experimentId}`);
|
||||
if (value) {
|
||||
await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value }));
|
||||
}
|
||||
}
|
||||
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 });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentListPage, ExperimentDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/experiments'
|
||||
));
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('bounded experiment creation', () => {
|
||||
test('preview displays frozen count/window/policies before duplicate-safe admission and exact navigation', async () => {
|
||||
const value = await ready();
|
||||
expect(host.textContent).toContain('No experiments yet.');
|
||||
expect(host.textContent).toContain('2 trials · Frozen template name');
|
||||
expect(host.textContent).toContain(new Date(value.dataset.bounds.tradeStart).toISOString());
|
||||
expect(host.textContent).toContain(value.request.datasetHash);
|
||||
const asset = [...host.querySelectorAll('dt')].find(
|
||||
item => item.textContent === 'Asset / timeframe'
|
||||
);
|
||||
expect(asset?.nextElementSibling?.textContent).toBe('X0.US / 1m');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Confirm experiment').click();
|
||||
button('Confirm experiment').click();
|
||||
});
|
||||
const post = request('/api/v2/experiments', 'POST');
|
||||
expect(post.body).toEqual({ ...value.input, previewHash: value.previewHash });
|
||||
expect(post.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
await flush(() => reply(post, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('every form change invalidates the preview and rejects a late response for the old input', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => change('Experiment name', 'Edited study'));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const stale = request('/api/v2/experiments/preview', 'POST');
|
||||
await flush(() => change('Parameter grid (JSON)', '{}'));
|
||||
const old = structuredClone(value);
|
||||
old.input.name = 'Edited study';
|
||||
await flush(() => reply(stale, { preview: old }));
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(host.querySelector('[aria-label="Frozen experiment inputs"]')).toBeNull();
|
||||
});
|
||||
test('invalid JSON and reserved keys are rejected before preview; server validation stays visible', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Parameter grid (JSON)', '{');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"__proto__":[1]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(host.textContent).toContain('Invalid parameter name');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[20],"slowPeriod":[10]}'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/experiments/preview', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test.each(['network', 'malformed', 'foreign', 'server'] as const)(
|
||||
'%s create ambiguity retains byte-identical body/key and locks editing until explicit retry',
|
||||
async failure => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
if (failure === 'network') {
|
||||
first.settled = true;
|
||||
first.reject(new Error('response lost'));
|
||||
} else if (failure === 'malformed') {
|
||||
reply(first, { experiment: { id: experimentId } }, 202);
|
||||
} else if (failure === 'foreign') {
|
||||
reply(first, { experiment: detail(preview(2, otherBacktestId)) }, 202);
|
||||
} else {
|
||||
reply(first, { error: 'Temporary failure' }, 500);
|
||||
}
|
||||
});
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
expect(field('Saved backtest').disabled).toBe(true);
|
||||
expect(button('Preview experiment').disabled).toBe(true);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), { experiments: [] })
|
||||
);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const second = request('/api/v2/experiments', 'POST');
|
||||
expect(second.rawBody).toBe(first.rawBody);
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(second, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
}
|
||||
);
|
||||
test('stale-preview conflict does not silently replace intent and explicit new intent requires a fresh preview', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => reply(first, { error: 'Preview changed; refresh inputs' }, 409));
|
||||
expect(host.textContent).toContain('Preview changed; refresh inputs');
|
||||
expect(
|
||||
requests.filter(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toHaveLength(1);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
expect(field('Experiment name').disabled).toBe(false);
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
expect(request('/api/v2/experiments', 'POST').headers.get('Idempotency-Key')).not.toBe(
|
||||
first.headers.get('Idempotency-Key')
|
||||
);
|
||||
});
|
||||
test('old create completion cannot navigate after selecting a different backtest', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const old = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(old, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments?backtestId=${otherBacktestId}`);
|
||||
expect(field('Experiment name').value).toBe('');
|
||||
expect(host.textContent).not.toContain('Retry experiment submission');
|
||||
});
|
||||
test.each([
|
||||
'wrong-parent',
|
||||
'duplicate-trial',
|
||||
'wrong-dataset',
|
||||
'invalid-date',
|
||||
'wrong-series',
|
||||
] as const)('malformed %s preview never enables admission', async kind => {
|
||||
await list();
|
||||
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());
|
||||
if (kind === 'wrong-parent') {
|
||||
value.input.backtestId = otherBacktestId;
|
||||
}
|
||||
if (kind === 'duplicate-trial') {
|
||||
value.candidates[1]!.trialKey = value.candidates[0]!.trialKey;
|
||||
}
|
||||
if (kind === 'wrong-dataset') {
|
||||
value.dataset = { ...value.dataset, hash: 'f'.repeat(64) };
|
||||
}
|
||||
if (kind === 'invalid-date') {
|
||||
value.dataset = { ...value.dataset, bounds: { ...value.dataset.bounds, tradeEnd: 9e15 } };
|
||||
}
|
||||
if (kind === 'wrong-series') {
|
||||
value.dataset = { ...value.dataset, series: [] };
|
||||
}
|
||||
await flush(() => reply(request('/api/v2/experiments/preview', 'POST'), { preview: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).not.toContain('Confirm experiment');
|
||||
});
|
||||
test('owned links require deliberate discard and keep ambiguous body/key when navigation is declined', async () => {
|
||||
const value = await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const first = request('/api/v2/experiments', 'POST');
|
||||
await flush(() => {
|
||||
first.settled = true;
|
||||
first.reject(new Error('lost'));
|
||||
});
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: [detail(value)],
|
||||
})
|
||||
);
|
||||
let prompts = 0;
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
prompts++;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await flush(() =>
|
||||
(host.querySelector(`a[href="/experiments/${experimentId}"]`) as HTMLAnchorElement).click()
|
||||
);
|
||||
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
|
||||
expect(prompts).toBe(2);
|
||||
expect(location).toBe(`/experiments?backtestId=${backtestId}`);
|
||||
expect(field('Experiment name').disabled).toBe(true);
|
||||
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'));
|
||||
await flush(() => reply(retry, { experiment: detail(value) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('list loading/error/empty states recover and saved links preserve missing counts', async () => {
|
||||
await render(createElement(ExperimentListPage), '/experiments');
|
||||
expect(host.textContent).toContain('Loading experiments...');
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/experiments'), { error: 'Read unavailable' }, 500);
|
||||
reply(request('/api/v2/backtests?limit=50&offset=0'), []);
|
||||
});
|
||||
expect(host.textContent).toContain('No saved canonical backtests');
|
||||
expect(host.textContent).toContain('Read unavailable');
|
||||
await flush(() => button('Refresh experiments').click());
|
||||
const value = detail(preview(2), ['completed', 'missing']);
|
||||
await flush(() => reply(request('/api/v2/experiments'), { experiments: [value] }));
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.querySelector(`a[href="/experiments/${experimentId}"]`)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('experiment outcomes and cancellation', () => {
|
||||
test('all states, null reasons, exact zero, mismatches, provenance and exact run links remain visible', async () => {
|
||||
const value = detail(preview(8), [
|
||||
'completed',
|
||||
'failed',
|
||||
'missing',
|
||||
'cancelled',
|
||||
'running',
|
||||
'paused',
|
||||
'pending',
|
||||
'completed',
|
||||
]);
|
||||
value.trials[7]!.comparable = false;
|
||||
value.trials[7]!.diagnostic = 'Retained request does not match the candidate';
|
||||
value.trials[7]!.limitations = ['Result cannot be compared'];
|
||||
value.trials[7]!.metrics = null;
|
||||
value.trials[7]!.unavailable = null;
|
||||
await showDetail(value);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(8);
|
||||
expect(host.textContent).toContain('missing: 1');
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('Child run missing');
|
||||
expect(host.textContent).toContain('Incomparable');
|
||||
expect(host.textContent).toContain('Retained request does not match');
|
||||
expect(host.textContent).toContain('Unavailable: insufficient-periods');
|
||||
const first = host.querySelector('tbody tr')!;
|
||||
expect(first.querySelectorAll('td')[3]!.textContent).toBe('0');
|
||||
expect(first.querySelectorAll('td')[4]!.textContent).toBe('0');
|
||||
expect(host.querySelector(`a[href="/backtests/${backtestId}/run/${runId(0)}"]`)).not.toBeNull();
|
||||
expect(host.querySelectorAll('tbody a')).toHaveLength(7);
|
||||
expect(host.textContent).toContain(value.previewHash);
|
||||
expect(host.textContent).toContain(value.preview.request.build.engineBinarySha256);
|
||||
expect(host.textContent).not.toContain('Retry failed');
|
||||
});
|
||||
test('cancel is explicit and duplicate-safe, retains terminal outcomes and distinguishes requested running work', async () => {
|
||||
const value = detail(preview(3), ['completed', 'running', 'pending']);
|
||||
await showDetail(value);
|
||||
await flush(() => {
|
||||
button('Cancel remaining trials').click();
|
||||
button('Cancel remaining trials').click();
|
||||
});
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
expect(post.body).toEqual({});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const cancelled = detail(value.preview, ['completed', 'running', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
cancelled.trials[1]!.cancelRequested = true;
|
||||
await flush(() => reply(post, { experiment: cancelled }));
|
||||
expect(host.textContent).toContain('Cancellation requested. Running trials may still finish');
|
||||
expect(host.textContent).toContain('completed: 1');
|
||||
expect(host.textContent).toContain('running: 1');
|
||||
expect(host.textContent).toContain('cancelled: 1');
|
||||
expect(host.textContent).not.toContain('Cancel remaining trials');
|
||||
});
|
||||
test('cancellation response loss is visible and refresh verifies persisted state', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const post = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => {
|
||||
post.settled = true;
|
||||
post.reject(new Error('lost'));
|
||||
});
|
||||
expect(host.textContent).toContain('Refresh to verify the saved state');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: cancelled })
|
||||
);
|
||||
expect(host.textContent).toContain('cancelled: 2');
|
||||
});
|
||||
test('old detail and cancel responses never overwrite a different selected experiment', async () => {
|
||||
const value = detail();
|
||||
await showDetail(value);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const oldCancel = request(`/api/v2/experiments/${experimentId}/cancel`, 'POST');
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = detail(preview(1));
|
||||
other.id = otherExperimentId;
|
||||
other.name = 'Other experiment';
|
||||
other.preview.input.name = other.name;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
const cancelled = detail(value.preview, ['cancelled', 'cancelled']);
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() => reply(oldCancel, { experiment: cancelled }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Other experiment');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const stale = request(`/api/v2/experiments/${otherExperimentId}`);
|
||||
await flush(() => navigate(`/experiments/${experimentId}`));
|
||||
await flush(() => reply(stale, { experiment: other }));
|
||||
expect(host.textContent).not.toContain('Other experiment');
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test.each([
|
||||
'identity',
|
||||
'missing-row',
|
||||
'wrong-parameters',
|
||||
'count-mismatch',
|
||||
'malformed-metrics',
|
||||
] as const)('malformed %s detail fails closed and recovers after refresh', async kind => {
|
||||
await showDetail();
|
||||
const value = detail(preview(), ['completed', 'pending']);
|
||||
if (kind === 'identity') {
|
||||
value.id = otherExperimentId;
|
||||
}
|
||||
if (kind === 'missing-row') {
|
||||
value.trials.pop();
|
||||
}
|
||||
if (kind === 'wrong-parameters') {
|
||||
value.trials[0]!.parameters = { fastPeriod: 19 };
|
||||
}
|
||||
if (kind === 'count-mismatch') {
|
||||
value.counts.completed = 0;
|
||||
}
|
||||
if (kind === 'malformed-metrics') {
|
||||
(value.trials[0]!.metrics as unknown as Record<string, unknown>).totalReturn = '0';
|
||||
}
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: detail() })
|
||||
);
|
||||
expect(host.querySelectorAll('tbody tr')).toHaveLength(2);
|
||||
});
|
||||
test('not-found/read failures show recovery controls without claiming an empty result', async () => {
|
||||
await showDetail();
|
||||
expect(host.textContent).toContain('Loading experiment...');
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Experiment not found' }, 404)
|
||||
);
|
||||
expect(host.textContent).toContain('Experiment not found');
|
||||
expect(button('Refresh experiment').disabled).toBe(false);
|
||||
expect(host.querySelector('tbody')).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue