feat(research): compare immutable fee and slippage scenarios
This commit is contained in:
parent
3ed7b98f7c
commit
397cd0e160
41 changed files with 3234 additions and 144 deletions
118
test/integration/cost-sensitivity-api.test.ts
Normal file
118
test/integration/cost-sensitivity-api.test.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
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 { 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',
|
||||
};
|
||||
const input = {
|
||||
backtestId: randomUUID(),
|
||||
name: 'Validation preview',
|
||||
scenarios: [{ feeRate: '0', slippageRate: '0' }],
|
||||
};
|
||||
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 ? { 'Idempotency-Key': key } : {}),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const id = randomUUID(),
|
||||
previewHash = 'a'.repeat(64);
|
||||
|
||||
const actions = [
|
||||
['/cost-sensitivity/preview', JSON.stringify(input)],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash })],
|
||||
];
|
||||
describe('cost-sensitivity HTTP gates', () => {
|
||||
test('cost mutation requires verified operator/service even in disabled auth mode', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, undefined, 'key')).status).toBe(401);
|
||||
}
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, 'read', 'key')).status).toBe(403);
|
||||
}
|
||||
expect((await f.request('', 'GET', undefined, 'read')).status).toBe(200);
|
||||
});
|
||||
test('strict mixed modes, costs, malformed JSON and missing receipt fail before storage', async () => {
|
||||
for (const [path, body, key] of [
|
||||
['/cost-sensitivity/preview', '{', 'key'],
|
||||
['/cost-sensitivity/preview', JSON.stringify({ ...input, grid: {} }), 'key'],
|
||||
[
|
||||
'/cost-sensitivity/preview',
|
||||
JSON.stringify({ ...input, scenarios: [{ feeRate: '0', slippageRate: '1' }] }),
|
||||
'key',
|
||||
],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash }), undefined],
|
||||
['/cost-sensitivity', JSON.stringify({ ...input, previewHash, mode: 'ordinary' }), 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(path, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
test('correct operation routes return404 or sanitized500; existing detail/cancel routes stay shared', async () => {
|
||||
for (const role of ['operator', 'service'] as const) {
|
||||
const f = fixture();
|
||||
for (const [path, body] of actions) {
|
||||
expect((await f.request(path, 'POST', body, role, 'key')).status).toBe(404);
|
||||
}
|
||||
expect((await f.request(`/${id}`, 'GET', undefined, role)).status).toBe(404);
|
||||
}
|
||||
for (const error of [new Error('private database failure'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw error;
|
||||
});
|
||||
const response = await f.request(
|
||||
'/cost-sensitivity/preview',
|
||||
'POST',
|
||||
JSON.stringify(input),
|
||||
'operator'
|
||||
);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
|
||||
}
|
||||
});
|
||||
});
|
||||
846
test/integration/cost-sensitivity-ui.test.tsx
Normal file
846
test/integration/cost-sensitivity-ui.test.tsx
Normal file
|
|
@ -0,0 +1,846 @@
|
|||
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 {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
} 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 || 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) => ({
|
||||
...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;
|
||||
}
|
||||
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: [] });
|
||||
});
|
||||
}
|
||||
const costPath = '/api/v2/experiments/cost-sensitivity';
|
||||
const detailPath = `/api/v2/experiments/${experimentId}`;
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
async function ready(value = costs()) {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', value.input.name);
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
for (let i = 1; i < value.input.scenarios.length; i++) {
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
}
|
||||
await flush(() =>
|
||||
value.input.scenarios.forEach((scenario, index) => {
|
||||
change(`Scenario ${index + 1} fee rate`, scenario.feeRate);
|
||||
change(`Scenario ${index + 1} slippage rate`, scenario.slippageRate);
|
||||
})
|
||||
);
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value }));
|
||||
return value;
|
||||
}
|
||||
async function lose(item: Pending) {
|
||||
await flush(() => {
|
||||
item.settled = true;
|
||||
item.reject(new Error('Response lost'));
|
||||
});
|
||||
}
|
||||
async function showDetail(value?: ExperimentDetail | CostSensitivityDetail) {
|
||||
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('cost sensitivity in the existing experiment editor', () => {
|
||||
test('normalizes fraction spellings, previews baseline without writes, and submits the same frozen cost body', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
expect(field('Scenario 1 fee rate').value).toBe('');
|
||||
expect(host.querySelector('textarea')).toBeNull();
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '0.001');
|
||||
change('Scenario 1 slippage rate', '0.0020');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const preparing = request(`${costPath}/preview`, 'POST');
|
||||
expect(preparing.body).toEqual(costs().input);
|
||||
expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength(
|
||||
0
|
||||
);
|
||||
await flush(() => reply(preparing, { preview: costs() }));
|
||||
expect(host.textContent).toContain('Baseline');
|
||||
expect(host.textContent).toContain('0.00100000');
|
||||
expect(host.textContent).toContain('2 trials');
|
||||
expect(host.textContent).toContain('Fixed half-spread rate:');
|
||||
const confirm = button('Confirm experiment');
|
||||
await flush(() => {
|
||||
confirm.click();
|
||||
confirm.click();
|
||||
});
|
||||
const post = request(costPath, 'POST');
|
||||
expect(post.body).toEqual({ ...costs().input, previewHash: costs().previewHash });
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(requests.filter(item => item.path === costPath && item.method === 'POST')).toHaveLength(
|
||||
1
|
||||
);
|
||||
await flush(() => reply(post, { experiment: detail(costs()) }, 202));
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
test('normalized duplicate pairs receive explicit preview failure and preserve editable inputs', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
});
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '0.001');
|
||||
change('Scenario 1 slippage rate', '0.002');
|
||||
change('Scenario 2 fee rate', '0.00100000');
|
||||
change('Scenario 2 slippage rate', '0.00200000');
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const previewRequest = request(`${costPath}/preview`, 'POST');
|
||||
const input = previewRequest.body as { scenarios: unknown[] };
|
||||
expect(input.scenarios[0]).toEqual(input.scenarios[1]);
|
||||
await flush(() => reply(previewRequest, { error: 'Duplicate normalized cost pair' }, 400));
|
||||
expect(host.textContent).toContain('Duplicate normalized cost pair');
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.001');
|
||||
expect(field('Experiment type').disabled).toBe(false);
|
||||
});
|
||||
test.each(['-0.01', '1.00000001', 'not-a-number'])(
|
||||
'invalid fee %s never sends preview',
|
||||
async value => {
|
||||
await ready();
|
||||
await flush(() => change('Scenario 1 fee rate', value));
|
||||
const before = requests.length;
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(requests).toHaveLength(before);
|
||||
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
||||
}
|
||||
);
|
||||
test('slippage one is rejected while fee one is accepted as a fraction', async () => {
|
||||
await ready();
|
||||
await flush(() => {
|
||||
change('Scenario 1 fee rate', '1');
|
||||
change('Scenario 1 slippage rate', '1');
|
||||
});
|
||||
const before = requests.length;
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(requests).toHaveLength(before);
|
||||
await flush(() => change('Scenario 1 slippage rate', '0.99999999'));
|
||||
await flush(() => button('Preview experiment').click());
|
||||
expect(
|
||||
(request(`${costPath}/preview`, 'POST').body as { scenarios: unknown[] }).scenarios
|
||||
).toEqual([{ feeRate: '1.00000000', slippageRate: '0.99999999' }]);
|
||||
});
|
||||
test.each(['network', 'malformed', 'wrong-kind', 'foreign'] as const)(
|
||||
'%s submission retains mode, body and key for exact retry',
|
||||
async kind => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const original = request(costPath, 'POST');
|
||||
if (kind === 'network') {
|
||||
await lose(original);
|
||||
} else {
|
||||
const value = detail(costs());
|
||||
if (kind === 'foreign') {
|
||||
value.backtestId = otherBacktestId;
|
||||
}
|
||||
await flush(() =>
|
||||
reply(
|
||||
original,
|
||||
kind === 'malformed'
|
||||
? { experiment: {} }
|
||||
: { experiment: kind === 'wrong-kind' ? detail() : value },
|
||||
202
|
||||
)
|
||||
);
|
||||
}
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed.');
|
||||
expect(field('Experiment type').disabled).toBe(true);
|
||||
expect(
|
||||
field('Scenario 1 fee rate').disabled ||
|
||||
field('Scenario 1 fee rate').closest('fieldset')!.disabled
|
||||
).toBe(true);
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(field('Experiment type').value).toBe('cost-sensitivity');
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request(costPath, 'POST');
|
||||
expect(retry.rawBody).toBe(original.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key'));
|
||||
expect(
|
||||
requests.some(item => item.path === '/api/v2/experiments' && item.method === 'POST')
|
||||
).toBe(false);
|
||||
await flush(() =>
|
||||
reply(retry, { experiment: detail(costs(), ['completed', 'completed']) }, 202)
|
||||
);
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
}
|
||||
);
|
||||
test('releasing uncertain intent is explicit and requires a fresh preview', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
await lose(request(costPath, 'POST'));
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment type').disabled).toBe(true);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Start new experiment').click());
|
||||
expect(field('Experiment type').disabled).toBe(false);
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
});
|
||||
test('same-event mode change cannot submit the previously prepared ordinary experiment', async () => {
|
||||
await list();
|
||||
await flush(() => {
|
||||
change('Experiment name', 'Trend study');
|
||||
change('Parameter grid (JSON)', JSON.stringify(preview().input.grid));
|
||||
});
|
||||
await flush(() => button('Preview experiment').click());
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/experiments/preview', 'POST'), { preview: preview() })
|
||||
);
|
||||
const submit = button('Confirm experiment');
|
||||
await flush(() => {
|
||||
change('Experiment type', 'cost-sensitivity');
|
||||
submit.click();
|
||||
});
|
||||
expect(
|
||||
requests.filter(item => item.method === 'POST' && !item.path.endsWith('/preview'))
|
||||
).toHaveLength(0);
|
||||
expect(field('Experiment type').value).toBe('cost-sensitivity');
|
||||
});
|
||||
test('mode changes fence pending reads, retain drafts and disable parameter-only panels', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const stale = request(`${costPath}/preview`, 'POST');
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(stale.signal?.aborted).toBe(true);
|
||||
await flush(() => reply(stale, { preview: costs() }));
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
await flush(() => change('Parameter grid (JSON)', '{"fastPeriod":[3]}'));
|
||||
await flush(() => change('Experiment type', 'cost-sensitivity'));
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.00100000');
|
||||
expect(button('Preview chronological validation').disabled).toBe(true);
|
||||
expect(button('Preview walk-forward').disabled).toBe(true);
|
||||
await flush(() => change('Experiment type', 'parameters'));
|
||||
expect(field('Parameter grid (JSON)').value).toBe('{"fastPeriod":[3]}');
|
||||
});
|
||||
test('adding/removing scenarios invalidates preview and preserves order', async () => {
|
||||
await ready();
|
||||
expect(button('Remove scenario 1').disabled).toBe(true);
|
||||
await flush(() => button('Add cost scenario').click());
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
await flush(() => {
|
||||
change('Scenario 2 fee rate', '0.02');
|
||||
change('Scenario 2 slippage rate', '0.03');
|
||||
});
|
||||
await flush(() => button('Remove scenario 1').click());
|
||||
expect(field('Scenario 1 fee rate').value).toBe('0.02');
|
||||
expect(button('Remove scenario 1').disabled).toBe(true);
|
||||
});
|
||||
test('unconfirmed cost submission guards owned links and ignores late completion after source navigation', async () => {
|
||||
await ready();
|
||||
await flush(() => button('Confirm experiment').click());
|
||||
const original = request(costPath, 'POST');
|
||||
await lose(original);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() =>
|
||||
[...host.querySelectorAll('a')]
|
||||
.find(item => item.textContent === 'Show all experiments')!
|
||||
.click()
|
||||
);
|
||||
expect(location).toContain(backtestId);
|
||||
await flush(() => button('Retry experiment submission').click());
|
||||
const retry = request(costPath, 'POST');
|
||||
await flush(() => navigate(`/experiments?backtestId=${otherBacktestId}`));
|
||||
await flush(() => reply(retry, { experiment: detail(costs()) }, 202));
|
||||
expect(location).toContain(otherBacktestId);
|
||||
});
|
||||
test.each([
|
||||
'baseline',
|
||||
'parameters',
|
||||
'source-grid',
|
||||
'source-request',
|
||||
'source-dataset',
|
||||
'order',
|
||||
'missing-costs',
|
||||
'duplicates',
|
||||
'extra-grid',
|
||||
] as const)('malformed %s preview fails closed', async kind => {
|
||||
await ready();
|
||||
await flush(() => button('Preview experiment').click());
|
||||
const value = costs();
|
||||
if (kind === 'baseline') {
|
||||
value.candidates[0]!.costs.feeRate = '0.05000000';
|
||||
}
|
||||
if (kind === 'parameters') {
|
||||
value.candidates[1]!.parameters.fastPeriod = 3;
|
||||
}
|
||||
if (kind === 'source-grid') {
|
||||
value.source.input.grid = { fastPeriod: [2] };
|
||||
}
|
||||
if (kind === 'source-request') {
|
||||
value.request.policy.matching.halfSpreadRate = '0.50000000' as never;
|
||||
}
|
||||
if (kind === 'source-dataset') {
|
||||
value.dataset = { ...value.dataset, hash: '1'.repeat(64) };
|
||||
}
|
||||
if (kind === 'order') {
|
||||
value.candidates.reverse();
|
||||
}
|
||||
if (kind === 'missing-costs') {
|
||||
delete (value.candidates[1] as Partial<(typeof value.candidates)[number]>).costs;
|
||||
}
|
||||
if (kind === 'duplicates') {
|
||||
value.input.scenarios[0] = { ...value.candidates[0]!.costs };
|
||||
value.candidates[1]!.costs = { ...value.candidates[0]!.costs };
|
||||
}
|
||||
if (kind === 'extra-grid') {
|
||||
Object.assign(value.input, { grid: {} });
|
||||
}
|
||||
await flush(() => reply(request(`${costPath}/preview`, 'POST'), { preview: value }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.querySelector('[aria-label="Prepared cost scenarios"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cost outcomes on the ordinary detail and retry routes', () => {
|
||||
test('all outcomes keep exact costs, null reasons and zero without ranking', async () => {
|
||||
const value = detail(
|
||||
costs([
|
||||
{ feeRate: '0.001', slippageRate: '0.002' },
|
||||
{ feeRate: '0.002', slippageRate: '0.003' },
|
||||
{ feeRate: '0.003', slippageRate: '0.004' },
|
||||
{ feeRate: '0.004', slippageRate: '0.005' },
|
||||
]),
|
||||
['completed', 'failed', 'missing', 'cancelled', 'completed']
|
||||
);
|
||||
value.trials[4]!.comparable = false;
|
||||
value.trials[4]!.diagnostic = 'Policy mismatch';
|
||||
await showDetail(value);
|
||||
expect(host.textContent).toContain('Scenario / costs / fixed parameters');
|
||||
expect(host.textContent).toContain('Baseline');
|
||||
expect(host.textContent).toContain('Scenario 4');
|
||||
expect(host.textContent).toContain('Fee rate: 0.00100000');
|
||||
expect(host.textContent).toContain('Unavailable: insufficient-periods');
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('Expected child run is missing');
|
||||
expect(host.textContent).toContain('Incomparable');
|
||||
expect(host.textContent).toContain('Policy mismatch');
|
||||
expect([...host.querySelectorAll('td')].some(item => item.textContent === '0')).toBe(true);
|
||||
expect(requests.every(item => item.method === 'GET')).toBe(true);
|
||||
});
|
||||
test.each([
|
||||
'wrong-kind',
|
||||
'missing-kind',
|
||||
'unknown-kind',
|
||||
'trial-costs',
|
||||
'fixed-parameters',
|
||||
'trial-order',
|
||||
'missing-row',
|
||||
'ordinary-cost-injection',
|
||||
] as const)('malformed %s detail cannot display results', async kind => {
|
||||
await showDetail();
|
||||
const value = detail(costs(), ['completed', 'completed']);
|
||||
if (kind === 'wrong-kind') {
|
||||
value.kind = 'parameters';
|
||||
}
|
||||
if (kind === 'missing-kind') {
|
||||
delete value.kind;
|
||||
}
|
||||
if (kind === 'unknown-kind') {
|
||||
Object.assign(value, { kind: 'unknown' });
|
||||
}
|
||||
if (kind === 'trial-costs') {
|
||||
Object.assign(value.trials[1]!, { costs: { feeRate: '0.9', slippageRate: '0.9' } });
|
||||
}
|
||||
if (kind === 'fixed-parameters') {
|
||||
value.trials[1]!.parameters.fastPeriod = 7;
|
||||
}
|
||||
if (kind === 'trial-order') {
|
||||
value.trials.reverse();
|
||||
}
|
||||
if (kind === 'missing-row') {
|
||||
value.trials.pop();
|
||||
}
|
||||
let raw: unknown = value;
|
||||
if (kind === 'ordinary-cost-injection') {
|
||||
const ordinary = detail();
|
||||
Object.assign(ordinary.trials[0]!, { costs: { feeRate: '0', slippageRate: '0' } });
|
||||
raw = ordinary;
|
||||
}
|
||||
await flush(() => reply(request(detailPath), { experiment: raw }));
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).not.toContain('Every trial outcome');
|
||||
});
|
||||
test('same-event refresh blocks cancellation until the readonly response resolves', async () => {
|
||||
await showDetail(detail(costs()));
|
||||
const cancel = button('Cancel remaining trials');
|
||||
await flush(() => {
|
||||
button('Refresh experiment').click();
|
||||
cancel.click();
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => reply(request(detailPath), { experiment: detail(costs()) }));
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
const value = detail(costs());
|
||||
value.cancelRequested = true;
|
||||
await flush(() => reply(request(`${detailPath}/cancel`, 'POST'), { experiment: value }));
|
||||
expect(host.textContent).toContain('Cancellation requested');
|
||||
});
|
||||
test('failed cost trial reuses existing retry and lazy failure history with exact captured receipt', async () => {
|
||||
const value = detail(costs(), ['completed', 'failed']) as CostSensitivityDetail;
|
||||
await showDetail(value);
|
||||
await flush(() => button('Retry trial 2').click());
|
||||
await flush(() => button('Confirm retry trial 2').click());
|
||||
const path = `${detailPath}/trials/${runId(1)}/retry`,
|
||||
original = request(path, 'POST');
|
||||
expect(original.body).toEqual({ expectedAttemptNumber: 0, expectedRetryCount: 0 });
|
||||
await lose(original);
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const newer = detail(costs(), ['completed', 'completed']) as CostSensitivityDetail;
|
||||
newer.trials[1]!.attemptNumber = 1;
|
||||
newer.trials[1]!.retryCount = 1;
|
||||
await flush(() => reply(request(detailPath), { experiment: newer }));
|
||||
const saved: ExperimentTrialRetry = {
|
||||
id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
experimentId,
|
||||
runId: runId(1),
|
||||
trialKey: value.trials[1]!.trialKey,
|
||||
retryNumber: 1,
|
||||
previousAttemptNumber: 0,
|
||||
previousAttemptId: null,
|
||||
error: 'Strategy callback failed',
|
||||
progress: 0,
|
||||
currentDate: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
pausedAt: null,
|
||||
failureUpdatedAt: '2026-10-24T10:00:00Z',
|
||||
recordedAt: '2026-10-24T11:00:00Z',
|
||||
principal: 'operator',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
};
|
||||
await flush(() => button('Retry same request for trial 2').click());
|
||||
const retry = request(path, 'POST');
|
||||
expect(retry.rawBody).toBe(original.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(original.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, { retry: saved, experiment: newer }, 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
expect(host.textContent).toContain('Fee rate: 0.00100000');
|
||||
await flush(() => button('Show retry history for trial 2').click());
|
||||
await flush(() =>
|
||||
reply(request(`${detailPath}/trials/${runId(1)}/retries`), { retries: [saved] })
|
||||
);
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(host.textContent).toContain('previous attempt 0');
|
||||
});
|
||||
test('late detail cannot replace a different saved experiment', async () => {
|
||||
await showDetail();
|
||||
const stale = request(detailPath);
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = detail(costs());
|
||||
other.id = otherExperimentId;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
await flush(() => reply(stale, { experiment: detail(costs(), ['completed', 'completed']) }));
|
||||
expect(location).toBe(`/experiments/${otherExperimentId}`);
|
||||
expect(host.textContent).toContain('pending');
|
||||
});
|
||||
test('saved list identifies cost diagnostics and opens the existing detail route', async () => {
|
||||
await render(createElement(ExperimentListPage), `/experiments?backtestId=${backtestId}`);
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments?backtestId=${backtestId}`), {
|
||||
experiments: [detail(costs())],
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Cost sensitivity · template diagnostics');
|
||||
const link = [...host.querySelectorAll('a')].find(item => item.textContent === 'Trend study')!;
|
||||
expect(link.getAttribute('href')).toBe(`/experiments/${experimentId}`);
|
||||
await flush(() => link.click());
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
});
|
||||
});
|
||||
224
test/integration/cost-sensitivity.test.ts
Normal file
224
test/integration/cost-sensitivity.test.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
|
||||
import {
|
||||
buildCostSensitivityPreview,
|
||||
parseCostSensitivityInput,
|
||||
retainedCostSensitivityPreview,
|
||||
retainedWorkbenchPreview,
|
||||
workbenchTrialRequest,
|
||||
} from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
ExperimentError,
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} 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);
|
||||
}
|
||||
|
||||
describe('cost-sensitivity immutable preparation', () => {
|
||||
test('normalizes explicit fractions, preserves ordered implicit baseline and deterministic identity', () => {
|
||||
const raw = input(),
|
||||
baseline = source(canonicalSmaFixture().dataset),
|
||||
before = structuredClone({ raw, baseline });
|
||||
const preview = buildCostSensitivityPreview(raw, baseline);
|
||||
expect(buildCostSensitivityPreview(raw, baseline)).toEqual(preview);
|
||||
expect(retainedCostSensitivityPreview(preview)).toEqual(preview);
|
||||
expect(retainedWorkbenchPreview(preview)).toEqual(preview);
|
||||
expect({ raw, baseline }).toEqual(before);
|
||||
expect(preview.source).toEqual(baseline);
|
||||
expect(preview.candidates.map(c => c.index)).toEqual([0, 1, 2]);
|
||||
expect(preview.candidates.map(c => c.costs)).toEqual([
|
||||
{
|
||||
feeRate: baseline.request.policy.matching.risk.feeRate,
|
||||
slippageRate: baseline.request.policy.matching.slippageRate,
|
||||
},
|
||||
{ feeRate: '0.00000000', slippageRate: '0.00000000' },
|
||||
{ feeRate: '0.02000000', slippageRate: '0.01000000' },
|
||||
]);
|
||||
const equivalent = {
|
||||
...raw,
|
||||
scenarios: [
|
||||
{ feeRate: '0.00000000', slippageRate: '0.0' },
|
||||
{ feeRate: '0.020', slippageRate: '0.0100' },
|
||||
],
|
||||
};
|
||||
expect(buildCostSensitivityPreview(equivalent, baseline)).toEqual(preview);
|
||||
const reordered = buildCostSensitivityPreview(
|
||||
{ ...raw, scenarios: [...raw.scenarios].reverse() },
|
||||
baseline
|
||||
);
|
||||
expect(reordered.previewHash).not.toBe(preview.previewHash);
|
||||
expect(reordered.candidates[1]!.trialKey).toBe(preview.candidates[2]!.trialKey);
|
||||
});
|
||||
test('rejects malformed/mixed input, out-of-bounds or excess precision, duplicate normalized pairs and baseline duplication', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
raw = input();
|
||||
for (const scenario of [
|
||||
{ feeRate: '-0.1', slippageRate: '0' },
|
||||
{ feeRate: '1.00000001', slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '1' },
|
||||
{ feeRate: '0', slippageRate: '0.000000001' },
|
||||
{ feeRate: 0, slippageRate: '0' },
|
||||
{ feeRate: '0', slippageRate: '0', halfSpreadRate: '0' },
|
||||
]) {
|
||||
expect(() => parseCostSensitivityInput({ ...raw, scenarios: [scenario] })).toThrow(
|
||||
ExperimentError
|
||||
);
|
||||
}
|
||||
expect(() => parseCostSensitivityInput({ ...raw, grid: {} })).toThrow();
|
||||
expect(() => parseCostSensitivityInput({ ...raw, scenarios: [] })).toThrow();
|
||||
expect(() =>
|
||||
parseCostSensitivityInput({ ...raw, scenarios: Array(100).fill(raw.scenarios[0]) })
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
buildCostSensitivityPreview(
|
||||
{ ...raw, scenarios: [raw.scenarios[0]!, { feeRate: '0.000', slippageRate: '0.0' }] },
|
||||
baseline
|
||||
)
|
||||
).toThrow('Duplicate');
|
||||
expect(() =>
|
||||
buildCostSensitivityPreview(
|
||||
{
|
||||
...raw,
|
||||
scenarios: [
|
||||
{
|
||||
feeRate: baseline.request.policy.matching.risk.feeRate,
|
||||
slippageRate: baseline.request.policy.matching.slippageRate,
|
||||
},
|
||||
],
|
||||
},
|
||||
baseline
|
||||
)
|
||||
).toThrow('Duplicate');
|
||||
expect<unknown>(
|
||||
parseCostSensitivityInput({
|
||||
...raw,
|
||||
scenarios: [{ feeRate: '1', slippageRate: '0.99999999' }],
|
||||
}).scenarios
|
||||
).toEqual([{ feeRate: '1.00000000', slippageRate: '0.99999999' }]);
|
||||
});
|
||||
test('only two cost paths change; ordinary reconstruction is byte-equivalent and validation source stays v1', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
preview = buildCostSensitivityPreview(input(), baseline),
|
||||
id = '50000000-0000-4000-8000-000000000001';
|
||||
const original = experimentTrialRequest(baseline, baseline.candidates[0]!, id);
|
||||
expect(JSON.stringify(workbenchTrialRequest(baseline, baseline.candidates[0]!, id))).toBe(
|
||||
JSON.stringify(original)
|
||||
);
|
||||
expect(workbenchTrialRequest(preview, preview.candidates[0]!, id)).toEqual(original);
|
||||
for (const candidate of preview.candidates) {
|
||||
const request = workbenchTrialRequest(preview, candidate, id);
|
||||
expect(request.strategy.selection.parameters).toEqual(original.strategy.selection.parameters);
|
||||
expect(String(request.policy.matching.risk.feeRate)).toBe(candidate.costs.feeRate);
|
||||
expect(String(request.policy.matching.slippageRate)).toBe(candidate.costs.slippageRate);
|
||||
request.policy.matching.risk.feeRate = original.policy.matching.risk.feeRate;
|
||||
request.policy.matching.slippageRate = original.policy.matching.slippageRate;
|
||||
expect(request).toEqual(original);
|
||||
}
|
||||
expect(() => retainedExperimentPreview(preview)).toThrow();
|
||||
});
|
||||
test('retained tamper is server integrity failure even with a rehashed outer manifest', () => {
|
||||
const baseline = source(canonicalSmaFixture().dataset),
|
||||
preview = buildCostSensitivityPreview(input(), baseline);
|
||||
for (const mutate of [
|
||||
(p: typeof preview) => (p.candidates[1]!.costs.feeRate = '0.9'),
|
||||
(p: typeof preview) => p.candidates.reverse(),
|
||||
(p: typeof preview) => (p.request = structuredClone({ ...p.request, name: 'foreign' })),
|
||||
(p: typeof preview) => (p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }),
|
||||
]) {
|
||||
const changed = structuredClone(preview);
|
||||
mutate(changed);
|
||||
const { previewHash: _hash, ...manifest } = changed;
|
||||
changed.previewHash = experimentHash(manifest);
|
||||
let error: unknown;
|
||||
try {
|
||||
retainedCostSensitivityPreview(changed);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect(error).not.toBeInstanceOf(ExperimentError);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -682,12 +682,17 @@ describe('retry coordination and navigation', () => {
|
|||
await flush(() => reply(oldRead, { experiment: other }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test('refresh and confirmation in one event cannot install a stale read over accepted retry state', async () => {
|
||||
test('refresh and confirmation in one event serialize the read before retry acceptance', async () => {
|
||||
const value = await start();
|
||||
await flush(() => {
|
||||
button('Refresh experiment').click();
|
||||
button('Confirm retry trial 1').click();
|
||||
});
|
||||
expect(
|
||||
requests.filter(item => item.path === retryPath() && item.method === 'POST')
|
||||
).toHaveLength(0);
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
const post = request(retryPath(), 'POST');
|
||||
await flush(() => reply(post, accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue