feat(research): compare immutable fee and slippage scenarios

This commit is contained in:
Boki 2026-10-24 13:10:01 -04:00
parent 3ed7b98f7c
commit 397cd0e160
41 changed files with 3234 additions and 144 deletions

View file

@ -297,6 +297,7 @@ export async function fixture(browser: Browser, native = false) {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -11,6 +11,11 @@ import type {
ChronologicalValidationPreview,
ChronologicalValidationReport,
} from '@stock-bot/stock-config/chronological-validation';
import {
costScenarioSchema,
type CostSensitivityDetail,
type CostSensitivityPreview,
} from '@stock-bot/stock-config/cost-sensitivity';
import type {
ExperimentDetail,
ExperimentPreview,
@ -49,6 +54,158 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
test('cost_sensitivity_freezes_policy_runs_native_scenarios_and_reopens_existing_experiment_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset } = canonicalSmaFixture();
await retainResearchDataset(f.pool, dataset);
const version = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed native cost sensitivity fixture',
});
const definition = {
name: 'Fixed cost study template',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const backtest = await f.request('/api/v2/backtests', 'POST', {
...definition,
autoStart: false,
});
await f.login();
await f.page.goto(`${f.origin}/experiments?backtestId=${backtest.id}`);
await f.page.getByLabel('Saved backtest').selectOption(backtest.id);
await f.page
.getByLabel('Experiment name', { exact: true })
.fill('Fixed fee and slippage study');
await f.page.getByLabel('Experiment type').selectOption({ label: 'Cost sensitivity' });
expect(await f.page.getByLabel('Parameter grid').isVisible()).toBe(false);
await f.page.getByLabel('Scenario 1 fee rate', { exact: true }).fill('0.02');
await f.page.getByLabel('Scenario 1 slippage rate', { exact: true }).fill('0');
await f.page.getByRole('button', { name: 'Add cost scenario', exact: true }).click();
await f.page.getByLabel('Scenario 2 fee rate', { exact: true }).fill('0.01');
await f.page.getByLabel('Scenario 2 slippage rate', { exact: true }).fill('0.02');
const preparing = f.page.waitForResponse(response =>
response.url().endsWith('/api/v2/experiments/cost-sensitivity/preview')
);
await f.page.getByRole('button', { name: 'Preview experiment', exact: true }).click();
const prepared = await preparing;
expect(prepared.status()).toBe(200);
const { preview } = (await prepared.json()) as { preview: CostSensitivityPreview };
expect(preview.version).toBe('cost-sensitivity-preview/v1');
expect(preview.source.input.grid).toEqual({});
expect(preview.candidates.map(candidate => candidate.costs)).toEqual([
{ feeRate: '0.01000000', slippageRate: '0.00000000' },
{ feeRate: '0.02000000', slippageRate: '0.00000000' },
{ feeRate: '0.01000000', slippageRate: '0.02000000' },
]);
expect(
preview.candidates.every(
candidate =>
JSON.stringify(candidate.parameters) === JSON.stringify(definition.strategyParameters)
)
).toBe(true);
expect((await f.pool.query('SELECT * FROM research_experiments')).rowCount).toBe(0);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
const submitting = f.page.waitForResponse(
response =>
response.request().method() === 'POST' &&
response.url().endsWith('/api/v2/experiments/cost-sensitivity')
);
await f.page.getByRole('button', { name: 'Confirm experiment', exact: true }).click();
const submitted = await submitting;
expect(submitted.status()).toBe(202);
const { experiment } = (await submitted.json()) as { experiment: CostSensitivityDetail };
expect(submitted.headers().location).toBe(`/api/v2/experiments/${experiment.id}`);
expect(experiment.preview).toEqual(preview);
expect(experiment.kind).toBe('cost-sensitivity');
expect(experiment.trialCount).toBe(3);
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(3);
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Edited after cost admission',
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
initialCapital: 20000,
config: {
...definition.config,
canonical: { ...canonicalSettings, feeRate: '0.3', slippageRate: '0.4' },
},
});
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
.n === 3,
'all three fixed-input cost scenarios complete through the native runner'
);
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
await visible(f.page, /completed: 3/);
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(3);
const outcomes = f.page.locator('section[aria-label="Experiment trial outcomes"] tbody tr');
expect(await outcomes.count()).toBe(3);
for (const [index, trial] of experiment.trials.entries()) {
const result = (await f.request(`/api/v2/runs/${trial.runId}/results`)) as CanonicalRunResult;
const expected = structuredClone(preview.request);
expected.runId = trial.runId!;
expected.policy.matching.risk.ledger.sessionId = trial.runId!;
expected.policy.matching.risk.ledger.accountId = `research:${trial.runId}`;
const costs = costScenarioSchema.parse(trial.costs);
expected.policy.matching.risk.feeRate = costs.feeRate;
expected.policy.matching.slippageRate = costs.slippageRate;
expect(result.request).toEqual(expected);
expect(result.financialEngine).toBe('rust');
expect(result.financial.policy).toEqual(expected.policy);
expect(result.financial.identity).toEqual({
version: 1,
sessionId: trial.runId!,
datasetHash: expected.datasetHash,
});
const text = await outcomes.nth(index).innerText();
expect(text).toContain(index === 0 ? 'Baseline' : `Scenario ${index}`);
expect(text).toContain(trial.costs.feeRate);
expect(text).toContain(trial.costs.slippageRate);
expect(text).toContain(String(result.analytics.metrics.totalReturn));
}
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
const replay = (await f.request(
'/api/v2/experiments/cost-sensitivity',
'POST',
submitted.request().postDataJSON(),
{ 'Idempotency-Key': submitted.request().headers()['idempotency-key']! }
)) as { experiment: CostSensitivityDetail };
expect(replay.experiment.id).toBe(experiment.id);
expect(replay.experiment.preview).toEqual(preview);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(3);
await f.page.reload();
await visible(f.page, /completed: 3/);
await f.page.getByRole('link', { name: 'All experiments', exact: true }).click();
await f.page.getByRole('link', { name: 'Fixed fee and slippage study', exact: true }).click();
await visible(f.page, /completed: 3/);
await f.page
.locator(`a[href="/backtests/${backtest.id}/run/${experiment.trials[2]!.runId}"]`)
.click();
await visible(f.page, 'Canonical research result');
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('walk_forward_freezes_all_windows_runs_native_members_and_reopens_reset_report_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());

View 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' });
}
});
});

View 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}`);
});
});

View 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);
}
});
});

View file

@ -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');

View file

@ -67,6 +67,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -66,6 +66,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -105,6 +105,7 @@ async function fixture() {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(sql(name));
}

View file

@ -79,7 +79,9 @@ async function fixture(poolMax = 1, withValidation = true) {
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
...(withValidation ? ['24-chronological-validation.sql', '25-walk-forward.sql'] : []),
...(withValidation
? ['24-chronological-validation.sql', '25-walk-forward.sql', '26-cost-sensitivity.sql']
: []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -70,6 +70,7 @@ async function fixture() {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -0,0 +1,666 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Hono } from 'hono';
import { Pool } from 'pg';
import { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
import type { CanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
import type { CostSensitivityInput } from '@stock-bot/stock-config/cost-sensitivity';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { ChronologicalValidationService } from '../../apps/stock/web-api/src/services/chronological-validation.service';
import { ExperimentError } from '../../apps/stock/web-api/src/services/experiment-input';
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('chronological-validation');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
const tokens = {
operator: 'chronological-operator-fixture-not-a-real-secret-1234',
service: 'chronological-service-fixture-not-a-real-secret-1234',
};
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture(poolMax = 1, withCosts = true, capital = 10000) {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Disposable safety database required');
}
const schema = 'stock_bot_safety_validation_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
// A single connection detects accidental nested pool reads while the admission lock is held.
const pool = new Pool({
connectionString: url,
application_name: schema,
max: poolMax,
options: `-c search_path=${schema} -c statement_timeout=10000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const name of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
'09-backtest-run-contract.sql',
'10-durable-backtest-dispatch.sql',
'12-historical-datasets.sql',
'14-backtest-submission.sql',
'16-strategy-catalog.sql',
'17-research-retention.sql',
'18-backtest-strategy-versions.sql',
'19-canonical-research.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
...(withCosts ? ['26-cost-sensitivity.sql'] : []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
const container = { postgres, logger },
api = new BacktestServiceV2(container),
experiments = new ExperimentsService(container),
catalog = new StrategyCatalogService(container);
const version = await catalog.seedBuiltin(
'Validation SMA',
(await (packages ??= packageBuiltinStrategies()))[0]!,
'seed'
);
const data = canonicalSmaFixture(),
dataset = data.dataset;
await retainResearchDataset(pool, dataset);
const draft = await api.createBacktest(
{
name: 'Validation template',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: ['X0.US'],
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: capital,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
},
{ autoStart: false }
);
const input: CostSensitivityInput = {
backtestId: draft.id,
name: 'Explicit cost diagnostics',
scenarios: [
{ feeRate: '0.001', slippageRate: '0' },
{ feeRate: '0', slippageRate: '0.01' },
],
};
const app = new Hono();
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
environment: 'test',
hostname: '127.0.0.1',
}).mount(app);
app.route('/', createExperimentRoutes(container));
const request = (raw: unknown = input, role: keyof typeof tokens = 'operator') =>
app.request('/api/v2/experiments/cost-sensitivity/preview', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens[role]}` },
body: JSON.stringify(raw),
});
const review = async (decision: 'approve' | 'revoke' = 'approve') => {
await catalog.reviewVersion(
version.id,
{ decision, reason: 'Disposable validation proof' },
'operator'
);
return (await catalog.getVersionReviews(version.id)).at(-1)!;
};
const snapshot = async () => {
const tables = (
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname=$1 ORDER BY tablename', [
schema,
])
).rows;
const rows: Record<string, unknown> = {};
for (const { tablename } of tables) {
const quoted = '"' + String(tablename).replaceAll('"', '""') + '"';
rows[String(tablename)] = (
await pool.query(
`SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) AS rows FROM ${quoted} t`
)
).rows[0].rows;
}
return rows;
};
const validations = new ChronologicalValidationService(container);
const repository = new PostgresBacktestRunRepository(postgres);
const execute = async (id: string) => {
const engine = new RustBacktestAdapter({
logger,
storage: {
async getHistoricalBars() {
throw new Error('No provider reads allowed');
},
},
});
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
try {
await runner.runQueued(id);
} finally {
await runner.shutdown();
}
};
return {
cloneTemplate: async (sourceDataset = dataset) =>
api.createBacktest(
{
name: 'Other validation template',
strategy: 'catalog',
strategyVersionId: version.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: ['X0.US'],
startDate: new Date(sourceDataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(sourceDataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: capital,
config: {
datasetHash: sourceDataset.manifest.hash,
dataFrequency: '1m',
canonical: canonicalSettings,
},
},
{ autoStart: false }
),
validations,
repository,
execute,
api,
pool,
postgres,
experiments,
catalog,
version,
draft,
dataset,
input,
request,
review,
snapshot,
};
}
const actor = (key = randomUUID()) => ({ principal: 'operator' as const, key });
type Fixture = Awaited<ReturnType<typeof fixture>>;
async function submit(f: Fixture, identity = actor()) {
await f.review();
const preview = await f.experiments.previewCosts(f.input),
body = { ...f.input, previewHash: preview.previewHash };
return { preview, body, identity, experiment: await f.experiments.submitCosts(body, identity) };
}
describe.skipIf(!url)('bounded cost-sensitivity experiments', () => {
test('pool1 native baseline agrees with ordinary empty-grid; saved scenarios expose exact costs and immutable results', async () => {
const f = await fixture(),
start = await submit(f);
expect(start.experiment.kind).toBe('cost-sensitivity');
expect(start.experiment.trials).toHaveLength(3);
const input = { backtestId: f.draft.id, name: 'Ordinary reference', grid: {} };
const preview = await f.experiments.preview(input),
ordinary = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
actor()
);
for (const trial of [...start.experiment.trials, ...ordinary.trials]) {
await f.execute(trial.runId!);
}
const detail = await f.experiments.get(start.experiment.id);
expect(detail.counts.completed).toBe(3);
expect(detail.trials.every(t => t.comparable)).toBe(true);
const baseline = await f.api.getRunResults(detail.trials[0]!.runId!),
reference = await f.api.getRunResults(ordinary.trials[0]!.runId!);
expect(canonicalReproductionHash(baseline as CanonicalRunResult)).toBe(
canonicalReproductionHash(reference as CanonicalRunResult)
);
expect(await f.experiments.get(detail.id)).toEqual(detail);
expect((await f.experiments.list()).find(e => e.id === detail.id)!.kind).toBe(
'cost-sensitivity'
);
expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(detail.id);
}, 60000);
});
const result = async (f: Fixture, id: string) =>
(await f.api.getRunResults(id)) as CanonicalRunResult;
describe.skipIf(!url)('cost financial and recovery proofs', () => {
test('Rust alone applies exact execution fees and adverse slippage, resetting capital for every scenario', async () => {
const f = await fixture();
f.input.scenarios.push({ feeRate: '0.02', slippageRate: '0.01' });
const start = await submit(f);
const oracle = [
{ prices: ['5.00000000', '2.00000000'], fees: '0.70000000', equity: '9969.30000000' },
{ prices: ['5.00000000', '2.00000000'], fees: '0.07000000', equity: '9969.93000000' },
{ prices: ['5.05000000', '1.98000000'], fees: '0.00000000', equity: '9969.30000000' },
{ prices: ['5.05000000', '1.98000000'], fees: '1.40600000', equity: '9967.89400000' },
];
for (const [index, trial] of start.experiment.trials.entries()) {
await f.execute(trial.runId!);
const saved = await result(f, trial.runId!),
expected = oracle[index]!;
expect(String(saved.financial.reporting.initialEquity)).toBe('10000.00000000');
expect(saved.financial.projection.fills.map(fill => String(fill.price))).toEqual(
expected.prices
);
expect(saved.financial.projection.fills.map(fill => String(fill.quantity))).toEqual([
'10.00000000',
'10.00000000',
]);
expect(String(saved.financial.projection.valuation.fees)).toBe(expected.fees);
expect(String(saved.financial.projection.valuation.equity)).toBe(expected.equity);
}
}, 60000);
test('fee-inclusive funding cannot be bypassed by a lower-cost scenario; unchanged risk may change fills', async () => {
const f = await fixture(1, true, 50);
f.input.scenarios = [{ feeRate: '0', slippageRate: '0' }];
const start = await submit(f);
for (const trial of start.experiment.trials) {
await f.execute(trial.runId!);
}
const baseline = await result(f, start.experiment.trials[0]!.runId!),
zero = await result(f, start.experiment.trials[1]!.runId!);
expect(baseline.financial.projection.fills).toEqual([]);
expect(String(baseline.financial.projection.valuation.cash)).toBe('50.00000000');
expect(zero.financial.projection.fills).toHaveLength(2);
expect(String(zero.financial.projection.valuation.cash)).toBe('20.00000000');
expect(baseline.request.policy.matching.risk.maxGrossExposure).toBe(
zero.request.policy.matching.risk.maxGrossExposure
);
}, 60000);
test('frozen source survives template edit, manual retry retains costs and reproduction retains exact economics', async () => {
const f = await fixture(),
start = await submit(f),
trial = start.experiment.trials[1]!,
runId = trial.runId!;
const snapshot = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
.rows[0].request_snapshot;
const claim = await f.repository.startCanonical(snapshot);
await f.repository.fail(runId, 'Cost attempt failure', claim.attemptId);
await f.api.updateBacktest(f.draft.id, {
name: 'Changed template',
initialCapital: 12000,
config: {
datasetHash: f.dataset.manifest.hash,
dataFrequency: '1m',
canonical: { ...canonicalSettings, feeRate: '0.03', slippageRate: '0.04' },
},
});
const newReview = await f.review();
const retry = await f.experiments.retryTrial(
start.experiment.id,
runId,
{ expectedAttemptNumber: 1, expectedRetryCount: 0 },
actor()
);
expect(retry.retry.error).toBe('Cost attempt failure');
expect(retry.retry.reviewId).toBe(newReview.id);
expect(
(await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0]
.request_snapshot
).toEqual(snapshot);
await f.execute(runId);
const original = await result(f, runId);
expect(String(original.request.policy.matching.risk.feeRate)).toBe('0.00100000');
const reproduction = await f.api.reproduceRun(runId, actor());
await f.execute(reproduction.id);
expect(canonicalReproductionHash(await result(f, reproduction.id))).toBe(
canonicalReproductionHash(original)
);
expect((await f.experiments.get(start.experiment.id)).preview).toEqual(start.preview);
await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow();
await f.review('revoke');
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
expect((await f.experiments.submitCosts(start.body, start.identity)).id).toBe(
start.experiment.id
);
await expect(f.experiments.submitCosts(start.body, actor())).rejects.toThrow();
}, 60000);
});
describe.skipIf(!url)('cost SQL and admission boundaries', () => {
test('first/idempotent upgrade preserves old evidence/leases and leaves v1 callable and non-request guard bodies unchanged', async () => {
const f = await fixture(1, false);
await f.review();
const input = { backtestId: f.draft.id, name: 'Old sweep', grid: { fastPeriod: [1, 2] } },
preview = await f.experiments.preview(input),
ordinary = await f.experiments.submit(
{ ...input, previewHash: preview.previewHash },
actor()
);
await f.execute(ordinary.trials[0]!.runId!);
const pending = ordinary.trials[1]!.runId!,
request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [pending]))
.rows[0].request_snapshot;
await f.repository.startCanonical(request);
const before = await f.snapshot();
const functions = async () =>
(
await f.pool.query(
'SELECT proname,pg_get_functiondef(oid) AS definition FROM pg_proc WHERE pronamespace=current_schema()::regnamespace ORDER BY proname'
)
).rows;
const oldFunctions = await functions(),
migration = readFileSync(
new URL('../../database/postgres/init/26-cost-sensitivity.sql', import.meta.url),
'utf8'
);
await f.pool.query(migration);
expect(await f.snapshot()).toEqual(before);
const changed = [
'require_experiment_manifest',
'require_active_backtest_for_new_run',
'require_experiment_retry_failure',
];
expect(
(await functions()).filter(
row =>
oldFunctions.some(old => old.proname === row.proname) && !changed.includes(row.proname)
)
).toEqual(oldFunctions.filter(row => !changed.includes(row.proname)));
const expectedBlocks = {
require_active_backtest_for_new_run: [
" expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(NEW.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||NEW.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');",
' expected := experiment_trial_request(experiment.preview,NEW.trial_index,NEW.id);',
],
require_experiment_retry_failure: [
" expected := jsonb_set(experiment.preview->'request','{runId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,sessionId}',to_jsonb(original.id::text));\n expected := jsonb_set(expected,'{policy,matching,risk,ledger,accountId}',to_jsonb('research:'||original.id::text));\n expected := jsonb_set(expected,'{strategy,selection,parameters}',candidate->'parameters');",
' expected := experiment_trial_request(experiment.preview,original.trial_index,original.id);',
],
};
const now = await functions();
for (const [name, [oldBlock, newBlock]] of Object.entries(expectedBlocks)) {
expect(now.find(r => r.proname === name)!.definition).toBe(
oldFunctions.find(r => r.proname === name)!.definition.replace(oldBlock, newBlock)
);
}
await f.pool.query(migration);
expect(await f.snapshot()).toEqual(before);
expect((await submit(f)).experiment.trials).toHaveLength(3);
}, 60000);
test('late candidate, outbox failure and omitted dispatch roll back all children and receipt', async () => {
const f = await fixture();
await f.review();
const preview = await f.experiments.previewCosts(f.input),
body = { ...f.input, previewHash: preview.previewHash };
for (const [table, condition, action, message] of [
['runs', 'NEW.trial_index=2', "RAISE EXCEPTION 'Injected failure';", 'Injected'],
[
'backtest_dispatch',
'EXISTS(SELECT 1 FROM runs r WHERE r.id=NEW.run_id AND r.trial_index=2)',
"RAISE EXCEPTION 'Injected failure';",
'Injected',
],
['backtest_dispatch', 'TRUE', 'RETURN NULL;', 'atomically'],
]) {
await f.pool.query(
`CREATE OR REPLACE FUNCTION cost_injection() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF ${condition} THEN ${action} END IF; RETURN NEW; END $$`
);
await f.pool.query(
`CREATE TRIGGER cost_injection BEFORE INSERT ON ${table} FOR EACH ROW EXECUTE FUNCTION cost_injection()`
);
const before = await f.snapshot();
await expect(f.experiments.submitCosts(body, actor())).rejects.toThrow(message);
expect(await f.snapshot()).toEqual(before);
await f.pool.query(`DROP TRIGGER cost_injection ON ${table}`);
}
expect((await f.experiments.submitCosts(body, actor())).trials).toHaveLength(3);
}, 60000);
test('same/cross-parent/cross-kind receipt races produce exactly one operation owner', async () => {
const f = await fixture(5);
await f.review();
const preview = await f.experiments.previewCosts(f.input),
body = { ...f.input, previewHash: preview.previewHash },
identity = actor();
const [first, replay] = await Promise.all([
f.experiments.submitCosts(body, identity),
f.experiments.submitCosts(body, identity),
]);
expect(first.id).toBe(replay.id);
const other = await f.cloneTemplate(),
otherInput = { ...f.input, backtestId: other.id },
otherPreview = await f.experiments.previewCosts(otherInput),
cross = actor();
const race = await Promise.allSettled([
f.experiments.submitCosts(body, cross),
f.experiments.submitCosts({ ...otherInput, previewHash: otherPreview.previewHash }, cross),
]);
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(race.filter(r => r.status === 'rejected')).toHaveLength(1);
const normalInput = { backtestId: f.draft.id, name: 'Parameter sweep', grid: {} },
normal = await f.experiments.preview(normalInput),
mixed = actor();
const mixedRace = await Promise.allSettled([
f.experiments.submitCosts(body, mixed),
f.experiments.submit({ ...normalInput, previewHash: normal.previewHash }, mixed),
]);
expect(mixedRace.filter(r => r.status === 'fulfilled')).toHaveLength(1);
expect(mixedRace.filter(r => r.status === 'rejected')).toHaveLength(1);
for (const item of [...race, ...mixedRace]) {
if (item.status === 'rejected') {
expect(item.reason).toBeInstanceOf(ExperimentError);
expect(item.reason.status).toBe(409);
}
}
expect((await f.pool.query('SELECT count(*)::int n FROM research_experiments')).rows[0].n).toBe(
3
);
await expect(f.experiments.submitCosts({ ...body, name: 'Changed' }, identity)).rejects.toThrow(
'different'
);
}, 60000);
test('SQL targets exact source, baseline, cost shape, parameters and two-path request isolation', async () => {
const f = await fixture(),
start = await submit(f),
row = (
await f.pool.query('SELECT * FROM research_experiments WHERE id=$1', [start.experiment.id])
).rows[0];
const validate = async (preview: unknown) =>
f.pool.query(
'SELECT validate_cost_manifest(jsonb_populate_record(NULL::research_experiments,$1))',
[{ ...row, preview }]
);
await validate(start.preview);
for (const [mutate, message] of [
[(p: typeof start.preview) => (p.source.input.grid = { fastPeriod: [1] }), 'empty-grid'],
[
(p: typeof start.preview) =>
(p.request = structuredClone({ ...p.request, name: 'Foreign' })),
'empty-grid',
],
[
(p: typeof start.preview) => (p.candidates[0]!.costs = { feeRate: '0', slippageRate: '0' }),
'exact ordered',
],
[
(p: typeof start.preview) =>
(p.candidates[1]!.parameters = { fastPeriod: 1, slowPeriod: 3 }),
'fixed parameters',
],
[
(p: typeof start.preview) =>
(p.candidates[1]!.costs = { feeRate: '0.001', slippageRate: '0.00000000' }),
'exact ordered',
],
[
(p: typeof start.preview) => {
p.input.scenarios[0]!.slippageRate = '1.00000000';
p.candidates[1]!.costs.slippageRate = '1.00000000';
},
'canonical bounds',
],
[
(p: typeof start.preview) => {
p.input.scenarios[0] = { ...p.candidates[0]!.costs };
p.candidates[1]!.costs = { ...p.candidates[0]!.costs };
},
'distinct',
],
] as const) {
const preview = structuredClone(start.preview);
mutate(preview);
await expect(validate(preview)).rejects.toThrow(message);
}
const ordinaryInput = { backtestId: f.draft.id, name: 'Ordinary', grid: {} },
normal = await f.experiments.preview(ordinaryInput);
await expect(
f.pool.query(
'INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8)',
[
randomUUID(),
f.draft.id,
ordinaryInput.name,
{
...normal,
candidates: normal.candidates.map(c => ({
...c,
costs: { feeRate: '0', slippageRate: '0' },
})),
},
normal.previewHash,
'operator',
randomUUID(),
'a'.repeat(64),
]
)
).rejects.toThrow('cannot contain');
const clone = { ...row, id: randomUUID(), submission_key: randomUUID() };
await expect(
f.pool.query(
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
[clone]
)
).rejects.toThrow('atomically');
const run = (
await f.pool.query('SELECT * FROM runs WHERE id=$1', [start.experiment.trials[1]!.runId])
).rows[0];
const inserted = async (mutate: (r: Record<string, any>) => void) => {
const client = await f.pool.connect();
try {
await client.query('BEGIN');
const exp = { ...row, id: randomUUID(), submission_key: randomUUID() };
await client.query(
'INSERT INTO research_experiments SELECT * FROM jsonb_populate_record(NULL::research_experiments,$1)',
[exp]
);
const id = randomUUID(),
candidate = {
...run,
id,
experiment_id: exp.id,
run_number: 999,
request_snapshot: structuredClone(run.request_snapshot),
};
candidate.request_snapshot.runId = id;
candidate.request_snapshot.policy.matching.risk.ledger.sessionId = id;
candidate.request_snapshot.policy.matching.risk.ledger.accountId = `research:${id}`;
mutate(candidate);
await client.query('INSERT INTO runs SELECT * FROM jsonb_populate_record(NULL::runs,$1)', [
candidate,
]);
} finally {
await client.query('ROLLBACK');
client.release();
}
};
await expect(
inserted(r => (r.request_snapshot.policy.matching.risk.feeRate = '0.90000000'))
).rejects.toThrow('exact frozen');
await expect(
inserted(r => (r.request_snapshot.policy.matching.halfSpreadRate = '0.10000000'))
).rejects.toThrow('exact frozen');
await expect(inserted(r => (r.trial_index = 99))).rejects.toThrow('exact candidate');
expect((await f.experiments.get(start.experiment.id)).trials).toHaveLength(3);
}, 60000);
test('cancel overlaps a blocked manual retry, leaving no live work and retaining failure evidence', async () => {
const f = await fixture(5),
start = await submit(f),
runId = start.experiment.trials[1]!.runId!;
await f.pool.query(
"UPDATE runs SET status='failed',error='Cost failure',completed_at=NOW() WHERE id=$1",
[runId]
);
const before = (await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId]))
.rows;
const blocker = await f.pool.connect();
await blocker.query('BEGIN');
await blocker.query('SELECT id FROM backtests WHERE id=$1 FOR UPDATE', [f.draft.id]);
const pending = Promise.allSettled([
f.experiments.retryTrial(
start.experiment.id,
runId,
{ expectedAttemptNumber: 0, expectedRetryCount: 0 },
actor()
),
]);
try {
let count = 0;
for (let i = 0; i < 100; i++) {
count = Number(
(
await f.pool.query(
"SELECT count(*)::int n FROM pg_stat_activity WHERE application_name=current_schema() AND wait_event_type='Lock'"
)
).rows[0].n
);
if (count > 0) {
break;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
expect(count).toBeGreaterThan(0);
await f.experiments.cancel(start.experiment.id);
await blocker.query('COMMIT');
} finally {
await blocker.query('ROLLBACK');
blocker.release();
}
const outcome = (await pending)[0]!;
expect(outcome.status).toBe('rejected');
if (outcome.status === 'rejected') {
expect(outcome.reason).toBeInstanceOf(ExperimentError);
expect(outcome.reason.status).toBe(409);
}
expect(
(await f.pool.query('SELECT to_jsonb(r) row FROM runs r WHERE id=$1', [runId])).rows
).toEqual(before);
const detail = await f.experiments.get(start.experiment.id);
expect(detail.cancelRequested).toBe(true);
expect(detail.trials.filter(t => t.status === 'cancelled')).toHaveLength(2);
}, 60000);
});

View file

@ -78,6 +78,7 @@ async function fixture() {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')

View file

@ -89,6 +89,7 @@ async function fixture() {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -70,7 +70,12 @@ async function fixture(poolMax = 4, withRetries = true) {
'21-run-reproduction.sql',
'22-experiments.sql',
...(withRetries
? ['23-experiment-retries.sql', '24-chronological-validation.sql', '25-walk-forward.sql']
? [
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]
: []),
]) {
await pool.query(

View file

@ -70,6 +70,7 @@ async function fixture(poolMax = 4, withExperiments = true) {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]
: []),
]) {

View file

@ -28,6 +28,7 @@ const migrations = [
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
];
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {

View file

@ -33,7 +33,9 @@ const retention =
'\n' +
sql('24-chronological-validation.sql') +
'\n' +
sql('25-walk-forward.sql');
sql('25-walk-forward.sql') +
'\n' +
sql('26-cost-sensitivity.sql');
const request = {
name: 'Retained evidence',
strategy: 'sma-crossover',

View file

@ -74,6 +74,7 @@ async function fixture() {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')

View file

@ -65,6 +65,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]) {
await pool.query(sql(name));
}

View file

@ -68,6 +68,7 @@ async function fixture(poolMax = 4, withReproduction = true) {
'23-experiment-retries.sql',
'24-chronological-validation.sql',
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
]
: []),
]) {

View file

@ -71,7 +71,7 @@ async function fixture(poolMax = 1, withWalkForward = true) {
'22-experiments.sql',
'23-experiment-retries.sql',
'24-chronological-validation.sql',
...(withWalkForward ? ['25-walk-forward.sql'] : []),
...(withWalkForward ? ['25-walk-forward.sql', '26-cost-sensitivity.sql'] : []),
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')