feat(research): reproduce retained canonical runs with economic comparison
This commit is contained in:
parent
e3bd708838
commit
30accfcf43
31 changed files with 2969 additions and 28 deletions
|
|
@ -292,6 +292,7 @@ export async function fixture(browser: Browser, native = false) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -1049,6 +1049,114 @@ test('research_project_to_finding_browser_with_canonical_strategy_setup_run_and_
|
|||
await f.page.waitForURL(completedUrl);
|
||||
await visible(f.page, '9969.30000000');
|
||||
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
|
||||
|
||||
// Original reproduction is independent of subsequent mutable template edits.
|
||||
await f.request(`/api/v2/backtests/${backtestId}`, 'PUT', {
|
||||
name: 'Changed current settings',
|
||||
initialCapital: 20000,
|
||||
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
|
||||
config: { ...sent.config, canonical: { ...sent.config.canonical, feeRate: '0.02', seed: 7 } },
|
||||
});
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
await f.page.getByRole('button', { name: 'Reproduce original', exact: true }).click();
|
||||
const reproductionDialog = f.page.getByRole('dialog', {
|
||||
name: 'Reproduce original',
|
||||
exact: true,
|
||||
});
|
||||
const originalInputs = reproductionDialog.getByRole('region', {
|
||||
name: 'Original retained inputs',
|
||||
exact: true,
|
||||
});
|
||||
await originalInputs.waitFor({ state: 'visible' });
|
||||
expect(await originalInputs.textContent()).toContain(retained.hash);
|
||||
expect(await originalInputs.textContent()).toContain(selected.id);
|
||||
await reproductionDialog
|
||||
.getByText('Exact parameters, financial policies and build', { exact: true })
|
||||
.click();
|
||||
expect(await originalInputs.locator('pre').textContent()).toContain(
|
||||
'"initialCapital": "10000.00000000"'
|
||||
);
|
||||
expect(await originalInputs.locator('pre').textContent()).toContain('"fastPeriod": 2');
|
||||
const reproducing = f.page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
response.url().endsWith(`/runs/${run.id}/reproduce`)
|
||||
);
|
||||
await reproductionDialog
|
||||
.getByRole('button', { name: 'Confirm reproduction', exact: true })
|
||||
.click();
|
||||
const reproducedResponse = await reproducing;
|
||||
expect(reproducedResponse.status()).toBe(202);
|
||||
expect(reproducedResponse.request().headers()['idempotency-key']).toBeTruthy();
|
||||
expect(reproducedResponse.request().postDataJSON()).toEqual({});
|
||||
const reproducedRun = await reproducedResponse.json();
|
||||
expect(reproducedRun.originalRunId).toBe(run.id);
|
||||
expect(reproducedRun.id).not.toBe(run.id);
|
||||
expect(reproducedResponse.headers().location).toBe(`/api/v2/runs/${reproducedRun.id}`);
|
||||
await f.page.waitForURL(`${f.origin}/backtests/${backtestId}/run/${reproducedRun.id}`);
|
||||
const duplicate = await f.page.evaluate(
|
||||
async ({ sourceId, key }) => {
|
||||
const response = await fetch(`/api/v2/runs/${sourceId}/reproduce`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key },
|
||||
body: '{}',
|
||||
});
|
||||
return { status: response.status, run: await response.json() };
|
||||
},
|
||||
{ sourceId: run.id, key: reproducedResponse.request().headers()['idempotency-key']! }
|
||||
);
|
||||
expect(duplicate.status).toBe(202);
|
||||
expect(duplicate.run.id).toBe(reproducedRun.id);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
await visible(f.page, 'Economic results match the original.');
|
||||
const comparison = await f.request(`/api/v2/runs/${reproducedRun.id}/reproduction-comparison`);
|
||||
expect(comparison.status).toBe('match');
|
||||
expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(comparison.reproducedHash).toBe(comparison.originalHash);
|
||||
const reproducedResult = (await f.request(
|
||||
`/api/v2/runs/${reproducedRun.id}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(reproducedResult.request.strategy.selection).toEqual(result.request.strategy.selection);
|
||||
expect(reproducedResult.request.build).toEqual(result.request.build);
|
||||
expect(reproducedResult.request.datasetHash).toBe(result.request.datasetHash);
|
||||
expect(String(reproducedResult.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'10000.00000000'
|
||||
);
|
||||
expect(reproducedResult.financial.projection).toEqual(result.financial.projection);
|
||||
expect(reproducedResult.analytics).toEqual(result.analytics);
|
||||
await f.page.reload();
|
||||
await visible(f.page, 'Economic results match the original.');
|
||||
await f.page.getByRole('link', { name: 'Open original run', exact: true }).click();
|
||||
await f.page.waitForURL(completedUrl);
|
||||
await visible(f.page, '9969.30000000');
|
||||
|
||||
// Ordinary submission still freezes the current settings and has no reproduction lineage.
|
||||
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
||||
const currentResponse = await submitInBrowser(f.page);
|
||||
expect(currentResponse.status()).toBe(202);
|
||||
const currentRun = await currentResponse.json();
|
||||
expect(currentRun.originalRunId).toBeNull();
|
||||
await visible(f.page, 'Canonical research result');
|
||||
const currentResult = (await f.request(
|
||||
`/api/v2/runs/${currentRun.id}/results`
|
||||
)) as CanonicalRunResult;
|
||||
expect(String(currentResult.request.policy.matching.risk.ledger.initialCapital)).toBe(
|
||||
'20000.00000000'
|
||||
);
|
||||
expect(currentResult.request.strategy.selection.parameters).toEqual({
|
||||
fastPeriod: 1,
|
||||
slowPeriod: 2,
|
||||
});
|
||||
expect(currentResult.request.strategy.selection.seed).toBe(7);
|
||||
expect(String(currentResult.request.policy.matching.risk.feeRate)).toBe('0.02000000');
|
||||
expect(await f.request(`/api/v2/runs/${run.id}/results`)).toEqual(result);
|
||||
expect(
|
||||
(await f.pool.query('SELECT original_run_id FROM runs WHERE id=$1', [reproducedRun.id]))
|
||||
.rows[0].original_run_id
|
||||
).toBe(run.id);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(3);
|
||||
expect(f.historicalDataReads).toEqual([]);
|
||||
expect(f.unexpectedNetwork).toEqual([]);
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
|
|
|
|||
159
test/integration/reproduction-comparison.test.ts
Normal file
159
test/integration/reproduction-comparison.test.ts
Normal 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();
|
||||
});
|
||||
186
test/integration/run-reproduction-api.test.ts
Normal file
186
test/integration/run-reproduction-api.test.ts
Normal 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');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
558
test/integration/run-reproduction-ui.test.tsx
Normal file
558
test/integration/run-reproduction-ui.test.tsx
Normal 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');
|
||||
});
|
||||
});
|
||||
|
|
@ -62,6 +62,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -100,6 +100,7 @@ async function fixture() {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ async function fixture() {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -84,6 +84,7 @@ async function fixture() {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ const migrations = [
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -24,7 +24,9 @@ const retention =
|
|||
'\n' +
|
||||
sql('18-backtest-strategy-versions.sql') +
|
||||
'\n' +
|
||||
sql('19-canonical-research.sql');
|
||||
sql('19-canonical-research.sql') +
|
||||
'\n' +
|
||||
sql('21-run-reproduction.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -69,6 +69,7 @@ async function fixture() {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
602
test/postgres/run-reproduction.test.ts
Normal file
602
test/postgres/run-reproduction.test.ts
Normal file
|
|
@ -0,0 +1,602 @@
|
|||
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 { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
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 { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.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';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('run-reproduction');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 4, withReproduction = true) {
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_reproduce_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
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',
|
||||
...(withReproduction ? ['21-run-reproduction.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 };
|
||||
const api = new BacktestServiceV2(container);
|
||||
const catalog = new StrategyCatalogService(container);
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical API',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(s => s.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 draft = await api.createBacktest(definition, { autoStart: false });
|
||||
const approve = async () => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained builtin' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Canonical execution must never load provider data');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
schema,
|
||||
api,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
app: new Hono().route('/', createBacktestV2Routes(container)),
|
||||
};
|
||||
}
|
||||
|
||||
const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
async function completed(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
await f.approve();
|
||||
const run = await f.api.createRun({ backtestId: f.draft.id });
|
||||
await f.execute(run.id);
|
||||
const result = await f.api.getRunResults(run.id);
|
||||
if (!result || !('kind' in result)) {
|
||||
throw new Error('Expected real canonical result');
|
||||
}
|
||||
return { run, result };
|
||||
}
|
||||
function copied(request: CanonicalRunRequest, id: string, reviewId = request.strategy.reviewId) {
|
||||
const snapshot = structuredClone(request);
|
||||
snapshot.runId = id;
|
||||
snapshot.policy.matching.risk.ledger.sessionId = id;
|
||||
snapshot.policy.matching.risk.ledger.accountId = `research:${id}`;
|
||||
snapshot.strategy.reviewId = reviewId;
|
||||
return snapshot;
|
||||
}
|
||||
async function insertCopy(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
sourceId: string,
|
||||
snapshot: CanonicalRunRequest,
|
||||
parent = f.draft.id
|
||||
) {
|
||||
return f.pool.query(
|
||||
`INSERT INTO runs
|
||||
(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,original_run_id,
|
||||
submission_principal,submission_key,submission_hash)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending',NULL,$3,$4,$5,'operator',$6,$7
|
||||
FROM runs WHERE backtest_id=$2 RETURNING *`,
|
||||
[snapshot.runId, parent, snapshot, snapshot.datasetHash, sourceId, randomUUID(), 'a'.repeat(64)]
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('retained original-run reproduction', () => {
|
||||
test('reproduce_after_template_provider_change: original executable/input identities and economic_hash_parity survive another selected version', async () => {
|
||||
const f = await fixture(1);
|
||||
const { run, result } = await completed(f);
|
||||
const originalRows = (
|
||||
await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])
|
||||
).rows;
|
||||
const otherPackage = (await (packages ??= packageBuiltinStrategies()))[1]!;
|
||||
const otherVersion = await f.catalog.seedBuiltin(
|
||||
'Other current template',
|
||||
otherPackage,
|
||||
'other'
|
||||
);
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
name: 'New template name',
|
||||
strategyVersionId: otherVersion.id,
|
||||
strategyParameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.1,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
initialCapital: 12000,
|
||||
config: { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '0.02' } },
|
||||
});
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'Require new review' },
|
||||
'operator'
|
||||
);
|
||||
const approval = await f.approve();
|
||||
expect(approval.id).not.toBe(result.request.strategy.reviewId);
|
||||
const preview = await f.api.getReproductionPreview(run.id);
|
||||
expect(preview.available).toBe(true);
|
||||
expect(preview.request).toEqual(result.request);
|
||||
expect(preview.currentReviewId).toBe(approval.id);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
const key = receipt();
|
||||
const reproduced = await f.api.reproduceRun(run.id, key);
|
||||
expect(reproduced.originalRunId).toBe(run.id);
|
||||
expect(reproduced.id).not.toBe(run.id);
|
||||
expect(reproduced.backtestId).toBe(run.backtestId);
|
||||
expect((await f.api.getReproductionComparison(reproduced.id)).status).toBe('pending');
|
||||
const admitted = (
|
||||
await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [reproduced.id])
|
||||
).rows[0].request_snapshot;
|
||||
expect(admitted).toEqual(copied(result.request, reproduced.id, approval.id));
|
||||
// Storage is a provider-read failure fixture; both jobs must use the retained bytes.
|
||||
await f.execute(reproduced.id);
|
||||
const repeated = (await f.api.getRunResults(reproduced.id)) as CanonicalRunResult;
|
||||
expect(String(repeated.financial.projection.valuation.equity)).toBe('9969.30000000');
|
||||
expect(String(repeated.financial.projection.valuation.fees)).toBe('0.70000000');
|
||||
expect(repeated.financial.projection.fills).toEqual(result.financial.projection.fills);
|
||||
const comparison = await f.api.getReproductionComparison(reproduced.id);
|
||||
expect(comparison.status).toBe('match');
|
||||
expect(comparison.originalHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(comparison.reproducedHash).toBe(comparison.originalHash);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])).rows
|
||||
).toEqual(originalRows);
|
||||
expect((await f.api.getBacktest(f.draft.id))?.strategyVersionId).toBe(otherVersion.id);
|
||||
expect((await f.api.getReproductionComparison(run.id)).status).toBe('not-reproduction');
|
||||
// Accepted receipts survive later eligibility changes; no second dispatch is admitted.
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'No new work' },
|
||||
'operator'
|
||||
);
|
||||
await f.catalog.updateStrategy(f.version.strategyId, { archived: true }, 'operator');
|
||||
await f.api.archiveBacktest(f.draft.id, true);
|
||||
expect((await f.api.reproduceRun(run.id, key)).id).toBe(reproduced.id);
|
||||
expect((await f.api.getReproductionPreview(run.id)).available).toBe(false);
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('archived');
|
||||
await f.api.archiveBacktest(f.draft.id, false);
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('family is archived');
|
||||
await f.catalog.updateStrategy(f.version.strategyId, { archived: false }, 'operator');
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow(
|
||||
'current operator approval'
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2);
|
||||
});
|
||||
|
||||
test('comparison reports economic differences without tolerances or rewriting the original', async () => {
|
||||
const f = await fixture();
|
||||
const { run, result } = await completed(f);
|
||||
const copy = await f.api.reproduceRun(run.id, receipt());
|
||||
await f.execute(copy.id);
|
||||
const first = await f.api.getReproductionComparison(copy.id);
|
||||
expect(first.status).toBe('match');
|
||||
const changed = structuredClone(await f.api.getRunResults(copy.id)) as CanonicalRunResult;
|
||||
changed.financial.view.risk.dailyHalted = !changed.financial.view.risk.dailyHalted;
|
||||
// Simulate divergent valid financial diagnostics in this disposable result only.
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [
|
||||
changed,
|
||||
copy.id,
|
||||
]);
|
||||
const mismatch = await f.api.getReproductionComparison(copy.id);
|
||||
expect(mismatch.status).toBe('mismatch');
|
||||
expect(mismatch.originalHash).toBe(first.originalHash);
|
||||
expect(mismatch.reproducedHash).not.toBe(mismatch.originalHash);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
});
|
||||
|
||||
test('concurrent duplicate receipts are one run/outbox and operations or original identities never alias', async () => {
|
||||
const f = await fixture();
|
||||
const { run } = await completed(f);
|
||||
const key = receipt('simultaneous');
|
||||
const copies = await Promise.all(
|
||||
Array.from({ length: 5 }, () => f.api.reproduceRun(run.id, key))
|
||||
);
|
||||
expect(new Set(copies.map(copy => copy.id)).size).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(2);
|
||||
await expect(f.api.createRun({ backtestId: f.draft.id }, key)).rejects.toThrow(
|
||||
'different run request'
|
||||
);
|
||||
await expect(f.api.reproduceRun(randomUUID(), key)).rejects.toThrow('different run request');
|
||||
const ordinaryKey = receipt('ordinary');
|
||||
await f.api.createRun({ backtestId: f.draft.id }, ordinaryKey);
|
||||
await expect(f.api.reproduceRun(run.id, ordinaryKey)).rejects.toThrow('different run request');
|
||||
const other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Second template' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const second = await f.api.createRun({ backtestId: other.id });
|
||||
await f.execute(second.id);
|
||||
const racingKey = receipt('cross-parent');
|
||||
const racers = await Promise.allSettled([
|
||||
f.api.reproduceRun(run.id, racingKey),
|
||||
f.api.reproduceRun(second.id, racingKey),
|
||||
]);
|
||||
expect(racers.filter(value => value.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(racers.filter(value => value.status === 'rejected')).toHaveLength(1);
|
||||
expect(
|
||||
(await f.pool.query('SELECT * FROM runs WHERE submission_key=$1', [racingKey.key])).rowCount
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test('SQL copy guard rejects altered economics, cross-parent sources, missing receipts and rewritten lineage', async () => {
|
||||
const f = await fixture();
|
||||
const { run, result } = await completed(f);
|
||||
for (const mutation of [
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.name = 'Rewritten';
|
||||
},
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.strategy.selection.parameters = { fastPeriod: 6, slowPeriod: 7 };
|
||||
},
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.policy.matching.risk.feeRate =
|
||||
'0.00000000' as typeof value.policy.matching.risk.feeRate;
|
||||
},
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.strategy.reviewId = randomUUID();
|
||||
},
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.build.workerSha256 = 'b'.repeat(64);
|
||||
},
|
||||
(value: CanonicalRunRequest) => {
|
||||
value.policy.matching.risk.ledger.accountId = 'wrong';
|
||||
},
|
||||
]) {
|
||||
const snapshot = copied(result.request, randomUUID());
|
||||
mutation(snapshot);
|
||||
await expect(insertCopy(f, run.id, snapshot)).rejects.toThrow(
|
||||
'preserve the original frozen request'
|
||||
);
|
||||
}
|
||||
const other = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Other parent' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
await expect(
|
||||
insertCopy(f, run.id, copied(result.request, randomUUID()), other.id)
|
||||
).rejects.toThrow('same backtest');
|
||||
const id = randomUUID();
|
||||
await expect(insertCopy(f, id, copied(result.request, id))).rejects.toThrow(
|
||||
'completed canonical source'
|
||||
);
|
||||
const accepted = await f.api.reproduceRun(run.id, receipt());
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET original_run_id=NULL WHERE id=$1', [accepted.id])
|
||||
).rejects.toThrow('immutable');
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET original_run_id=$1 WHERE id=$2', [accepted.id, run.id])
|
||||
).rejects.toThrow('immutable');
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [{}, accepted.id])
|
||||
).rejects.toThrow('immutable');
|
||||
const direct = copied(result.request, randomUUID());
|
||||
await expect(
|
||||
f.pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,request_snapshot,dataset_hash,original_run_id)
|
||||
VALUES($1,$2,100,'pending',$3,$4,$5)`,
|
||||
[direct.runId, f.draft.id, direct, direct.datasetHash, run.id]
|
||||
)
|
||||
).rejects.toThrow('submission receipt');
|
||||
// Reapplying migration keeps all source/result/receipt rows and lineage unchanged.
|
||||
const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
expect((await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows).toEqual(before);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
await f.api.cancelRun(accepted.id);
|
||||
expect((await f.api.getReproductionComparison(accepted.id)).status).toBe('unavailable');
|
||||
expect((await f.api.getReproductionComparison(accepted.id)).originalHash).toBeNull();
|
||||
});
|
||||
|
||||
test('missing_original_artifact and corrupt retained dataset fail without admission or provider fallback', async () => {
|
||||
const f = await fixture();
|
||||
const { run, result } = await completed(f);
|
||||
await f.pool.query('ALTER TABLE strategy_versions DISABLE TRIGGER USER');
|
||||
const broken = structuredClone(f.pkg);
|
||||
broken.artifact.content += '\n// damaged retained bytes';
|
||||
await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [
|
||||
broken,
|
||||
f.version.id,
|
||||
]);
|
||||
const unavailable = await f.api.getReproductionPreview(run.id);
|
||||
expect(unavailable.available).toBe(false);
|
||||
expect(unavailable.reason).toContain('hash mismatch');
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('hash mismatch');
|
||||
await f.pool.query('UPDATE strategy_versions SET envelope=$1 WHERE id=$2', [
|
||||
f.pkg,
|
||||
f.version.id,
|
||||
]);
|
||||
await f.pool.query('ALTER TABLE strategy_versions ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER USER');
|
||||
const badDataset = {
|
||||
...f.dataset,
|
||||
bars: f.dataset.bars.map((bar, index) =>
|
||||
index === 0 ? { ...bar, close: bar.close + 1 } : bar
|
||||
),
|
||||
};
|
||||
await f.pool.query('UPDATE backtest_datasets SET payload=$1 WHERE hash=$2', [
|
||||
badDataset,
|
||||
f.dataset.manifest.hash,
|
||||
]);
|
||||
expect((await f.api.getReproductionPreview(run.id)).available).toBe(false);
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('content validation');
|
||||
await f.pool.query('ALTER TABLE backtest_datasets DISABLE TRIGGER ALL');
|
||||
await f.pool.query('DELETE FROM backtest_datasets WHERE hash=$1', [f.dataset.manifest.hash]);
|
||||
expect((await f.api.getReproductionPreview(run.id)).reason).toContain('not found');
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not found');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
});
|
||||
|
||||
test('unsupported_engine_version is explicit and accepted receipt replay survives later installed-build mismatch', async () => {
|
||||
const f = await fixture();
|
||||
const { run, result } = await completed(f);
|
||||
const key = receipt();
|
||||
const accepted = await f.api.reproduceRun(run.id, key);
|
||||
const historical = structuredClone(result);
|
||||
historical.request.build.runtimeVersion = 'historical-unsupported';
|
||||
// Simulate an older stored build in this disposable schema; never change installed binaries.
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [
|
||||
historical.request,
|
||||
run.id,
|
||||
]);
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [
|
||||
historical,
|
||||
run.id,
|
||||
]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE backtest_results ENABLE TRIGGER USER');
|
||||
const preview = await f.api.getReproductionPreview(run.id);
|
||||
expect(preview.available).toBe(false);
|
||||
expect(preview.reason).toContain('not installed');
|
||||
expect(preview.request?.build.runtimeVersion).toBe('historical-unsupported');
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('not installed');
|
||||
expect((await f.api.reproduceRun(run.id, key)).id).toBe(accepted.id);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(historical);
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(2);
|
||||
});
|
||||
|
||||
test('current original-family archive serializes with reproduction admission', async () => {
|
||||
const f = await fixture();
|
||||
const { run } = await completed(f);
|
||||
const blocker = await f.pool.connect();
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('SELECT id FROM strategies WHERE id=$1 FOR UPDATE', [f.version.strategyId]);
|
||||
let settled = false;
|
||||
const pending = f.api.reproduceRun(run.id, receipt()).finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
const outcome = pending.then(
|
||||
value => ({ value, error: null }),
|
||||
error => ({ value: null, error })
|
||||
);
|
||||
try {
|
||||
for (let attempt = 0; attempt < 200; attempt++) {
|
||||
const waiters = await f.pool.query(
|
||||
`SELECT count(*)::int AS count FROM pg_stat_activity
|
||||
WHERE application_name=$1 AND wait_event_type='Lock' AND query LIKE '%FOR UPDATE OF s%'`,
|
||||
[f.schema]
|
||||
);
|
||||
if (waiters.rows[0].count > 0) {
|
||||
break;
|
||||
}
|
||||
if (attempt === 199) {
|
||||
throw new Error('Reproduction did not wait on original-family lock');
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
expect(settled).toBe(false);
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
await blocker.query('COMMIT');
|
||||
expect((await outcome).error?.message).toContain('family is archived');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
}
|
||||
});
|
||||
|
||||
test('first SQL21 upgrade preserves existing results, snapshots, receipts and active lease state', async () => {
|
||||
const f = await fixture(4, false);
|
||||
const { run, result } = await completed(f);
|
||||
const key = receipt('pre-upgrade');
|
||||
const active = await f.api.createRun({ backtestId: f.draft.id }, key);
|
||||
await f.pool.query(
|
||||
`UPDATE runs SET status='running',attempt_number=2,attempt_id=$1,
|
||||
lease_expires_at=NOW()+INTERVAL '1 hour',progress=25 WHERE id=$2`,
|
||||
[randomUUID(), active.id]
|
||||
);
|
||||
const before = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
const dispatch = (await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows;
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/21-run-reproduction.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const after = (await f.pool.query('SELECT * FROM runs ORDER BY run_number')).rows;
|
||||
expect(
|
||||
after.map(({ original_run_id, ...row }) => {
|
||||
expect(original_run_id).toBeNull();
|
||||
return row;
|
||||
})
|
||||
).toEqual(before);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch ORDER BY run_id')).rows).toEqual(
|
||||
dispatch
|
||||
);
|
||||
expect((await f.api.createRun({ backtestId: f.draft.id }, key)).id).toBe(active.id);
|
||||
expect(await f.api.getRunResults(run.id)).toEqual(result);
|
||||
const copy = await f.api.reproduceRun(run.id, receipt());
|
||||
await f.execute(copy.id);
|
||||
expect((await f.api.getReproductionComparison(copy.id)).status).toBe('match');
|
||||
});
|
||||
|
||||
test('corrupt retained canonical request or result is a sanitized server failure, never a valid preview or input400', async () => {
|
||||
const f = await fixture();
|
||||
const { run, result } = await completed(f);
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [
|
||||
{ ...result.request, policy: {} },
|
||||
run.id,
|
||||
]);
|
||||
const response = await f.app.request(`/api/v2/runs/${run.id}/reproduction`);
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.json()).toEqual({ error: 'Could not inspect original run reproduction' });
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow();
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=$1 WHERE id=$2', [result.request, run.id]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE backtest_results DISABLE TRIGGER USER');
|
||||
const corrupt = structuredClone(result);
|
||||
corrupt.analytics.metrics.totalReturn = 99;
|
||||
await f.pool.query('UPDATE backtest_results SET canonical_result=$1 WHERE run_id=$2', [
|
||||
corrupt,
|
||||
run.id,
|
||||
]);
|
||||
expect((await f.app.request(`/api/v2/runs/${run.id}/reproduction`)).status).toBe(500);
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('does not match');
|
||||
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
||||
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
||||
});
|
||||
|
||||
test('incomplete, missing and legacy source inputs are explicit unavailable states', async () => {
|
||||
const f = await fixture();
|
||||
await f.approve();
|
||||
const run = await f.api.createRun({ backtestId: f.draft.id });
|
||||
expect((await f.api.getReproductionPreview(run.id)).reason).toContain('completed');
|
||||
await expect(f.api.reproduceRun(run.id, receipt())).rejects.toThrow('completed');
|
||||
await expect(f.api.getReproductionPreview(randomUUID())).rejects.toThrow('not found');
|
||||
await expect(f.api.getReproductionComparison(randomUUID())).rejects.toThrow('not found');
|
||||
// Legacy rows remain readable and acquire NULL lineage after additive migration.
|
||||
const legacy = await f.api.createBacktest(
|
||||
{
|
||||
name: 'Legacy',
|
||||
strategy: 'sma',
|
||||
symbols: ['X0.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-01-02',
|
||||
initialCapital: 10000,
|
||||
},
|
||||
{ autoStart: false }
|
||||
);
|
||||
const legacyRun = await f.api.createRun({ backtestId: legacy.id });
|
||||
await f.pool.query("UPDATE runs SET status='completed' WHERE id=$1", [legacyRun.id]);
|
||||
expect((await f.api.getRun(legacyRun.id))?.originalRunId).toBeNull();
|
||||
expect((await f.api.getReproductionPreview(legacyRun.id)).reason).toContain(
|
||||
'frozen canonical inputs'
|
||||
);
|
||||
expect((await f.api.getReproductionComparison(legacyRun.id)).status).toBe('not-reproduction');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue