feat(research): compare saved experiments against explicit trials

This commit is contained in:
Boki 2026-10-24 14:06:21 -04:00
parent 397cd0e160
commit 46a4f13acd
22 changed files with 3045 additions and 35 deletions

View file

@ -16,6 +16,7 @@ import {
type CostSensitivityDetail,
type CostSensitivityPreview,
} from '@stock-bot/stock-config/cost-sensitivity';
import type { ExperimentComparison } from '@stock-bot/stock-config/experiment-comparison';
import type {
ExperimentDetail,
ExperimentPreview,
@ -54,6 +55,190 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
test('saved_experiment_comparison_preserves_cost_reference_native_summaries_and_archived_history_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 saved comparison fixture',
});
const definition = {
name: 'Saved comparison 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,
});
const costInput = {
backtestId: backtest.id,
name: 'Older cost experiment',
scenarios: [
{ feeRate: '0.02', slippageRate: '0' },
{ feeRate: '0.01', slippageRate: '0.02' },
],
};
const { preview: costPreview } = (await f.request(
'/api/v2/experiments/cost-sensitivity/preview',
'POST',
costInput
)) as { preview: CostSensitivityPreview };
const { experiment: costs } = (await f.request(
'/api/v2/experiments/cost-sensitivity',
'POST',
{ ...costInput, previewHash: costPreview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: CostSensitivityDetail };
const parameterInput = {
backtestId: backtest.id,
name: 'Newer parameter experiment',
grid: { fastPeriod: [1, 2] },
};
const { preview } = (await f.request(
'/api/v2/experiments/preview',
'POST',
parameterInput
)) as { preview: ExperimentPreview };
const { experiment: parameters } = (await f.request(
'/api/v2/experiments',
'POST',
{ ...parameterInput, previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: ExperimentDetail };
f.dispatcher.start();
await until(
async () =>
(await f.pool.query("SELECT count(*)::int AS n FROM runs WHERE status='completed'")).rows[0]
.n === 5,
'five native cost and parameter trials complete'
);
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Mutable template changed after execution',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
await f.request(`/api/v2/backtests/${backtest.id}/archive`, 'POST', { archived: true });
await f.request(`/api/v2/strategy-versions/${version.id}/reviews`, 'POST', {
decision: 'revoke',
reason: 'Historical reads must not require current admission approval',
});
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [version.strategyId]);
const durableCounts = async () =>
(
await f.pool.query(`SELECT
(SELECT count(*)::int FROM runs) AS runs,
(SELECT count(*)::int FROM backtest_dispatch) AS dispatch,
(SELECT count(*)::int FROM research_experiments) AS experiments,
(SELECT sum(manual_retry_count)::int FROM runs) AS retries`)
).rows[0];
const before = await durableCounts();
const query = new URLSearchParams({ leftId: costs.id, rightId: parameters.id });
const endpoint = `/api/v2/experiments/compare?${query}`;
const { comparison } = (await f.request(endpoint)) as { comparison: ExperimentComparison };
expect(comparison.selection.referenceTrialKey).toBe(costs.trials[0]!.trialKey);
expect(comparison.rows.map(row => row.differences)).toEqual([[], ['costs'], ['costs'], [], []]);
expect(comparison.rows.map(row => row.ready)).toEqual([true, false, false, true, true]);
for (const experiment of comparison.experiments) {
for (const trial of experiment.trials) {
const result = (await f.request(
`/api/v2/runs/${trial.runId}/results`
)) as CanonicalRunResult;
expect(result.financialEngine).toBe('rust');
expect(trial.metrics).toEqual(result.analytics.metrics);
expect(trial.unavailable).toEqual(result.analytics.unavailable);
}
}
await f.login();
await f.page.goto(`${f.origin}/experiments`);
// Click order, rather than the newest-first list, chooses the explicit left reference.
await f.page.getByLabel(`Select ${costs.name} for comparison`, { exact: true }).check();
await f.page.getByLabel(`Select ${parameters.name} for comparison`, { exact: true }).check();
await f.page.getByRole('link', { name: 'Compare selected experiments', exact: true }).click();
await f.page.getByRole('heading', { name: 'Compare experiments', exact: true }).waitFor();
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(new URL(f.page.url()).searchParams.get('leftId')).toBe(costs.id);
expect(new URL(f.page.url()).searchParams.get('rightId')).toBe(parameters.id);
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
costs.trials[0]!.trialKey
);
expect(await f.page.getByText('Matching settings', { exact: true }).count()).toBe(3);
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(2);
expect(await f.page.getByText('Saved summary available', { exact: true }).count()).toBe(5);
for (const experiment of comparison.experiments) {
for (const trial of experiment.trials) {
const row = f.page.locator(
`tr:has(a[href="/backtests/${backtest.id}/run/${trial.runId}"])`
);
expect(await row.count()).toBe(1);
expect(await row.innerText()).toContain(String(trial.metrics!.totalReturn));
}
}
const referenceKey = costs.trials[1]!.trialKey;
const changedRead = f.page.waitForResponse(response => {
const url = new URL(response.url());
return (
url.pathname === '/api/v2/experiments/compare' &&
url.searchParams.get('referenceTrialKey') === referenceKey
);
});
await f.page.getByLabel('Reference trial', { exact: true }).selectOption(referenceKey);
const response = await changedRead;
expect(response.status()).toBe(200);
const changed = (await response.json()) as { comparison: ExperimentComparison };
expect(changed.comparison.rows.map(row => row.differences)).toEqual([
['costs'],
[],
['costs'],
['costs'],
['costs'],
]);
await until(
async () => (await f.page.getByText('Matching settings', { exact: true }).count()) === 1,
'explicit cost reference replaces comparison'
);
expect(new URL(f.page.url()).searchParams.get('referenceTrialKey')).toBe(referenceKey);
const savedUrl = f.page.url();
await f.page.reload();
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
referenceKey
);
expect(await f.page.getByText('Settings differ', { exact: true }).count()).toBe(4);
await f.page
.locator(`a[href="/backtests/${backtest.id}/run/${costs.trials[1]!.runId}"]`)
.click();
await visible(f.page, 'Canonical research result');
await f.page.goto(savedUrl);
await f.page.getByLabel('Reference trial', { exact: true }).waitFor();
expect(await f.page.getByLabel('Reference trial', { exact: true }).inputValue()).toBe(
referenceKey
);
expect(await durableCounts()).toEqual(before);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
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());

View file

@ -0,0 +1,128 @@
import { describe, expect, mock, test } from 'bun:test';
import { Hono } from 'hono';
import { z } from 'zod';
import { createHttpSecurity } from '@stock-bot/di';
import type { IServiceContainer } from '@stock-bot/services';
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
const tokens = {
operator: 'validation-admin-fixture-not-a-real-secret-1234',
service: 'validation-service-fixture-not-a-real-secret-1234',
read: 'validation-read-fixture-not-a-real-secret-1234',
};
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
function fixture(
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
query: Query = async () => ({ rows: [] })
) {
const client = { query: mock(query) };
const database = {
query: mock(query),
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
};
const app = new Hono();
if (mode !== 'absent') {
createHttpSecurity({
adminToken: tokens.operator,
serviceToken: tokens.service,
readToken: tokens.read,
environment: 'test',
hostname: '127.0.0.1',
disabled: mode === 'disabled',
}).mount(app);
}
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
return {
database,
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
return app.request('/api/v2/experiments' + path, {
method,
headers: {
'Content-Type': 'application/json',
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
...(key ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body }),
});
},
};
}
const leftId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
rightId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
query = `?leftId=${leftId}&rightId=${rightId}`;
describe('experiment comparison HTTP boundary', () => {
test('authorized read clients may compare without mutation credentials; unauthenticated reads are denied', async () => {
const f = fixture();
expect((await f.request('/compare' + query)).status).toBe(401);
for (const role of ['read', 'operator', 'service'] as const) {
const response = await f.request('/compare' + query, 'GET', undefined, role);
expect(response.status).toBe(404);
expect(response.headers.get('Cache-Control')).toBe('no-store');
}
expect(f.database.query.mock.calls).toHaveLength(0);
});
test('unknown/duplicate query keys, malformed IDs, same pair and reference keys fail before transactions', async () => {
for (const suffix of [
'',
`?leftId=${leftId}`,
query + '&unknown=1',
query + '&leftId=' + leftId,
query + '&%6CeftId=' + leftId,
query + '&referenceTrialKey=x',
`?leftId=${leftId}&rightId=${leftId}`,
`?leftId=${leftId}&rightId=${leftId.toUpperCase()}`,
query + '&referenceTrialKey=' + 'a'.repeat(64) + '&referenceTrialKey=' + 'a'.repeat(64),
]) {
const f = fixture();
expect((await f.request('/compare' + suffix, 'GET', undefined, 'read')).status).toBe(400);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
});
test('valid UUID casing normalizes before querying retained experiment identities', async () => {
const identifiers: unknown[] = [];
const f = fixture('enabled', async (sql, values) => {
if (sql.includes('SELECT id,validation_phase')) {
identifiers.push(values?.[0]);
}
return { rows: [] };
});
expect(
(
await f.request(
`/compare?leftId=${leftId.toUpperCase()}&rightId=${rightId.toUpperCase()}`,
'GET',
undefined,
'read'
)
).status
).toBe(404);
expect(identifiers).toEqual([[leftId, rightId]]);
});
test('snapshot mode precedes role reads; unsupported phases409 and unexpected DB errors500 are sanitized', async () => {
const calls: string[] = [];
const f = fixture('enabled', async sql => {
calls.push(sql);
if (sql.includes('SELECT id,validation_phase')) {
return {
rows: [
{ id: leftId, validation_phase: 'train' },
{ id: rightId, validation_phase: null },
],
};
}
return { rows: [] };
});
expect((await f.request('/compare' + query, 'GET', undefined, 'read')).status).toBe(409);
expect(calls[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(calls).toHaveLength(2);
for (const error of [new Error('private storage error'), new z.ZodError([])]) {
const broken = fixture('enabled', async () => {
throw error;
});
const response = await broken.request('/compare' + query, 'GET', undefined, 'read');
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
}
});
});

View file

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

View file

@ -0,0 +1,399 @@
import { randomUUID } from 'node:crypto';
import { describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import type {
CostSensitivityInput,
WorkbenchExperimentDetail,
WorkbenchExperimentPreview,
} from '@stock-bot/stock-config/cost-sensitivity';
import {
experimentComparisonDimensions,
type ExperimentComparisonDimension,
} from '@stock-bot/stock-config/experiment-comparison';
import { builtinCatalogDescriptors, canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import {
parseFinancialDecimal,
type CanonicalBacktestAnalytics,
type HistoricalDatasetV2,
} from '@stock-bot/types';
import { canonicalRiskSessionClock } from '../../apps/stock/web-api/src/services/canonical-risk-clock';
import { buildCostSensitivityPreview } from '../../apps/stock/web-api/src/services/cost-sensitivity-input';
import {
compareExperiments,
comparisonConditions,
parseExperimentComparison,
} from '../../apps/stock/web-api/src/services/experiment-comparison';
import {
buildExperimentPreview,
PREVIEW_RUN_ID,
} from '../../apps/stock/web-api/src/services/experiment-input';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
import { nativeReplayFixture } from '../fixtures/native-replay';
const backtestId = '10000000-0000-4000-8000-000000000001';
const versionId = '20000000-0000-4000-8000-000000000001';
const owner = `strategy:${versionId}`;
const input = (): CostSensitivityInput => ({
backtestId,
name: 'Cost diagnostics',
scenarios: [
{ feeRate: '0', slippageRate: '0' },
{ feeRate: '0.02', slippageRate: '0.01' },
],
});
function source(dataset: HistoricalDatasetV2, raw = input()) {
const experiment = { backtestId: raw.backtestId, name: raw.name, grid: {} };
const descriptor = builtinCatalogDescriptors[0]!;
const policy = structuredClone(nativeReplayFixture(36, 1, [owner]).config);
const clock = canonicalRiskSessionClock(dataset);
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
policy.matching.risk.ledger.riskSession = clock.riskSession;
policy.risk_boundaries = clock.riskBoundaries;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId: PREVIEW_RUN_ID,
backtestId,
name: 'Template',
strategy: {
familyId: '30000000-0000-4000-8000-000000000001',
versionId,
origin: 'builtin',
reviewId: '40000000-0000-4000-8000-000000000001',
package: {
version: 1,
program: descriptor.program,
parameterSchema: descriptor.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content: 'fixture',
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
},
selection: {
strategyId: descriptor.program.strategyId,
strategyVersion: descriptor.program.strategyVersion,
ownerId: owner,
seed: 42,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '40',
parameters: { fastPeriod: 2, slowPeriod: 3 },
},
},
datasetHash: dataset.manifest.hash,
policy,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
build: {
version: 1,
workerSha256: 'a'.repeat(64),
engineWrapperSha256: 'b'.repeat(64),
engineBinarySha256: 'c'.repeat(64),
dependencyLockSha256: 'd'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'linux',
arch: 'x64',
},
modelArtifacts: [],
});
return buildExperimentPreview(experiment, request, dataset.manifest);
}
function detail(preview: WorkbenchExperimentPreview, id = randomUUID()): WorkbenchExperimentDetail {
const metrics: CanonicalBacktestAnalytics['metrics'] = {
totalReturn: 0,
cagr: null,
maxDrawdown: null,
exposureTime: null,
volatility: null,
downsideDeviation: null,
sharpeRatio: null,
sortinoRatio: null,
var95: null,
cvar95: null,
var99: null,
alpha: null,
beta: null,
informationRatio: null,
roundTripCount: null,
winRate: null,
profitFactor: null,
avgWin: null,
avgLoss: null,
};
return {
id,
backtestId: preview.input.backtestId,
name: preview.input.name,
kind: preview.version === 'cost-sensitivity-preview/v1' ? 'cost-sensitivity' : 'parameters',
createdAt: '2026-01-01T00:00:00.000Z',
cancelRequested: false,
trialCount: preview.candidates.length,
counts: {
pending: 0,
running: 0,
paused: 0,
completed: preview.candidates.length,
failed: 0,
cancelled: 0,
},
datasetHash: preview.request.datasetHash,
strategyVersionId: preview.request.strategy.versionId,
previewHash: preview.previewHash,
preview,
trials: preview.candidates.map(candidate => ({
...candidate,
runId: randomUUID(),
attemptNumber: 1,
retryCount: 0,
status: 'completed' as const,
progress: 100,
cancelRequested: false,
error: null,
comparable: true,
diagnostic: null,
metrics,
unavailable: { sharpeRatio: 'insufficient-periods' as const },
limitations: ['fixture compact summary'],
})),
} as WorkbenchExperimentDetail;
}
const differences = (
first: Record<ExperimentComparisonDimension, unknown>,
second: Record<ExperimentComparisonDimension, unknown>
) =>
experimentComparisonDimensions.filter(
key => canonicalStrategyJson(first[key]) !== canonicalStrategyJson(second[key])
);
describe('retained input comparison policy', () => {
test('names/run/account/version-owner IDs and strategy/parameters may vary without mutating either input', () => {
const data = canonicalSmaFixture().dataset,
baseline = source(data),
original = structuredClone(baseline),
changed = structuredClone(baseline.request),
version = randomUUID(),
owner = `strategy:${version}`,
runId = randomUUID();
changed.name = 'Other presentation';
changed.runId = runId;
changed.backtestId = randomUUID();
changed.strategy.familyId = randomUUID();
changed.strategy.versionId = version;
changed.strategy.reviewId = randomUUID();
changed.strategy.package.artifact.content = 'Other trusted implementation';
changed.strategy.package.artifact.sha256 = 'f'.repeat(64);
changed.strategy.selection.parameters = { fastPeriod: 1, slowPeriod: 3 };
changed.strategy.selection.ownerId = owner;
changed.policy.matching.risk.ledger.sessionId = runId;
changed.policy.matching.risk.ledger.accountId = `research:${runId}`;
changed.policy.matching.risk.ledger.ownerIds = [owner];
changed.policy.matching.owners[0]!.ownerId = owner;
changed.policy.cadence[0]!.owner_id = owner;
const before = structuredClone(changed);
expect(comparisonConditions(changed, data.manifest)).toEqual(
comparisonConditions(baseline.request, data.manifest)
);
expect(changed).toEqual(before);
expect(baseline).toEqual(original);
});
test('every mutable financial/execution/clock/analytics/seed/build condition lands in its explicit mismatch partition', () => {
const data = canonicalSmaFixture().dataset,
baseline = source(data).request,
original = comparisonConditions(baseline, data.manifest);
const cases: [ExperimentComparisonDimension, (r: CanonicalRunRequest) => void][] = [
['dataset', r => (r.datasetHash = 'f'.repeat(64))],
[
'capital',
r =>
(r.policy.matching.risk.ledger.initialCapital = parseFinancialDecimal('20000.00000000')),
],
['capital', r => (r.strategy.selection.ownerBudget = parseFinancialDecimal('50.00000000'))],
['costs', r => (r.policy.matching.risk.feeRate = parseFinancialDecimal('0.20000000'))],
['costs', r => (r.policy.matching.halfSpreadRate = parseFinancialDecimal('0.10000000'))],
['costs', r => (r.policy.matching.slippageRate = parseFinancialDecimal('0.10000000'))],
['execution', r => (r.policy.matching.latencyMs = 1)],
['execution', r => (r.policy.participation_rate = parseFinancialDecimal('0.50000000'))],
[
'execution',
r => {
r.strategy.selection.instrumentId = 'OTHER';
r.policy.matching.series[0]!.instrumentId = 'OTHER';
},
],
[
'execution',
r => {
r.strategy.selection.seriesId = 'OTHER:1m';
r.policy.matching.series[0]!.seriesId = 'OTHER:1m';
r.policy.cadence[0]!.series_ids = ['OTHER:1m'];
},
],
[
'clock',
r =>
(r.policy.matching.risk.ledger.riskSession.sessionId =
'economic-session-must-not-normalize'),
],
['clock', r => (r.policy.matching.risk.ledger.riskSession.calendarId = 'other-calendar')],
[
'clock',
r => (r.policy.matching.risk.ledger.riskSession.calendarRevision = 'other-revision'),
],
['clock', r => (r.policy.matching.risk.ledger.riskSession.startsAt += 1)],
[
'clock',
r =>
r.policy.risk_boundaries.push({
...r.policy.matching.risk.ledger.riskSession,
sessionId: 'later',
startsAt: r.policy.matching.risk.ledger.riskSession.startsAt + 1000,
}),
],
['analytics', r => (r.analyticsPolicy.periodsPerYear = 365)],
['analytics', r => (r.analyticsPolicy.annualRiskFreeRate = 0.01)],
['seed', r => (r.strategy.selection.seed = 99)],
];
for (const key of [
'maxOrderQuantity',
'maxPositionQuantity',
'maxSymbolExposure',
'maxGrossExposure',
'maxDailyLoss',
'maxDrawdownAmount',
] as const) {
cases.push([
'risk',
r => (r.policy.matching.risk[key] = parseFinancialDecimal('20000.00000000')),
]);
}
cases.push(['risk', r => (r.policy.matching.risk.maxMarkAgeMs += 1)]);
for (const key of [
'workerSha256',
'engineWrapperSha256',
'engineBinarySha256',
'dependencyLockSha256',
] as const) {
cases.push(['build', r => (r.build[key] = 'f'.repeat(64))]);
}
for (const key of ['runtimeVersion', 'platform', 'arch'] as const) {
cases.push(['build', r => (r.build[key] = 'changed')]);
}
for (const [dimension, mutate] of cases) {
const request = structuredClone(baseline);
mutate(request);
expect(differences(original, comparisonConditions(request, data.manifest))).toEqual([
dimension,
]);
}
const bounds = {
...data.manifest,
bounds: { ...data.manifest.bounds, tradeEnd: data.manifest.bounds.tradeEnd - 1 },
};
expect(differences(original, comparisonConditions(baseline, bounds))).toEqual([
'dataset',
'window',
]);
const provenance = {
...data.manifest,
calendars: data.manifest.calendars.map(calendar => ({ ...calendar, revision: 'changed' })),
};
expect(differences(original, comparisonConditions(baseline, provenance))).toEqual(['dataset']);
});
test('unsupported currency/reserve/owner modes/models reject canonical parsing instead of silently matching', () => {
const data = canonicalSmaFixture().dataset,
baseline = source(data).request;
for (const mutate of [
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.baseCurrency = 'EUR'),
(r: CanonicalRunRequest) => (r.policy.matching.risk.ledger.reserveOwnerId = 'foreign'),
(r: CanonicalRunRequest) => (r.policy.matching.owners[0]!.mode = 'Orders'),
(r: CanonicalRunRequest) => (r.policy.allow_exploratory = true),
(r: CanonicalRunRequest) => Object.assign(r, { modelArtifacts: [{ id: 'unsupported' }] }),
]) {
const request = structuredClone(baseline);
mutate(request);
expect(() => comparisonConditions(request, data.manifest)).toThrow();
}
});
test('effective scenario costs compare across experiments, independently of summary availability and reference order', () => {
const baseline = source(canonicalSmaFixture().dataset),
costs = buildCostSensitivityPreview(input(), baseline),
left = detail(costs),
right = detail(
buildCostSensitivityPreview(
{ ...input(), scenarios: [...input().scenarios].reverse() },
baseline
)
);
const before = structuredClone([left, right] as [
WorkbenchExperimentDetail,
WorkbenchExperimentDetail,
]),
selected = left.trials[1]!.trialKey;
const compared = compareExperiments(
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
[left, right]
);
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
'mismatch',
'match',
'mismatch',
'mismatch',
'mismatch',
'match',
]);
expect(compared.rows.map(r => r.ready)).toEqual([false, true, false, false, false, true]);
expect(compared.experiments).toEqual(before);
expect([left, right]).toEqual(before);
left.trials[1]!.status = 'failed';
left.trials[1]!.comparable = false;
left.trials[1]!.diagnostic = 'Retained failure';
left.trials[1]!.metrics = null;
const failed = compareExperiments(
{ leftId: left.id, rightId: right.id, referenceTrialKey: selected },
[left, right]
);
expect(failed.reference.summaryAvailable).toBe(false);
expect(failed.reference.diagnostic).toBe('Retained failure');
expect(failed.rows.every(r => !r.ready)).toBe(true);
expect(failed.rows[5]!.summaryAvailable).toBe(true);
expect(failed.rows[5]!.inputCompatibility).toBe('match');
});
test('missing first candidate remains the default; zero/null metrics and completed cancellation are retained', () => {
const baseline = source(canonicalSmaFixture().dataset),
left = detail(buildCostSensitivityPreview(input(), baseline)),
right = detail(baseline);
left.trials[0]!.runId = null;
left.trials[0]!.status = 'missing';
left.trials[0]!.comparable = false;
left.trials[0]!.diagnostic = 'Expected trial run is missing';
left.trials[0]!.metrics = null;
right.cancelRequested = true;
const comparison = compareExperiments({ leftId: left.id, rightId: right.id }, [left, right]);
expect(comparison.selection.referenceTrialKey).toBe(left.trials[0]!.trialKey);
expect(comparison.reference.runId).toBeNull();
expect(comparison.rows.every(r => !r.ready)).toBe(true);
expect(comparison.experiments[1].trials[0]!.metrics!.totalReturn).toBe(0);
expect(comparison.experiments[1].trials[0]!.metrics!.sharpeRatio).toBeNull();
expect(comparison.experiments[1].trials[0]!.unavailable!.sharpeRatio).toBe(
'insufficient-periods'
);
expect(comparison.experiments[1].cancelRequested).toBe(true);
expect(() =>
compareExperiments(
{ leftId: left.id, rightId: right.id, referenceTrialKey: 'f'.repeat(64) },
[left, right]
)
).toThrow('does not belong');
expect(() => parseExperimentComparison({ leftId: left.id, rightId: left.id })).toThrow(
'distinct'
);
});
});

View file

@ -0,0 +1,434 @@
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 type { PoolClient } from 'pg';
import { createHttpSecurity } from '@stock-bot/di';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient } from '@stock-bot/postgres';
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 { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
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';
import { chronologicalDataset } from '../fixtures/chronological-validation';
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 = {
read: 'comparison-read-fixture-not-a-real-secret-1234',
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,
readToken: tokens.read,
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 }
),
app,
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 pair(f: Fixture) {
await f.review();
const costPreview = await f.experiments.previewCosts(f.input),
left = await f.experiments.submitCosts(
{ ...f.input, previewHash: costPreview.previewHash },
actor()
);
const input = {
backtestId: f.draft.id,
name: 'Other parameters',
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
},
preview = await f.experiments.preview(input),
right = await f.experiments.submit({ ...input, previewHash: preview.previewHash }, actor());
return { left, right, input: { leftId: left.id, rightId: right.id } };
}
const request = (f: Fixture, query: Record<string, string>) =>
f.app.request('/api/v2/experiments/compare?' + new URLSearchParams(query), {
headers: { Authorization: `Bearer ${tokens.read}` },
});
describe.skipIf(!url)('saved experiment comparison snapshot', () => {
test('pool1 native pair returns all compact summaries and actual scenario costs without writes; archive and template edits do not gate historical reopen', async () => {
const f = await fixture(),
p = await pair(f);
for (const trial of [...p.left.trials, ...p.right.trials]) {
await f.execute(trial.runId!);
}
const before = await f.snapshot();
const compared = await f.experiments.compare(p.input);
expect(await f.snapshot()).toEqual(before);
expect(compared.experiments.map(e => e.id)).toEqual([p.left.id, p.right.id]);
expect(compared.rows).toHaveLength(5);
expect(compared.rows.map(r => r.inputCompatibility)).toEqual([
'match',
'mismatch',
'mismatch',
'match',
'match',
]);
expect(compared.rows.map(r => r.ready)).toEqual([true, false, false, true, true]);
expect(compared.experiments[0].trials[0]!.metrics!.totalReturn).toBeCloseTo(-0.00307, 10);
expect(compared.experiments[0].trials[0]!.metrics!.sharpeRatio).toBeNull();
expect(compared.experiments[0].trials[0]!.unavailable!.sharpeRatio).toBeDefined();
expect(
compared.experiments[0].trials.every(
t => !('financial' in t) && !('trades' in t) && !('sessionReturns' in t)
)
).toBe(true);
const selected = await f.experiments.compare({
...p.input,
referenceTrialKey: p.left.trials[1]!.trialKey,
});
expect(selected.reference.index).toBe(1);
expect(selected.rows[1]!.ready).toBe(true);
expect(selected.rows[3]!.differences).toEqual(['costs']);
await f.api.updateBacktest(f.draft.id, {
name: 'Mutable presentation',
initialCapital: 12000,
config: {
datasetHash: f.dataset.manifest.hash,
dataFrequency: '1m',
canonical: { ...canonicalSettings, feeRate: '0.5' },
},
});
await f.review('revoke');
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
f.version.strategyId,
]);
const saved = await f.snapshot();
expect(await f.experiments.compare(p.input)).toEqual(compared);
expect(await f.snapshot()).toEqual(saved);
const response = await request(f, p.input);
expect(response.status).toBe(200);
expect(response.headers.get('Cache-Control')).toBe('no-store');
expect(await response.json()).toEqual({ comparison: compared });
const upperCaseResponse = await request(f, {
leftId: p.left.id.toUpperCase(),
rightId: p.right.id.toUpperCase(),
});
expect(upperCaseResponse.status).toBe(200);
expect(await upperCaseResponse.json()).toEqual({ comparison: compared });
}, 60000);
test('failed/missing/cancelled/inconsistent outcomes remain visible and never replace the unavailable default reference', async () => {
const f = await fixture(),
p = await pair(f);
await f.execute(p.left.trials[1]!.runId!);
await f.execute(p.right.trials[0]!.runId!);
await f.pool.query(
"UPDATE runs SET status='failed',error='Retained fixture failure',completed_at=NOW() WHERE id=$1",
[p.left.trials[0]!.runId]
);
await f.experiments.cancel(p.left.id);
let compared = await f.experiments.compare(p.input);
expect(compared.reference.index).toBe(0);
expect(compared.reference.diagnostic).toBe('Retained fixture failure');
expect(compared.rows.every(r => !r.ready)).toBe(true);
expect(compared.experiments[0].trials.map(t => t.status)).toEqual([
'failed',
'completed',
'cancelled',
]);
expect(compared.rows[1]!.summaryAvailable).toBe(true);
expect(compared.experiments[0].cancelRequested).toBe(true);
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
await f.pool.query(
'UPDATE runs SET experiment_id=NULL,trial_key=NULL,trial_index=NULL WHERE id=$1',
[p.left.trials[0]!.runId]
);
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
compared = await f.experiments.compare(p.input);
expect(compared.reference.runId).toBeNull();
expect(compared.experiments[0].trials[0]!.status).toBe('missing');
expect(compared.rows).toHaveLength(5);
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
await f.pool.query(
"UPDATE backtest_results SET canonical_result=jsonb_set(canonical_result,'{financial,policy,matching,slippageRate}',$2::jsonb) WHERE run_id=$1",
[p.right.trials[0]!.runId, JSON.stringify('0.50000000')]
);
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
compared = await f.experiments.compare(p.input);
expect(compared.rows[3]!.summaryAvailable).toBe(false);
expect(compared.rows[3]!.inputCompatibility).toBe('match');
expect(compared.experiments[1].trials[0]!.diagnostic).toContain('inconsistent');
await expect(
f.experiments.compare({ ...p.input, referenceTrialKey: 'f'.repeat(64) })
).rejects.toMatchObject({ status: 409 });
}, 60000);
test('read-only repeatable snapshot captures both sides before a controlled committed concurrent status change', async () => {
const f = await fixture(4),
p = await pair(f),
trace: string[] = [];
const transaction = f.postgres.transaction.bind(f.postgres);
let changed = false,
mode: unknown;
Object.defineProperty(f.postgres, 'transaction', {
value: (work: (client: PoolClient) => Promise<unknown>) =>
transaction(async client => {
const query = client.query.bind(client);
const proxy = Object.create(client) as PoolClient;
Object.defineProperty(proxy, 'query', {
value: async (sql: string, values?: unknown[]) => {
trace.push(sql);
const result = await query(sql, values);
if (sql.startsWith('SET TRANSACTION')) {
mode = (
await query(
"SELECT current_setting('transaction_isolation') AS isolation,current_setting('transaction_read_only') AS readonly"
)
).rows[0];
}
if (sql.startsWith('SELECT id,validation_phase') && !changed) {
changed = true;
await f.pool.query(
"UPDATE runs SET status='failed',error='Committed after snapshot',completed_at=NOW() WHERE id=$1",
[p.right.trials[0]!.runId]
);
}
return result;
},
});
return work(proxy);
}),
});
const compared = await f.experiments.compare(p.input);
expect(mode).toEqual({ isolation: 'repeatable read', readonly: 'on' });
expect(changed).toBe(true);
expect(trace[0]).toBe('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(compared.experiments[1].counts.pending).toBe(2);
expect(compared.experiments[1].counts.failed).toBe(0);
expect(compared.experiments[1].trials.map(t => t.status)).toEqual(['pending', 'pending']);
expect(compared.rows.every(r => !r.summaryAvailable)).toBe(true);
const fresh = await f.experiments.get(p.right.id);
expect(fresh.counts.failed).toBe(1);
expect(fresh.trials[0]!.error).toBe('Committed after snapshot');
expect(trace.filter(sql => /^(INSERT|UPDATE|DELETE|SELECT .*FOR UPDATE)/i.test(sql))).toEqual(
[]
);
expect(trace.some(sql => /SELECT .*canonical_result\s*(,|FROM)/i.test(sql))).toBe(false);
}, 60000);
test('standalone role, missing identity and retained corruption produce explicit409/404/sanitized500', async () => {
const f = await fixture(),
p = await pair(f),
data = chronologicalDataset();
await retainResearchDataset(f.pool, data.dataset);
const template = await f.cloneTemplate(data.dataset);
const input = {
backtestId: template.id,
name: 'Actual chronological phase',
grid: { fastPeriod: [1, 2], slowPeriod: [3] },
recipe: data.recipe,
},
preview = await f.experiments.previewValidation(input),
validation = await f.validations.submit(
{ ...input, previewHash: preview.previewHash },
actor()
);
expect((await request(f, { leftId: validation.id, rightId: p.right.id })).status).toBe(409);
expect((await request(f, { leftId: randomUUID(), rightId: p.right.id })).status).toBe(404);
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
await f.pool.query(
"UPDATE research_experiments SET preview=jsonb_set(preview,'{previewHash}',to_jsonb(repeat('f',64))) WHERE id=$1",
[p.left.id]
);
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
const response = await request(f, p.input);
expect(response.status).toBe(500);
expect(await response.json()).toEqual({ error: 'Experiment operation unavailable' });
}, 60000);
});