feat(research): compare saved experiments against explicit trials
This commit is contained in:
parent
397cd0e160
commit
46a4f13acd
22 changed files with 3045 additions and 35 deletions
128
test/integration/experiment-comparison-api.test.ts
Normal file
128
test/integration/experiment-comparison-api.test.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
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 { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
|
||||
const tokens = {
|
||||
operator: 'validation-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'validation-service-fixture-not-a-real-secret-1234',
|
||||
read: 'validation-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
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 = {
|
||||
query: mock(query),
|
||||
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 ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const leftId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
rightId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
|
||||
query = `?leftId=${leftId}&rightId=${rightId}`;
|
||||
describe('experiment comparison HTTP boundary', () => {
|
||||
test('authorized read clients may compare without mutation credentials; unauthenticated reads are denied', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request('/compare' + query)).status).toBe(401);
|
||||
for (const role of ['read', 'operator', 'service'] as const) {
|
||||
const response = await f.request('/compare' + query, 'GET', undefined, role);
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
}
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('unknown/duplicate query keys, malformed IDs, same pair and reference keys fail before transactions', async () => {
|
||||
for (const suffix of [
|
||||
'',
|
||||
`?leftId=${leftId}`,
|
||||
query + '&unknown=1',
|
||||
query + '&leftId=' + leftId,
|
||||
query + '&%6CeftId=' + leftId,
|
||||
query + '&referenceTrialKey=x',
|
||||
`?leftId=${leftId}&rightId=${leftId}`,
|
||||
`?leftId=${leftId}&rightId=${leftId.toUpperCase()}`,
|
||||
query + '&referenceTrialKey=' + 'a'.repeat(64) + '&referenceTrialKey=' + 'a'.repeat(64),
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request('/compare' + suffix, 'GET', undefined, 'read')).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('valid UUID casing normalizes before querying retained experiment identities', async () => {
|
||||
const identifiers: unknown[] = [];
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('SELECT id,validation_phase')) {
|
||||
identifiers.push(values?.[0]);
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
expect(
|
||||
(
|
||||
await f.request(
|
||||
`/compare?leftId=${leftId.toUpperCase()}&rightId=${rightId.toUpperCase()}`,
|
||||
'GET',
|
||||
undefined,
|
||||
'read'
|
||||
)
|
||||
).status
|
||||
).toBe(404);
|
||||
expect(identifiers).toEqual([[leftId, rightId]]);
|
||||
});
|
||||
test('snapshot mode precedes role reads; unsupported phases409 and unexpected DB errors500 are sanitized', async () => {
|
||||
const calls: string[] = [];
|
||||
const f = fixture('enabled', async sql => {
|
||||
calls.push(sql);
|
||||
if (sql.includes('SELECT id,validation_phase')) {
|
||||
return {
|
||||
rows: [
|
||||
{ id: leftId, validation_phase: 'train' },
|
||||
{ id: rightId, validation_phase: null },
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
expect((await f.request('/compare' + query, 'GET', undefined, 'read')).status).toBe(409);
|
||||
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
expect(calls).toHaveLength(2);
|
||||
for (const error of [new Error('private storage error'), new z.ZodError([])]) {
|
||||
const broken = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await broken.request('/compare' + query, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
994
test/integration/experiment-comparison-ui.test.tsx
Normal file
994
test/integration/experiment-comparison-ui.test.tsx
Normal file
|
|
@ -0,0 +1,994 @@
|
|||
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();
|
||||
});
|
||||
});
|
||||
399
test/integration/experiment-comparison.test.ts
Normal file
399
test/integration/experiment-comparison.test.ts
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CostSensitivityInput,
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentPreview,
|
||||
} from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import {
|
||||
experimentComparisonDimensions,
|
||||
type ExperimentComparisonDimension,
|
||||
} from '@stock-bot/stock-config/experiment-comparison';
|
||||
import { builtinCatalogDescriptors, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
parseFinancialDecimal,
|
||||
type CanonicalBacktestAnalytics,
|
||||
type HistoricalDatasetV2,
|
||||
} from '@stock-bot/types';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import { buildCostSensitivityPreview } from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
|
||||
import {
|
||||
compareExperiments,
|
||||
comparisonConditions,
|
||||
parseExperimentComparison,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-comparison';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const backtestId = '10000000-0000-4000-8000-000000000001';
|
||||
const versionId = '20000000-0000-4000-8000-000000000001';
|
||||
const owner = `strategy:${versionId}`;
|
||||
const input = (): CostSensitivityInput => ({
|
||||
backtestId,
|
||||
name: 'Cost diagnostics',
|
||||
scenarios: [
|
||||
{ feeRate: '0', slippageRate: '0' },
|
||||
{ feeRate: '0.02', slippageRate: '0.01' },
|
||||
],
|
||||
});
|
||||
function source(dataset: HistoricalDatasetV2, raw = input()) {
|
||||
const experiment = { backtestId: raw.backtestId, name: raw.name, grid: {} };
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
|
||||
const clock = canonicalRiskSessionClock(dataset);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
policy.matching.risk.ledger.riskSession = clock.riskSession;
|
||||
policy.risk_boundaries = clock.riskBoundaries;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: '30000000-0000-4000-8000-000000000001',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '40000000-0000-4000-8000-000000000001',
|
||||
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: {
|
||||
strategyId: descriptor.program.strategyId,
|
||||
strategyVersion: descriptor.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 42,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '40',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
},
|
||||
},
|
||||
datasetHash: 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(experiment, request, dataset.manifest);
|
||||
}
|
||||
|
||||
function detail(preview: WorkbenchExperimentPreview, id = randomUUID()): WorkbenchExperimentDetail {
|
||||
const metrics: CanonicalBacktestAnalytics['metrics'] = {
|
||||
totalReturn: 0,
|
||||
cagr: null,
|
||||
maxDrawdown: null,
|
||||
exposureTime: null,
|
||||
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,
|
||||
};
|
||||
return {
|
||||
id,
|
||||
backtestId: preview.input.backtestId,
|
||||
name: preview.input.name,
|
||||
kind: preview.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
cancelRequested: false,
|
||||
trialCount: preview.candidates.length,
|
||||
counts: {
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: preview.candidates.length,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
},
|
||||
datasetHash: preview.request.datasetHash,
|
||||
strategyVersionId: preview.request.strategy.versionId,
|
||||
previewHash: preview.previewHash,
|
||||
preview,
|
||||
trials: preview.candidates.map(candidate => ({
|
||||
...candidate,
|
||||
runId: randomUUID(),
|
||||
attemptNumber: 1,
|
||||
retryCount: 0,
|
||||
status: 'completed' as const,
|
||||
progress: 100,
|
||||
cancelRequested: false,
|
||||
error: null,
|
||||
comparable: true,
|
||||
diagnostic: null,
|
||||
metrics,
|
||||
unavailable: { sharpeRatio: 'insufficient-periods' as const },
|
||||
limitations: ['fixture compact summary'],
|
||||
})),
|
||||
} as WorkbenchExperimentDetail;
|
||||
}
|
||||
const differences = (
|
||||
first: Record<ExperimentComparisonDimension, unknown>,
|
||||
second: Record<ExperimentComparisonDimension, unknown>
|
||||
) =>
|
||||
experimentComparisonDimensions.filter(
|
||||
key => canonicalStrategyJson(first[key]) !== canonicalStrategyJson(second[key])
|
||||
);
|
||||
describe('retained input comparison policy', () => {
|
||||
test('names/run/account/version-owner IDs and strategy/parameters may vary without mutating either input', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data),
|
||||
original = structuredClone(baseline),
|
||||
changed = structuredClone(baseline.request),
|
||||
version = randomUUID(),
|
||||
owner = `strategy:${version}`,
|
||||
runId = randomUUID();
|
||||
changed.name = 'Other presentation';
|
||||
changed.runId = runId;
|
||||
changed.backtestId = randomUUID();
|
||||
changed.strategy.familyId = randomUUID();
|
||||
changed.strategy.versionId = version;
|
||||
changed.strategy.reviewId = randomUUID();
|
||||
changed.strategy.package.artifact.content = 'Other trusted implementation';
|
||||
changed.strategy.package.artifact.sha256 = 'f'.repeat(64);
|
||||
changed.strategy.selection.parameters = { fastPeriod: 1, slowPeriod: 3 };
|
||||
changed.strategy.selection.ownerId = owner;
|
||||
changed.policy.matching.risk.ledger.sessionId = runId;
|
||||
changed.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
changed.policy.matching.risk.ledger.ownerIds = [owner];
|
||||
changed.policy.matching.owners[0]!.ownerId = owner;
|
||||
changed.policy.cadence[0]!.owner_id = owner;
|
||||
const before = structuredClone(changed);
|
||||
expect(comparisonConditions(changed, data.manifest)).toEqual(
|
||||
comparisonConditions(baseline.request, data.manifest)
|
||||
);
|
||||
expect(changed).toEqual(before);
|
||||
expect(baseline).toEqual(original);
|
||||
});
|
||||
test('every mutable financial/execution/clock/analytics/seed/build condition lands in its explicit mismatch partition', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data).request,
|
||||
original = comparisonConditions(baseline, data.manifest);
|
||||
const cases: [ExperimentComparisonDimension, (r: CanonicalRunRequest) => void][] = [
|
||||
['dataset', r => (r.datasetHash = 'f'.repeat(64))],
|
||||
[
|
||||
'capital',
|
||||
r =>
|
||||
(r.policy.matching.risk.ledger.initialCapital = parseFinancialDecimal('20000.00000000')),
|
||||
],
|
||||
['capital', r => (r.strategy.selection.ownerBudget = parseFinancialDecimal('50.00000000'))],
|
||||
['costs', r => (r.policy.matching.risk.feeRate = parseFinancialDecimal('0.20000000'))],
|
||||
['costs', r => (r.policy.matching.halfSpreadRate = parseFinancialDecimal('0.10000000'))],
|
||||
['costs', r => (r.policy.matching.slippageRate = parseFinancialDecimal('0.10000000'))],
|
||||
['execution', r => (r.policy.matching.latencyMs = 1)],
|
||||
['execution', r => (r.policy.participation_rate = parseFinancialDecimal('0.50000000'))],
|
||||
[
|
||||
'execution',
|
||||
r => {
|
||||
r.strategy.selection.instrumentId = 'OTHER';
|
||||
r.policy.matching.series[0]!.instrumentId = 'OTHER';
|
||||
},
|
||||
],
|
||||
[
|
||||
'execution',
|
||||
r => {
|
||||
r.strategy.selection.seriesId = 'OTHER:1m';
|
||||
r.policy.matching.series[0]!.seriesId = 'OTHER:1m';
|
||||
r.policy.cadence[0]!.series_ids = ['OTHER:1m'];
|
||||
},
|
||||
],
|
||||
[
|
||||
'clock',
|
||||
r =>
|
||||
(r.policy.matching.risk.ledger.riskSession.sessionId =
|
||||
'economic-session-must-not-normalize'),
|
||||
],
|
||||
['clock', r => (r.policy.matching.risk.ledger.riskSession.calendarId = 'other-calendar')],
|
||||
[
|
||||
'clock',
|
||||
r => (r.policy.matching.risk.ledger.riskSession.calendarRevision = 'other-revision'),
|
||||
],
|
||||
['clock', r => (r.policy.matching.risk.ledger.riskSession.startsAt += 1)],
|
||||
[
|
||||
'clock',
|
||||
r =>
|
||||
r.policy.risk_boundaries.push({
|
||||
...r.policy.matching.risk.ledger.riskSession,
|
||||
sessionId: 'later',
|
||||
startsAt: r.policy.matching.risk.ledger.riskSession.startsAt + 1000,
|
||||
}),
|
||||
],
|
||||
['analytics', r => (r.analyticsPolicy.periodsPerYear = 365)],
|
||||
['analytics', r => (r.analyticsPolicy.annualRiskFreeRate = 0.01)],
|
||||
['seed', r => (r.strategy.selection.seed = 99)],
|
||||
];
|
||||
for (const key of [
|
||||
'maxOrderQuantity',
|
||||
'maxPositionQuantity',
|
||||
'maxSymbolExposure',
|
||||
'maxGrossExposure',
|
||||
'maxDailyLoss',
|
||||
'maxDrawdownAmount',
|
||||
] as const) {
|
||||
cases.push([
|
||||
'risk',
|
||||
r => (r.policy.matching.risk[key] = parseFinancialDecimal('20000.00000000')),
|
||||
]);
|
||||
}
|
||||
cases.push(['risk', r => (r.policy.matching.risk.maxMarkAgeMs += 1)]);
|
||||
for (const key of [
|
||||
'workerSha256',
|
||||
'engineWrapperSha256',
|
||||
'engineBinarySha256',
|
||||
'dependencyLockSha256',
|
||||
] as const) {
|
||||
cases.push(['build', r => (r.build[key] = 'f'.repeat(64))]);
|
||||
}
|
||||
for (const key of ['runtimeVersion', 'platform', 'arch'] as const) {
|
||||
cases.push(['build', r => (r.build[key] = 'changed')]);
|
||||
}
|
||||
for (const [dimension, mutate] of cases) {
|
||||
const request = structuredClone(baseline);
|
||||
mutate(request);
|
||||
expect(differences(original, comparisonConditions(request, data.manifest))).toEqual([
|
||||
dimension,
|
||||
]);
|
||||
}
|
||||
const bounds = {
|
||||
...data.manifest,
|
||||
bounds: { ...data.manifest.bounds, tradeEnd: data.manifest.bounds.tradeEnd - 1 },
|
||||
};
|
||||
expect(differences(original, comparisonConditions(baseline, bounds))).toEqual([
|
||||
'dataset',
|
||||
'window',
|
||||
]);
|
||||
const provenance = {
|
||||
...data.manifest,
|
||||
calendars: data.manifest.calendars.map(calendar => ({ ...calendar, revision: 'changed' })),
|
||||
};
|
||||
expect(differences(original, comparisonConditions(baseline, provenance))).toEqual(['dataset']);
|
||||
});
|
||||
test('unsupported currency/reserve/owner modes/models reject canonical parsing instead of silently matching', () => {
|
||||
const data = canonicalSmaFixture().dataset,
|
||||
baseline = source(data).request;
|
||||
for (const mutate of [
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.baseCurrency = 'EUR'),
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.reserveOwnerId = 'foreign'),
|
||||
(r: CanonicalRunRequest) => (r.policy.matching.owners[0]!.mode = 'Orders'),
|
||||
(r: CanonicalRunRequest) => (r.policy.allow_exploratory = true),
|
||||
(r: CanonicalRunRequest) => Object.assign(r, { modelArtifacts: [{ id: 'unsupported' }] }),
|
||||
]) {
|
||||
const request = structuredClone(baseline);
|
||||
mutate(request);
|
||||
expect(() => comparisonConditions(request, data.manifest)).toThrow();
|
||||
}
|
||||
});
|
||||
test('effective scenario costs compare across experiments, independently of summary availability and reference order', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
costs = buildCostSensitivityPreview(input(), baseline),
|
||||
left = detail(costs),
|
||||
right = detail(
|
||||
buildCostSensitivityPreview(
|
||||
{ ...input(), scenarios: [...input().scenarios].reverse() },
|
||||
baseline
|
||||
)
|
||||
);
|
||||
const before = structuredClone([left, right] as [
|
||||
WorkbenchExperimentDetail,
|
||||
WorkbenchExperimentDetail,
|
||||
]),
|
||||
selected = left.trials[1]!.trialKey;
|
||||
const compared = compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
||||
[left, right]
|
||||
);
|
||||
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
|
||||
'mismatch',
|
||||
'match',
|
||||
'mismatch',
|
||||
'mismatch',
|
||||
'mismatch',
|
||||
'match',
|
||||
]);
|
||||
expect(compared.rows.map(r => r.ready)).toEqual([false, true, false, false, false, true]);
|
||||
expect(compared.experiments).toEqual(before);
|
||||
expect([left, right]).toEqual(before);
|
||||
left.trials[1]!.status = 'failed';
|
||||
left.trials[1]!.comparable = false;
|
||||
left.trials[1]!.diagnostic = 'Retained failure';
|
||||
left.trials[1]!.metrics = null;
|
||||
const failed = compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
|
||||
[left, right]
|
||||
);
|
||||
expect(failed.reference.summaryAvailable).toBe(false);
|
||||
expect(failed.reference.diagnostic).toBe('Retained failure');
|
||||
expect(failed.rows.every(r => !r.ready)).toBe(true);
|
||||
expect(failed.rows[5]!.summaryAvailable).toBe(true);
|
||||
expect(failed.rows[5]!.inputCompatibility).toBe('match');
|
||||
});
|
||||
test('missing first candidate remains the default; zero/null metrics and completed cancellation are retained', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
left = detail(buildCostSensitivityPreview(input(), baseline)),
|
||||
right = detail(baseline);
|
||||
left.trials[0]!.runId = null;
|
||||
left.trials[0]!.status = 'missing';
|
||||
left.trials[0]!.comparable = false;
|
||||
left.trials[0]!.diagnostic = 'Expected trial run is missing';
|
||||
left.trials[0]!.metrics = null;
|
||||
right.cancelRequested = true;
|
||||
const comparison = compareExperiments({ leftId: left.id, rightId: right.id }, [left, right]);
|
||||
expect(comparison.selection.referenceTrialKey).toBe(left.trials[0]!.trialKey);
|
||||
expect(comparison.reference.runId).toBeNull();
|
||||
expect(comparison.rows.every(r => !r.ready)).toBe(true);
|
||||
expect(comparison.experiments[1].trials[0]!.metrics!.totalReturn).toBe(0);
|
||||
expect(comparison.experiments[1].trials[0]!.metrics!.sharpeRatio).toBeNull();
|
||||
expect(comparison.experiments[1].trials[0]!.unavailable!.sharpeRatio).toBe(
|
||||
'insufficient-periods'
|
||||
);
|
||||
expect(comparison.experiments[1].cancelRequested).toBe(true);
|
||||
expect(() =>
|
||||
compareExperiments(
|
||||
{ leftId: left.id, rightId: right.id, referenceTrialKey: 'f'.repeat(64) },
|
||||
[left, right]
|
||||
)
|
||||
).toThrow('does not belong');
|
||||
expect(() => parseExperimentComparison({ leftId: left.id, rightId: left.id })).toThrow(
|
||||
'distinct'
|
||||
);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue