feat(research): reproduce retained canonical runs with economic comparison

This commit is contained in:
Boki 2026-10-24 10:02:21 -04:00
parent e3bd708838
commit 30accfcf43
31 changed files with 2969 additions and 28 deletions

View file

@ -10,7 +10,13 @@ import type {
// Local to this file: no global preload, browser server or second test runner.
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
const globals = ['window', 'document', 'WebSocket', 'IS_REACT_ACT_ENVIRONMENT'] as const;
const globals = [
'window',
'document',
'WebSocket',
'ResizeObserver',
'IS_REACT_ACT_ENVIRONMENT',
] as const;
const savedGlobals = new Map(
globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
);
@ -252,6 +258,7 @@ beforeAll(async () => {
window: browser,
document: browser.document,
WebSocket: TestSocket,
ResizeObserver: browser.ResizeObserver,
IS_REACT_ACT_ENVIRONMENT: true,
}))
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });

View file

@ -0,0 +1,159 @@
import { randomUUID } from 'node:crypto';
import { beforeAll, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { parseFinancialDecimal } from '@stock-bot/types';
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { canonicalReproductionHash } from '../../apps/stock/web-api/src/services/reproduction-comparison';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
let original: CanonicalRunResult;
let reproduced: CanonicalRunResult;
beforeAll(async () => {
const pkg = (await packageBuiltinStrategies())[0]!;
const versionId = randomUUID();
const fixture = canonicalSmaFixture([`strategy:${versionId}`]);
const runId = randomUUID();
fixture.config.matching.risk.ledger.sessionId = runId;
fixture.config.matching.risk.ledger.accountId = `research:${runId}`;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: randomUUID(),
name: 'Comparison fixture',
strategy: {
familyId: randomUUID(),
versionId,
origin: 'builtin',
reviewId: randomUUID(),
package: pkg,
selection: fixture.selections[0],
},
datasetHash: fixture.dataset.manifest.hash,
policy: fixture.config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
// Projection fixtures; admission/build verification is covered by PostgreSQL native tests.
build: {
version: 1,
workerSha256: 'a'.repeat(64),
engineWrapperSha256: 'b'.repeat(64),
engineBinarySha256: 'c'.repeat(64),
dependencyLockSha256: 'd'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'fixture',
arch: 'fixture',
},
modelArtifacts: [],
});
const execute = (input: typeof request): CanonicalRunResult => {
const financial = runStrategyReplay(
prepareReplayLoad(fixture.dataset, input.policy),
[createBuiltinStrategy(input.strategy.selection)],
{ resultFormat: 'report' }
).result;
const report = buildCanonicalBacktestReport(financial, input.analyticsPolicy);
return {
kind: 'canonical-result/v1',
runId: input.runId,
backtestId: input.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: 1,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request: input,
...report,
};
};
original = execute(request);
const next = structuredClone(request);
next.runId = randomUUID();
next.policy.matching.risk.ledger.sessionId = next.runId;
next.policy.matching.risk.ledger.accountId = `research:${next.runId}`;
next.strategy.reviewId = randomUUID();
reproduced = execute(next);
});
test('economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata', () => {
expect(original.runId).not.toBe(reproduced.runId);
expect(original.request.strategy.reviewId).not.toBe(reproduced.request.strategy.reviewId);
expect(original.financial.projection.fills).toHaveLength(2);
expect(original.financial.projection.fills).toEqual(reproduced.financial.projection.fills);
const before = JSON.stringify([original, reproduced]);
expect(canonicalReproductionHash(original)).toMatch(/^[a-f0-9]{64}$/);
expect(canonicalReproductionHash(original)).toBe(canonicalReproductionHash(reproduced));
expect(JSON.stringify([original, reproduced])).toBe(before);
});
test('economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts', () => {
const changes: ((value: CanonicalRunResult) => void)[] = [
value => {
value.financial.projection.valuation.fees = parseFinancialDecimal('9');
},
value => {
value.financial.projection.fills[0]!.fee.amount = parseFinancialDecimal('0.51');
},
value => {
value.financial.projection.fills[0]!.price = parseFinancialDecimal('5.1');
},
value => {
value.financial.projection.fills.reverse();
},
value => {
value.financial.projection.fills[0]!.orderId = 'different-order';
},
value => {
value.financial.projection.fills[0]!.ownerId = 'different-owner';
value.financial.projection.fills[0]!.decision.ownerId = 'different-owner';
},
value => {
value.financial.view.risk.dailyHalted = !value.financial.view.risk.dailyHalted;
},
value => {
value.analytics.metrics.sharpeRatio = 0;
},
value => {
value.analytics.metrics.totalReturn = 0;
},
value => {
value.financial.modelLimitations.push('Additional model limitation');
},
value => {
value.request.strategy.selection.seed++;
},
];
for (const change of changes) {
const changed = structuredClone(original);
change(changed);
expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original));
}
});
test('economic hash preserves actual market-session identities and execution policy', () => {
const changed = structuredClone(original);
changed.financial.view.risk.riskSession.sessionId = 'different-market-session';
expect(canonicalReproductionHash(changed)).not.toBe(canonicalReproductionHash(original));
const policy = structuredClone(original);
policy.request.policy.matching.risk.feeRate = parseFinancialDecimal('0.02');
policy.financial.policy.matching.risk.feeRate = parseFinancialDecimal('0.02');
expect(canonicalReproductionHash(policy)).not.toBe(canonicalReproductionHash(original));
});
test('economic hash rejects mixed result/request/session identities rather than hiding them', () => {
const wrongRun = structuredClone(original);
wrongRun.runId = randomUUID();
expect(() => canonicalReproductionHash(wrongRun)).toThrow('identity');
const wrongSession = structuredClone(original);
wrongSession.financial.identity.sessionId = randomUUID();
expect(() => canonicalReproductionHash(wrongSession)).toThrow();
const wrongAccount = structuredClone(original);
wrongAccount.financial.view.portfolio.accountId = 'foreign-account';
expect(() => canonicalReproductionHash(wrongAccount)).toThrow();
});

View file

@ -0,0 +1,186 @@
import { createHash, 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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
const tokens = {
operator: 'reproduction-admin-fixture-not-a-real-secret-1234',
service: 'reproduction-service-fixture-not-a-real-secret-1234',
read: 'reproduction-read-fixture-not-a-real-secret-1234',
};
const originalRunId = randomUUID();
const runId = randomUUID();
const backtestId = randomUUID();
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>): 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('/', createBacktestV2Routes({ postgres: database } as unknown as IServiceContainer));
return {
database,
request(path: string, method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
return app.request(`/api/v2/runs/${path}`, {
method,
headers: {
'Content-Type': 'application/json',
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
...(key !== undefined ? { 'Idempotency-Key': key } : {}),
},
...(body === undefined ? {} : { body }),
});
},
};
}
function row(extra: Record<string, unknown> = {}) {
return {
id: runId,
backtest_id: backtestId,
original_run_id: originalRunId,
run_number: 2,
status: 'pending',
speed_multiplier: null,
progress: '0',
attempt_number: 0,
created_at: '2026-10-24T00:00:00Z',
updated_at: '2026-10-24T00:00:00Z',
...extra,
};
}
describe('original reproduction HTTP contract', () => {
test('mutation requires credential proof even with development bypass or forged actor', async () => {
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
const f = fixture(mode);
const response = await f.request(
`${originalRunId}/reproduce?actor=operator`,
'POST',
'{}',
undefined,
'receipt'
);
expect(response.status).toBe(401);
expect(f.database.query.mock.calls).toHaveLength(0);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
});
test('read-only role may inspect but cannot submit and anonymous reads reject', async () => {
const f = fixture();
expect((await f.request(`${runId}/reproduction`)).status).toBe(401);
expect((await f.request(`${runId}/reproduction-comparison`)).status).toBe(401);
expect((await f.request(`${runId}/reproduce`, 'POST', '{}', 'read', 'key')).status).toBe(403);
expect((await f.request(`${runId}/reproduction`, 'GET', undefined, 'read')).status).toBe(404);
});
test('strict original-run IDs, body and required keys reject financial overrides before storage', async () => {
for (const [id, body, key] of [
[originalRunId, '{}', undefined],
[originalRunId, '{}', 'contains space'],
[originalRunId, '{}', 'x'.repeat(201)],
[originalRunId, '{', 'key'],
[originalRunId, 'null', 'key'],
[originalRunId, '[]', 'key'],
[originalRunId, '{"feeRate":"0"}', 'key'],
[originalRunId, '{"originalRunId":"other"}', 'key'],
['not-uuid', '{}', 'key'],
]) {
const f = fixture();
expect((await f.request(`${id}/reproduce`, 'POST', body, 'operator', key)).status).toBe(400);
expect(f.database.query.mock.calls).toHaveLength(0);
expect(f.database.transaction.mock.calls).toHaveLength(0);
}
const f = fixture();
expect((await f.request('bad/reproduction', 'GET', undefined, 'read')).status).toBe(400);
expect((await f.request('bad/reproduction-comparison', 'GET', undefined, 'read')).status).toBe(
400
);
});
test('an accepted receipt returns its original run and Location before eligibility checks', async () => {
const key = 'already-admitted';
const hash = createHash('sha256')
.update(JSON.stringify({ version: 1, operation: 'reproduce-original', originalRunId }))
.digest('hex');
for (const principal of ['operator', 'service'] as const) {
const f = fixture('enabled', async (sql, values) => {
expect(sql).toContain('submission_principal=$1');
expect(values).toEqual([principal, key]);
return { rows: [row({ submission_hash: hash })] };
});
const reply = await f.request(`${originalRunId}/reproduce`, 'POST', '{}', principal, key);
expect(reply.status).toBe(202);
expect(reply.headers.get('Location')).toBe(`/api/v2/runs/${runId}`);
expect(reply.headers.get('Cache-Control')).toBe('no-store');
expect(await reply.json()).toMatchObject({ id: runId, originalRunId, backtestId });
expect(f.database.query.mock.calls).toHaveLength(1);
}
});
test('receipt intent conflict is409, missing source404, incomplete preview is unavailable', async () => {
const conflict = fixture('enabled', async () => ({
rows: [row({ submission_hash: 'different' })],
}));
expect(
(await conflict.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status
).toBe(409);
const missing = fixture();
expect(
(await missing.request(`${originalRunId}/reproduce`, 'POST', '{}', 'operator', 'key')).status
).toBe(404);
const pending = fixture('enabled', async () => ({ rows: [row()] }));
const preview = await pending.request(`${runId}/reproduction`, 'GET', undefined, 'read');
expect(preview.status).toBe(200);
expect(await preview.json()).toMatchObject({
originalRunId: runId,
backtestId,
available: false,
request: null,
});
const compare = await pending.request(
`${runId}/reproduction-comparison`,
'GET',
undefined,
'read'
);
expect(await compare.json()).toMatchObject({
runId,
originalRunId,
status: 'pending',
originalHash: null,
});
});
test('unexpected database and retained schema failures remain sanitized500, never input400 or available', async () => {
for (const failure of [new Error('private connection info'), new z.ZodError([])]) {
const f = fixture('enabled', async () => {
throw failure;
});
for (const [path, method, body, key] of [
[`${runId}/reproduction`, 'GET', undefined, undefined],
[`${runId}/reproduction-comparison`, 'GET', undefined, undefined],
[`${runId}/reproduce`, 'POST', '{}', 'key'],
] as const) {
const response = await f.request(path, method, body, 'operator', key);
expect(response.status).toBe(500);
expect(await response.text()).not.toContain('private connection');
}
}
});
});

View file

@ -0,0 +1,558 @@
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,
type CanonicalReproductionComparison,
type CanonicalReproductionPreview,
} from '@stock-bot/stock-config/canonical-research';
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
import type { Run } 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 RunReproduction: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunReproduction').RunReproduction;
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
let root: Root | undefined;
let host: HTMLDivElement;
let navigate: ReturnType<typeof router.useNavigate>;
let location = '';
const sourceId = '11111111-1111-4111-8111-111111111111';
const otherId = '22222222-2222-4222-8222-222222222222';
const backtestId = '33333333-3333-4333-8333-333333333333';
const versionId = '44444444-4444-4444-8444-444444444444';
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;
headers: Headers;
settled: boolean;
signal?: AbortSignal | null;
};
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 item = [...host.querySelectorAll('button')].find(
item => item.textContent?.trim() === label
);
if (!item) {
throw new Error(`Missing ${label}: ${host.textContent}`);
}
return item;
}
function Probe() {
navigate = router.useNavigate();
location = router.useLocation().pathname;
return null;
}
async function render(element: ReactElement, path = `/backtests/${backtestId}/run/${sourceId}`) {
root ??= createRoot(host);
await flush(() =>
root!.render(
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
)
);
}
const run = (id = sourceId, extra: Partial<Run> = {}): Run => ({
id,
backtestId,
runNumber: 1,
status: 'completed',
speedMultiplier: null,
progress: 100,
createdAt: '2026-10-24',
updatedAt: '2026-10-24',
originalRunId: null,
...extra,
});
function preview(
id = sourceId,
extra: Partial<CanonicalReproductionPreview> = {}
): CanonicalReproductionPreview {
const owner = `strategy:${versionId}`;
const { config, dataset } = nativeReplayFixture(3, 1, [owner]);
config.matching.risk.ledger.sessionId = id;
config.matching.risk.ledger.accountId = `research:${id}`;
const builtin = builtinCatalogDescriptors[0]!;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId: id,
backtestId,
name: 'Frozen original inputs',
strategy: {
familyId: '55555555-5555-4555-8555-555555555555',
versionId,
origin: 'builtin',
reviewId: '66666666-6666-4666-8666-666666666666',
package: {
version: 1,
program: builtin.program,
parameterSchema: builtin.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: builtin.entryExport,
content: 'Never execute this 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: 3 },
},
},
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: [],
});
return {
originalRunId: id,
backtestId,
available: true,
reason: null,
currentReviewId: '77777777-7777-4777-8777-777777777777',
request,
...extra,
};
}
const comparison = (
status: CanonicalReproductionComparison['status'] = 'match'
): CanonicalReproductionComparison => ({
version: 'canonical-reproduction/v1',
runId: otherId,
backtestId,
originalRunId: sourceId,
status,
reason: null,
originalHash: ['match', 'mismatch'].includes(status) ? 'a'.repeat(64) : null,
reproducedHash:
status === 'match' ? 'a'.repeat(64) : status === 'mismatch' ? 'b'.repeat(64) : null,
});
async function open(source = run(), archived = false) {
await render(createElement(RunReproduction, { run: source, archived }));
await flush(() => button('Reproduce original').click());
}
async function ready(source = run(), archived = false) {
await open(source, archived);
const value = preview(source.id);
await flush(() => reply(request(`/api/v2/runs/${source.id}/reproduction`), value));
return value;
}
const post = () => request(`/api/v2/runs/${sourceId}/reproduce`, 'POST');
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');
({ RunReproduction } = await import(
'../../apps/stock/web-app/src/features/backtest/components/RunReproduction'
));
({ BacktestDetailPageV2 } = await import(
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
));
});
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',
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
headers: new Headers(init?.headers),
signal: init?.signal,
settled: false,
};
requests.push(item);
return item.promise; // Ignore abort deliberately; component identity must fence late replies.
},
});
});
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('original-run reproduction UI', () => {
test('preview is read-only, renders exact retained inputs, and double-click admission sends only source/key', async () => {
const value = await ready();
expect(host.textContent).toContain('Frozen original inputs');
expect(host.textContent).toContain(value.request!.datasetHash);
expect(host.textContent).toContain(versionId);
expect(host.textContent).toContain('Random seed: 17');
expect(host.querySelector('pre')?.textContent).toContain('"fastPeriod": 2');
expect(host.querySelector('pre')?.textContent).toContain(
value.request!.build.engineBinarySha256
);
expect(host.querySelector('pre')?.textContent).not.toContain('Never execute this code');
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
const submit = button('Confirm reproduction');
await flush(() => {
submit.click();
submit.click();
});
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
expect(post().body).toEqual({});
expect(post().headers.get('Idempotency-Key')).toMatch(/^[a-f0-9-]{36}$/);
await flush(() =>
reply(post(), run(otherId, { originalRunId: sourceId, status: 'pending' }), 202)
);
expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`);
});
test('loading and failed preview do not become unavailable provenance and read retry does not submit', async () => {
await open();
expect(host.textContent).toContain('Loading original inputs...');
expect(button('Confirm reproduction').disabled).toBe(true);
await flush(() =>
reply(request(`/api/v2/runs/${sourceId}/reproduction`), { error: 'Store offline' }, 503)
);
expect(host.textContent).toContain('Store offline');
expect(host.textContent).not.toContain('Original reproduction unavailable');
await flush(() => button('Refresh original inputs').click());
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview()));
expect(button('Confirm reproduction').disabled).toBe(false);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
});
test.each([
'Legacy run lacks retained provenance',
'Original strategy approval was revoked',
'Installed build is unsupported',
])('%s displays an explicit unavailable reason with no fallback', async reason => {
await open();
await flush(() =>
reply(
request(`/api/v2/runs/${sourceId}/reproduction`),
preview(sourceId, { available: false, reason, request: null, currentReviewId: null })
)
);
expect(host.textContent).toContain(reason);
expect(button('Confirm reproduction').disabled).toBe(true);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
});
test('an archived parent blocks fresh admission even if a stale preview says available', async () => {
await ready(run(), true);
expect(host.textContent).toContain('This backtest is archived');
expect(button('Confirm reproduction').disabled).toBe(true);
});
test.each(['lost', 'malformed', 'wrong-parent', 'server-error'])(
'%s response retains the key across close, refresh, archive and explicit retry',
async failure => {
await ready();
await flush(() => button('Confirm reproduction').click());
const first = post();
const key = first.headers.get('Idempotency-Key');
await flush(() => {
if (failure === 'lost') {
first.settled = true;
first.reject(new Error('Lost'));
} else if (failure === 'malformed') {
reply(first, {}, 202);
} else if (failure === 'wrong-parent') {
reply(first, run(otherId, { originalRunId: sourceId, backtestId: 'wrong' }), 202);
} else {
reply(first, { error: 'Response unavailable' }, 500);
}
});
expect(host.textContent).toContain('previous request may already have been accepted');
await flush(() => button('Close').click());
await render(createElement(RunReproduction, { run: run(), archived: true }));
await flush(() => button('Reproduce original').click());
await flush(() =>
reply(
request(`/api/v2/runs/${sourceId}/reproduction`),
preview(sourceId, { available: false, reason: 'Archived', currentReviewId: null })
)
);
expect(button('Retry reproduction').disabled).toBe(false);
await flush(() => button('Retry reproduction').click());
expect(post().headers.get('Idempotency-Key')).toBe(key);
expect(post().body).toEqual({});
await flush(() => reply(post(), run(otherId, { originalRunId: sourceId }), 202));
expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`);
}
);
test.each([400, 401, 404, 409])(
'HTTP %s never automatically retries or changes the receipt',
async status => {
await ready();
await flush(() => button('Confirm reproduction').click());
const first = post();
const key = first.headers.get('Idempotency-Key');
await flush(() => reply(first, { error: `Definite rejection ${status}` }, status));
expect(host.textContent).toContain(`Definite rejection ${status}`);
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
await flush(() => button('Retry reproduction').click());
expect(post().headers.get('Idempotency-Key')).toBe(key);
}
);
test('a new receipt requires deliberate confirmation and fresh eligible preview', async () => {
await ready();
await flush(() => button('Confirm reproduction').click());
const first = post();
await flush(() => reply(first, { error: 'Conflict' }, 409));
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
await flush(() => button('Start new reproduction').click());
expect(button('Retry reproduction')).toBeTruthy();
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
await flush(() => button('Start new reproduction').click());
expect(button('Confirm reproduction').disabled).toBe(true);
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview()));
await flush(() => button('Confirm reproduction').click());
expect(post().headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
});
test('source and parent mismatched preview fails closed', async () => {
await open();
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview(otherId)));
expect(button('Confirm reproduction').disabled).toBe(true);
expect(host.textContent).toContain('could not be verified');
await flush(() => button('Refresh original inputs').click());
const wrong = preview();
wrong.backtestId = otherId;
wrong.request!.backtestId = otherId;
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), wrong));
expect(host.textContent).toContain('different run or backtest');
expect(button('Confirm reproduction').disabled).toBe(true);
});
test('late preview and late accepted mutation cannot navigate or overwrite a new selection', async () => {
await open();
const oldPreview = request(`/api/v2/runs/${sourceId}/reproduction`);
await render(createElement(RunReproduction, { run: run(otherId), archived: false }));
await flush(() => reply(oldPreview, preview()));
expect(host.querySelector('[role="dialog"]')).toBeNull();
await ready();
await flush(() => button('Confirm reproduction').click());
const oldPost = post();
await render(createElement(RunReproduction, { run: run(otherId), archived: false }));
await flush(() => navigate(`/backtests/${backtestId}/run/${otherId}`));
await flush(() => reply(oldPost, run('accepted-late', { originalRunId: sourceId }), 202));
expect(location).toBe(`/backtests/${backtestId}/run/${otherId}`);
expect(host.querySelector('[role="dialog"]')).toBeNull();
});
test.each(['match', 'mismatch', 'pending', 'unavailable'] as const)(
'saved reproduction displays server %s, exact source lineage and no invented result',
async status => {
await render(
createElement(RunReproduction, {
run: run(otherId, { originalRunId: sourceId }),
archived: false,
})
);
expect(host.textContent).toContain('Loading reproduction comparison');
const link = host.querySelector('a');
expect(link?.getAttribute('href')).toBe(`/backtests/${backtestId}/run/${sourceId}`);
const value = comparison(status);
if (status === 'unavailable') {
value.reason = 'No completed saved result';
}
await flush(() => reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), value));
expect(host.textContent).toContain(
{
match: 'Economic results match the original.',
mismatch: 'Economic results differ from the original.',
pending: 'Reproduction comparison pending completion.',
unavailable: 'Reproduction comparison unavailable.',
}[status]
);
if (value.originalHash) {
expect(host.textContent).toContain(value.originalHash);
}
if (status === 'unavailable') {
expect(host.textContent).toContain(value.reason!);
}
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
}
);
test('comparison errors, malformed matches and foreign sources cannot display a successful match', async () => {
await render(
createElement(RunReproduction, {
run: run(otherId, { originalRunId: sourceId }),
archived: false,
})
);
await flush(() =>
reply(
request(`/api/v2/runs/${otherId}/reproduction-comparison`),
{ error: 'Unavailable store' },
503
)
);
expect(host.textContent).toContain('Unavailable store');
expect(host.textContent).not.toContain('Economic results match');
await flush(() => button('Refresh comparison').click());
await flush(() =>
reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), {
...comparison(),
originalHash: null,
})
);
expect(host.textContent).toContain('could not be verified');
await flush(() => button('Refresh comparison').click());
await flush(() =>
reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), {
...comparison(),
reproducedHash: 'b'.repeat(64),
})
);
expect(host.textContent).toContain('could not be verified');
await flush(() => button('Refresh comparison').click());
await flush(() =>
reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), {
...comparison(),
originalRunId: 'foreign',
})
);
expect(host.textContent).toContain('does not match');
expect(host.textContent).not.toContain('Economic results match');
});
test('status changes invalidate late comparisons and request committed completion', async () => {
await render(
createElement(RunReproduction, {
run: run(otherId, { originalRunId: sourceId, status: 'running' }),
archived: false,
})
);
const old = request(`/api/v2/runs/${otherId}/reproduction-comparison`);
old.settled = true;
await render(
createElement(RunReproduction, {
run: run(otherId, { originalRunId: sourceId }),
archived: false,
})
);
await flush(() =>
reply(request(`/api/v2/runs/${otherId}/reproduction-comparison`), comparison())
);
await flush(() => old.resolve(Response.json(comparison('pending'))));
expect(host.textContent).toContain('Economic results match the original.');
expect(host.textContent).not.toContain('pending completion');
});
test('parent uses original preview even when current catalog configuration cannot execute', async () => {
await render(
createElement(
router.Routes,
null,
createElement(router.Route, {
path: '/backtests/:id/run/:runId',
element: createElement(BacktestDetailPageV2),
})
)
);
await flush(() => {
reply(request(`/api/v2/backtests/${backtestId}`), {
id: backtestId,
name: 'Different current setup',
strategy: 'catalog',
strategyVersionId: 'different-version',
strategyParameters: {},
symbols: ['OTHER'],
startDate: '2024-01-01',
endDate: '2024-01-02',
initialCapital: 20000,
config: {},
archivedAt: null,
createdAt: '2024-01-01',
updatedAt: '2024-01-01',
});
reply(request(`/api/v2/backtests/${backtestId}/runs`), [run()]);
});
await flush(() => {
reply(request(`/api/v2/backtests/${backtestId}/canonical-capability`), {
available: false,
reason: 'Current version unavailable',
});
reply(request(`/api/v2/runs/${sourceId}`), run());
});
await flush(() =>
reply(request(`/api/v2/runs/${sourceId}/results`), { error: 'Missing display result' }, 404)
);
expect(host.textContent).toContain('Current version unavailable');
expect(host.textContent).toContain('Run current settings');
expect(button('Reproduce original').disabled).toBe(false);
await flush(() => button('Reproduce original').click());
await flush(() => reply(request(`/api/v2/runs/${sourceId}/reproduction`), preview()));
expect(button('Confirm reproduction').disabled).toBe(false);
expect(host.textContent).toContain('Frozen original inputs');
});
});