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
|
|
@ -187,3 +187,24 @@ export function parseCanonicalFinancialResult(input: unknown, request: Canonical
|
|||
request.policy
|
||||
);
|
||||
}
|
||||
|
||||
/** Reproduce retained inputs on the exact installed build; no historical binary provisioning. */
|
||||
export interface CanonicalReproductionPreview {
|
||||
originalRunId: string;
|
||||
backtestId: string;
|
||||
available: boolean;
|
||||
reason: string | null;
|
||||
request: CanonicalRunRequest | null;
|
||||
/** Current approval required for a fresh admission; historical approval stays in request. */
|
||||
currentReviewId: string | null;
|
||||
}
|
||||
export interface CanonicalReproductionComparison {
|
||||
version: 'canonical-reproduction/v1';
|
||||
runId: string;
|
||||
backtestId: string;
|
||||
originalRunId: string | null;
|
||||
status: 'not-reproduction' | 'pending' | 'unavailable' | 'match' | 'mismatch';
|
||||
reason: string | null;
|
||||
originalHash: string | null;
|
||||
reproducedHash: string | null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,7 +60,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql' ||
|
||||
f === '19-canonical-research.sql' ||
|
||||
f === '20-research-workspace.sql')
|
||||
f === '20-research-workspace.sql' ||
|
||||
f === '21-run-reproduction.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import { getCredentialHttpPrincipal, getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
CatalogExecutionUnavailableError,
|
||||
RunSubmissionConflictError,
|
||||
} from '../services/backtest-v2.service';
|
||||
import { RunReproductionError } from '../services/run-reproduction';
|
||||
import { StrategyCatalogError } from '../services/strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
|
@ -184,6 +185,79 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/reproduction', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const id = z.string().uuid().safeParse(c.req.param('id'));
|
||||
if (!id.success) {
|
||||
return c.json({ error: 'Invalid original run ID' }, 400);
|
||||
}
|
||||
try {
|
||||
return c.json(await backtestService.getReproductionPreview(id.data));
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
logger.error('Failed to preview reproduction', error);
|
||||
return c.json({ error: 'Could not inspect original run reproduction' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/v2/runs/:id/reproduce', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const principal = getCredentialHttpPrincipal(c.req.raw);
|
||||
if (!principal) {
|
||||
return c.json({ error: 'Verified credential principal required' }, 401);
|
||||
}
|
||||
let originalRunId: string;
|
||||
let key: string;
|
||||
try {
|
||||
originalRunId = z.string().uuid().parse(c.req.param('id'));
|
||||
key = z
|
||||
.string()
|
||||
.regex(/^[\x21-\x7e]{1,200}$/)
|
||||
.parse(c.req.header('Idempotency-Key'));
|
||||
z.object({})
|
||||
.strict()
|
||||
.parse(await c.req.json());
|
||||
} catch {
|
||||
return c.json(
|
||||
{ error: 'Use a valid run ID, an empty object and a 1–200 visible ASCII Idempotency-Key' },
|
||||
400
|
||||
);
|
||||
}
|
||||
try {
|
||||
const run = await backtestService.reproduceRun(originalRunId, { principal, key });
|
||||
c.header('Location', `/api/v2/runs/${run.id}`);
|
||||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError || error instanceof RunSubmissionConflictError) {
|
||||
return c.json({ error: error.message }, 409);
|
||||
}
|
||||
logger.error('Failed to reproduce original run', error);
|
||||
return c.json({ error: 'Could not reproduce original run' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id/reproduction-comparison', async c => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
const id = z.string().uuid().safeParse(c.req.param('id'));
|
||||
if (!id.success) {
|
||||
return c.json({ error: 'Invalid run ID' }, 400);
|
||||
}
|
||||
try {
|
||||
return c.json(await backtestService.getReproductionComparison(id.data));
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
return c.json({ error: error.message, code: error.code }, error.status);
|
||||
}
|
||||
logger.error('Failed to compare reproduction', error);
|
||||
return c.json({ error: 'Could not compare retained reproduction results' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/runs/:id', async c => {
|
||||
try {
|
||||
const run = await backtestService.getRun(c.req.param('id'));
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ import {
|
|||
import {
|
||||
canonicalRunRequestSchema,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalReproductionComparison,
|
||||
type CanonicalReproductionPreview,
|
||||
type CanonicalRunCapability,
|
||||
type CanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
|
|
@ -33,6 +35,8 @@ import type { WebSocketHandler } from '../websocket/run-updates';
|
|||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
import { canonicalReproductionHash } from './reproduction-comparison';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
|
@ -78,6 +82,7 @@ export interface Backtest {
|
|||
}
|
||||
|
||||
export interface Run {
|
||||
originalRunId: string | null;
|
||||
dataset: BacktestRunDatasetSelection;
|
||||
id: string;
|
||||
backtestId: string;
|
||||
|
|
@ -504,6 +509,224 @@ export class BacktestServiceV2 {
|
|||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
/** Preview validates retained inputs without admitting work or consulting current settings. */
|
||||
async getReproductionPreview(originalRunId: string): Promise<CanonicalReproductionPreview> {
|
||||
return this.container.postgres.transaction(async client => {
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const preview: CanonicalReproductionPreview = {
|
||||
originalRunId,
|
||||
backtestId: source.backtest_id,
|
||||
available: false,
|
||||
reason: null,
|
||||
request: null,
|
||||
currentReviewId: null,
|
||||
};
|
||||
try {
|
||||
const request = await this.originalCanonicalRequest(client, source);
|
||||
preview.request = request;
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'Backtest is archived; restore it before reproducing a run'
|
||||
);
|
||||
}
|
||||
preview.currentReviewId = await verifyReproductionInputs(client, this.container, request);
|
||||
preview.available = true;
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof RunReproductionError)) {
|
||||
throw cause;
|
||||
}
|
||||
preview.reason = cause.message;
|
||||
}
|
||||
return preview;
|
||||
});
|
||||
}
|
||||
|
||||
async reproduceRun(originalRunId: string, submission: RunSubmission): Promise<Run> {
|
||||
if (
|
||||
!submission ||
|
||||
!['operator', 'service'].includes(submission.principal) ||
|
||||
!/^[\x21-\x7e]{1,200}$/.test(submission.key)
|
||||
) {
|
||||
throw new HistoricalDataRequestError('Reproduction requires a verified submission receipt');
|
||||
}
|
||||
const submissionHash = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
operation: 'reproduce-original',
|
||||
originalRunId,
|
||||
})
|
||||
)
|
||||
.digest('hex');
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const replay = async () => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
'SELECT * FROM runs WHERE submission_principal=$1 AND submission_key=$2',
|
||||
[submission.principal, submission.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (saved && saved.submission_hash !== submissionHash) {
|
||||
throw new RunSubmissionConflictError();
|
||||
}
|
||||
return saved;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
const source = (await client.query('SELECT * FROM runs WHERE id=$1', [originalRunId]))
|
||||
.rows[0];
|
||||
if (!source) {
|
||||
throw new RunReproductionError(404, 'Original run not found');
|
||||
}
|
||||
const parent = (
|
||||
await client.query('SELECT archived_at FROM backtests WHERE id=$1 FOR UPDATE', [
|
||||
source.backtest_id,
|
||||
])
|
||||
).rows[0];
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (!parent || parent.archived_at !== null) {
|
||||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const original = await this.originalCanonicalRequest(client, source);
|
||||
const reviewId = await verifyReproductionInputs(client, this.container, original);
|
||||
const runId = uuidv4();
|
||||
const snapshot = structuredClone(original);
|
||||
snapshot.runId = runId;
|
||||
snapshot.policy.matching.risk.ledger.sessionId = runId;
|
||||
snapshot.policy.matching.risk.ledger.accountId = `research:${runId}`;
|
||||
snapshot.strategy.reviewId = reviewId;
|
||||
canonicalRunRequestSchema.parse(snapshot);
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,
|
||||
submission_principal,submission_key,submission_hash,original_run_id)
|
||||
SELECT $1,$2,COALESCE(MAX(run_number),0)+1,'pending'::run_status,NULL,$3::jsonb,$4,$5,$6,$7,$8
|
||||
FROM runs WHERE backtest_id=$2
|
||||
ON CONFLICT (submission_principal,submission_key) DO NOTHING RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
source.backtest_id,
|
||||
JSON.stringify(snapshot),
|
||||
snapshot.datasetHash,
|
||||
submission.principal,
|
||||
submission.key,
|
||||
submissionHash,
|
||||
originalRunId,
|
||||
]
|
||||
);
|
||||
if (!inserted.rows[0]) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent reproduction disappeared; retry with the same key');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return inserted.rows[0];
|
||||
});
|
||||
return this.mapRun(row);
|
||||
}
|
||||
|
||||
async getReproductionComparison(runId: string): Promise<CanonicalReproductionComparison> {
|
||||
const current = (await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0];
|
||||
if (!current) {
|
||||
throw new RunReproductionError(404, 'Run not found');
|
||||
}
|
||||
const comparison: CanonicalReproductionComparison = {
|
||||
version: 'canonical-reproduction/v1',
|
||||
runId,
|
||||
backtestId: current.backtest_id,
|
||||
originalRunId: current.original_run_id ?? null,
|
||||
status: 'not-reproduction',
|
||||
reason: null,
|
||||
originalHash: null,
|
||||
reproducedHash: null,
|
||||
};
|
||||
if (!comparison.originalRunId) {
|
||||
return comparison;
|
||||
}
|
||||
if (['pending', 'running', 'paused'].includes(current.status)) {
|
||||
return { ...comparison, status: 'pending', reason: 'The reproduction has not completed' };
|
||||
}
|
||||
if (current.status !== 'completed') {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The reproduction did not complete successfully',
|
||||
};
|
||||
}
|
||||
const source = (
|
||||
await this.container.postgres.query('SELECT * FROM runs WHERE id=$1', [
|
||||
comparison.originalRunId,
|
||||
])
|
||||
).rows[0];
|
||||
if (!source || source.status !== 'completed' || source.backtest_id !== current.backtest_id) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'The original completed run is unavailable',
|
||||
};
|
||||
}
|
||||
const original = await this.getRunResults(source.id);
|
||||
const reproduced = await this.getRunResults(runId);
|
||||
if (!original || !reproduced || !('kind' in original) || !('kind' in reproduced)) {
|
||||
return {
|
||||
...comparison,
|
||||
status: 'unavailable',
|
||||
reason: 'Complete canonical results are unavailable',
|
||||
};
|
||||
}
|
||||
const originalHash = canonicalReproductionHash(original);
|
||||
const reproducedHash = canonicalReproductionHash(reproduced);
|
||||
return {
|
||||
...comparison,
|
||||
originalHash,
|
||||
reproducedHash,
|
||||
status: originalHash === reproducedHash ? 'match' : 'mismatch',
|
||||
};
|
||||
}
|
||||
|
||||
private async originalCanonicalRequest(client: PoolClient, source: QueryResultRow) {
|
||||
if (source.status !== 'completed') {
|
||||
throw new RunReproductionError(409, 'Only completed original runs can be reproduced');
|
||||
}
|
||||
if (source.request_snapshot?.kind !== 'canonical-research/v1') {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original run lacks compatible frozen canonical inputs'
|
||||
);
|
||||
}
|
||||
const request = canonicalRunRequestSchema.parse(source.request_snapshot);
|
||||
if (
|
||||
request.runId !== source.id ||
|
||||
request.backtestId !== source.backtest_id ||
|
||||
request.datasetHash !== source.dataset_hash
|
||||
) {
|
||||
throw new Error('The retained canonical source identity is inconsistent');
|
||||
}
|
||||
const result = await this.getRunResults(source.id, client);
|
||||
if (!result || !('kind' in result) || result.kind !== 'canonical-result/v1') {
|
||||
throw new RunReproductionError(409, 'The original canonical result is unavailable');
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
async getRun(id: string): Promise<Run | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]);
|
||||
|
||||
|
|
@ -755,6 +978,7 @@ export class BacktestServiceV2 {
|
|||
|
||||
private mapRun(row: QueryResultRow): Run {
|
||||
return {
|
||||
originalRunId: row.original_run_id ?? null,
|
||||
dataset: datasetSelectionForRun(row),
|
||||
id: row.id,
|
||||
backtestId: row.backtest_id,
|
||||
|
|
|
|||
49
apps/stock/web-api/src/services/reproduction-comparison.ts
Normal file
49
apps/stock/web-api/src/services/reproduction-comparison.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
|
||||
/** Call with a retained result validated by getRunResults. This copies facts;
|
||||
* it never recalculates financial values or statistically approximates equality.
|
||||
* Only new admission identities are normalized. Market sessions, owner/decision/
|
||||
* order/fill IDs and every ordered financial/reporting fact remain significant. */
|
||||
export function canonicalReproductionHash(result: CanonicalRunResult): string {
|
||||
const request = canonicalRunRequestSchema.parse(result.request);
|
||||
if (
|
||||
result.kind !== 'canonical-result/v1' ||
|
||||
result.status !== 'completed' ||
|
||||
result.financialEngine !== 'rust' ||
|
||||
result.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
result.runId !== request.runId ||
|
||||
result.backtestId !== request.backtestId
|
||||
) {
|
||||
throw new Error('Reproduction comparison requires matching canonical result identity');
|
||||
}
|
||||
const financial = parseCanonicalFinancialResult(result.financial, request);
|
||||
// Parsed objects are detached. Do not recursively erase similarly named fields:
|
||||
// riskSession.sessionId, for example, is a real economic clock input.
|
||||
request.runId = 'run';
|
||||
request.strategy.reviewId = 'admission-review';
|
||||
request.policy.matching.risk.ledger.sessionId = 'run';
|
||||
request.policy.matching.risk.ledger.accountId = 'account';
|
||||
financial.identity.sessionId = 'run';
|
||||
financial.policy.matching.risk.ledger.sessionId = 'run';
|
||||
financial.policy.matching.risk.ledger.accountId = 'account';
|
||||
financial.view.portfolio.sessionId = 'run';
|
||||
financial.view.portfolio.accountId = 'account';
|
||||
return createHash('sha256')
|
||||
.update(
|
||||
canonicalStrategyJson({
|
||||
version: 'canonical-reproduction/v1',
|
||||
financialEngine: result.financialEngine,
|
||||
strategyExecution: result.strategyExecution,
|
||||
request,
|
||||
financial,
|
||||
analytics: result.analytics,
|
||||
})
|
||||
)
|
||||
.digest('hex');
|
||||
}
|
||||
104
apps/stock/web-api/src/services/run-reproduction.ts
Normal file
104
apps/stock/web-api/src/services/run-reproduction.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { readCanonicalDataset } from './canonical-research.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
export class RunReproductionError extends Error {
|
||||
readonly code = 'run_reproduction_unavailable';
|
||||
constructor(
|
||||
public readonly status: 404 | 409,
|
||||
message: string
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Under the parent lock, validate the ORIGINAL version, never current template settings. */
|
||||
export async function verifyReproductionInputs(
|
||||
client: PoolClient,
|
||||
container: IServiceContainer,
|
||||
request: CanonicalRunRequest
|
||||
): Promise<string> {
|
||||
const selected = (
|
||||
await client.query(
|
||||
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v
|
||||
JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (
|
||||
!selected ||
|
||||
selected.strategy_id !== request.strategy.familyId ||
|
||||
selected.origin !== 'builtin'
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original retained built-in version is unavailable');
|
||||
}
|
||||
if (selected.archived_at !== null) {
|
||||
throw new RunReproductionError(409, 'The original strategy family is archived');
|
||||
}
|
||||
const review = (
|
||||
await client.query(
|
||||
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
||||
[request.strategy.versionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original strategy version requires current operator approval'
|
||||
);
|
||||
}
|
||||
try {
|
||||
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
|
||||
request.strategy.versionId,
|
||||
client
|
||||
);
|
||||
if (canonicalStrategyJson(pkg) !== canonicalStrategyJson(request.strategy.package)) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The retained strategy artifact differs from the original request'
|
||||
);
|
||||
}
|
||||
const dataset = await readCanonicalDataset(client, request.datasetHash);
|
||||
const execution = dataset.manifest.executionSeries[0];
|
||||
if (
|
||||
execution?.instrumentId !== request.strategy.selection.instrumentId ||
|
||||
execution.seriesId !== request.strategy.selection.seriesId
|
||||
) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The retained dataset does not match the original execution series'
|
||||
);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (cause instanceof StrategyCatalogError || cause instanceof HistoricalDataRequestError) {
|
||||
throw new RunReproductionError(409, cause.message);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
let build;
|
||||
try {
|
||||
build = await readCanonicalBuildIdentity();
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause &&
|
||||
typeof cause === 'object' &&
|
||||
'code' in cause &&
|
||||
['ENOENT', 'ENOTDIR', 'EACCES'].includes(String(cause.code))
|
||||
) {
|
||||
throw new RunReproductionError(409, 'The original canonical build is not installed');
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
if (canonicalStrategyJson(build) !== canonicalStrategyJson(request.build)) {
|
||||
throw new RunReproductionError(
|
||||
409,
|
||||
'The original worker/native/runtime build is not installed; historical build execution is unavailable'
|
||||
);
|
||||
}
|
||||
return review.id;
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import { CanonicalResults } from './components/CanonicalResults';
|
|||
import { CanonicalSetup } from './components/CanonicalSetup';
|
||||
import { RunControlsCompact } from './components/RunControlsCompact';
|
||||
import { RunDataset } from './components/RunDataset';
|
||||
import { RunReproduction } from './components/RunReproduction';
|
||||
import { RunsListWithMetrics } from './components/RunsListWithMetrics';
|
||||
import { useBacktestV2 } from './hooks/useBacktestV2';
|
||||
import type { BacktestConfig } from './types/backtest.types';
|
||||
|
|
@ -510,6 +511,7 @@ export function BacktestDetailPageV2() {
|
|||
)}
|
||||
{currentRun && (
|
||||
<div className="px-4">
|
||||
<p className="text-xs text-text-secondary">Run current settings</p>
|
||||
<RunControlsCompact
|
||||
run={currentRun}
|
||||
onCancel={cancelRun}
|
||||
|
|
@ -604,7 +606,13 @@ export function BacktestDetailPageV2() {
|
|||
</div>
|
||||
)}
|
||||
{currentRun && <RunDataset dataset={currentRun.dataset} />}
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{renderTabContent()}</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{currentRun &&
|
||||
currentRun.id === runId &&
|
||||
currentRun.backtestId === id &&
|
||||
backtest?.id === id && <RunReproduction run={currentRun} archived={archived} />}
|
||||
{renderTabContent()}
|
||||
</div>
|
||||
</div>
|
||||
{showFinding && findingResult && (
|
||||
<SaveFindingDialog
|
||||
|
|
|
|||
|
|
@ -0,0 +1,387 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import type {
|
||||
CanonicalReproductionComparison,
|
||||
CanonicalReproductionPreview,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/Dialog';
|
||||
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { backtestApiV2, ReproductionSubmissionError, type Run } from '../services/backtestApiV2';
|
||||
|
||||
interface Props {
|
||||
run: Run;
|
||||
archived: boolean;
|
||||
}
|
||||
|
||||
/** A source change discards no receipt into another run's controls. */
|
||||
export function RunReproduction(props: Props) {
|
||||
return <Reproduction key={`${props.run.backtestId}:${props.run.id}`} {...props} />;
|
||||
}
|
||||
function Reproduction({ run, archived }: Props) {
|
||||
const navigate = useNavigate();
|
||||
const alive = useRef(false);
|
||||
const pending = useRef(false);
|
||||
const intent = useRef<{ originalRunId: string; backtestId: string; key: string } | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [preview, setPreview] = useState<CanonicalReproductionPreview | null>(null);
|
||||
const [previewError, setPreviewError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [reload, setReload] = useState(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [hasIntent, setHasIntent] = useState(false);
|
||||
const [ambiguous, setAmbiguous] = useState(false);
|
||||
const [comparison, setComparison] = useState<CanonicalReproductionComparison | null>(null);
|
||||
const [comparisonError, setComparisonError] = useState('');
|
||||
const [comparisonLoading, setComparisonLoading] = useState(false);
|
||||
const [comparisonReload, setComparisonReload] = useState(0);
|
||||
useUnsavedWarning(hasIntent);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setPreviewError('');
|
||||
setPreview(null);
|
||||
void backtestApiV2
|
||||
.reproductionPreview(run.id, controller.signal)
|
||||
.then(value => {
|
||||
if (value.originalRunId !== run.id || value.backtestId !== run.backtestId) {
|
||||
throw new Error('The reproduction preview belongs to a different run or backtest');
|
||||
}
|
||||
if (current) {
|
||||
setPreview(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setPreviewError(
|
||||
cause instanceof Error ? cause.message : 'Could not load original inputs'
|
||||
);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [open, reload, run.id, run.backtestId, run.status, archived]);
|
||||
useEffect(() => {
|
||||
if (!run.originalRunId) {
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setComparisonError('');
|
||||
setComparisonLoading(true);
|
||||
void backtestApiV2
|
||||
.reproductionComparison(run.id, controller.signal)
|
||||
.then(value => {
|
||||
if (
|
||||
value.runId !== run.id ||
|
||||
value.backtestId !== run.backtestId ||
|
||||
value.originalRunId !== run.originalRunId ||
|
||||
value.status === 'not-reproduction'
|
||||
) {
|
||||
throw new Error('The reproduction comparison does not match this run and its original');
|
||||
}
|
||||
if (current) {
|
||||
setComparison(value);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (current) {
|
||||
setComparisonError(cause instanceof Error ? cause.message : 'Could not load comparison');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (current) {
|
||||
setComparisonLoading(false);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
controller.abort();
|
||||
};
|
||||
}, [run.id, run.backtestId, run.originalRunId, run.status, comparisonReload]);
|
||||
|
||||
const canCreate = !archived && !loading && !previewError && preview?.available && preview.request;
|
||||
const submit = async () => {
|
||||
if (pending.current || (!intent.current && !canCreate)) {
|
||||
return;
|
||||
}
|
||||
// A retry retains this exact source/key even if a later preview is unavailable.
|
||||
intent.current ??= {
|
||||
originalRunId: run.id,
|
||||
backtestId: run.backtestId,
|
||||
key: crypto.randomUUID(),
|
||||
};
|
||||
const captured = intent.current;
|
||||
pending.current = true;
|
||||
setHasIntent(true);
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const admitted = await backtestApiV2.reproduceRun(captured.originalRunId, captured.key);
|
||||
if (
|
||||
admitted.backtestId !== captured.backtestId ||
|
||||
admitted.originalRunId !== captured.originalRunId
|
||||
) {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The accepted reproduction belongs to a different source. Retry the same submission to verify it.',
|
||||
null
|
||||
);
|
||||
}
|
||||
if (alive.current) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
navigate(
|
||||
`/backtests/${encodeURIComponent(admitted.backtestId)}/run/${encodeURIComponent(admitted.id)}`
|
||||
);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (alive.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Could not reproduce original run');
|
||||
setAmbiguous(!(cause instanceof ReproductionSubmissionError) || cause.ambiguous);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (alive.current) {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const close = () => {
|
||||
if (!pending.current) {
|
||||
setOpen(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<section
|
||||
aria-label="Original-run reproduction"
|
||||
className="mb-3 space-y-2 text-sm text-text-secondary"
|
||||
>
|
||||
<div className="flex gap-3 items-center flex-wrap">
|
||||
<Button variant="outline" size="sm" onClick={() => setOpen(true)}>
|
||||
Reproduce original
|
||||
</Button>
|
||||
<p>Use this run's retained inputs. New Run and Rerun use current settings.</p>
|
||||
</div>
|
||||
{run.originalRunId && (
|
||||
<section
|
||||
aria-label="Reproduction comparison"
|
||||
className="rounded border border-border p-3 space-y-2 break-words"
|
||||
>
|
||||
<p>
|
||||
Reproduction of{' '}
|
||||
<Link
|
||||
className="text-primary-500 underline"
|
||||
to={`/backtests/${encodeURIComponent(run.backtestId)}/run/${encodeURIComponent(run.originalRunId)}`}
|
||||
>
|
||||
Open original run
|
||||
</Link>{' '}
|
||||
<span className="text-xs">({run.originalRunId})</span>
|
||||
</p>
|
||||
{comparisonLoading && <p role="status">Loading reproduction comparison...</p>}
|
||||
{comparisonError && <p role="alert">{comparisonError}</p>}
|
||||
{comparison && (
|
||||
<>
|
||||
<p role="status">
|
||||
{comparison.status === 'match'
|
||||
? 'Economic results match the original.'
|
||||
: comparison.status === 'mismatch'
|
||||
? 'Economic results differ from the original.'
|
||||
: comparison.status === 'pending'
|
||||
? 'Reproduction comparison pending completion.'
|
||||
: 'Reproduction comparison unavailable.'}
|
||||
</p>
|
||||
{comparison.reason && <p>{comparison.reason}</p>}
|
||||
<p className="text-xs">Comparison policy: {comparison.version}</p>
|
||||
{comparison.originalHash && (
|
||||
<p className="text-xs break-all">
|
||||
Original economic hash: {comparison.originalHash}
|
||||
</p>
|
||||
)}
|
||||
{comparison.reproducedHash && (
|
||||
<p className="text-xs break-all">
|
||||
Reproduced economic hash: {comparison.reproducedHash}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs">
|
||||
The server compares retained inputs and saved results, excluding new run identities
|
||||
and execution duration. A match is not strategy validation.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={comparisonLoading}
|
||||
onClick={() => setComparisonReload(value => value + 1)}
|
||||
>
|
||||
Refresh comparison
|
||||
</Button>
|
||||
</section>
|
||||
)}
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={value => {
|
||||
if (!value) {
|
||||
close();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-w-3xl w-[min(48rem,95vw)]">
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Reproduce original"
|
||||
className="space-y-4"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Reproduce original</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="break-all">Original run: {run.id}</p>
|
||||
<p>
|
||||
This submits a new run using the original dataset, strategy version, parameters, seed
|
||||
and policies. Current template settings are not used. The same installed engine build
|
||||
and current strategy approval are required.
|
||||
</p>
|
||||
{loading && <p role="status">Loading original inputs...</p>}
|
||||
{previewError && <p role="alert">{previewError}</p>}
|
||||
{archived && (
|
||||
<p role="status">
|
||||
This backtest is archived. Restore it before creating a new reproduction.
|
||||
</p>
|
||||
)}
|
||||
{preview && !preview.available && (
|
||||
<p role="status">
|
||||
Original reproduction unavailable:{' '}
|
||||
{preview.reason ?? 'Retained inputs cannot be reproduced.'}
|
||||
</p>
|
||||
)}
|
||||
{preview?.request && (
|
||||
<section aria-label="Original retained inputs" className="space-y-2 break-words">
|
||||
<h3 className="font-medium text-text-primary">Original retained inputs</h3>
|
||||
<p>Name: {preview.request.name}</p>
|
||||
<p className="break-all">Dataset: {preview.request.datasetHash}</p>
|
||||
<p>
|
||||
Strategy version:{' '}
|
||||
<Link
|
||||
className="text-primary-500 underline"
|
||||
to={`/strategies/versions/${encodeURIComponent(preview.request.strategy.versionId)}`}
|
||||
>
|
||||
{preview.request.strategy.versionId}
|
||||
</Link>
|
||||
</p>
|
||||
<p>
|
||||
Asset: {preview.request.strategy.selection.instrumentId} · Series:{' '}
|
||||
{preview.request.strategy.selection.seriesId}
|
||||
</p>
|
||||
<p>Random seed: {preview.request.strategy.selection.seed}</p>
|
||||
<p>
|
||||
Initial capital: {preview.request.policy.matching.risk.ledger.initialCapital}{' '}
|
||||
{preview.request.policy.matching.risk.ledger.baseCurrency}
|
||||
</p>
|
||||
<p className="text-xs break-all">
|
||||
Original review: {preview.request.strategy.reviewId} · Current approval:{' '}
|
||||
{preview.currentReviewId ?? 'Unavailable'}
|
||||
</p>
|
||||
<details>
|
||||
<summary className="cursor-pointer">
|
||||
Exact parameters, financial policies and build
|
||||
</summary>
|
||||
<pre className="overflow-auto text-xs p-3 bg-surface-secondary rounded">
|
||||
{JSON.stringify(
|
||||
{
|
||||
strategy: preview.request.strategy.selection,
|
||||
artifact: {
|
||||
...preview.request.strategy.package.artifact,
|
||||
content: undefined,
|
||||
},
|
||||
dependencyLock: {
|
||||
...preview.request.strategy.package.dependencyLock,
|
||||
content: undefined,
|
||||
},
|
||||
policy: preview.request.policy,
|
||||
analyticsPolicy: preview.request.analyticsPolicy,
|
||||
modelArtifacts: preview.request.modelArtifacts,
|
||||
build: preview.request.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={loading || submitting}
|
||||
onClick={() => setReload(value => value + 1)}
|
||||
>
|
||||
Refresh original inputs
|
||||
</Button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{hasIntent && (
|
||||
<p role="status">
|
||||
{ambiguous ? 'The previous request may already have been accepted. ' : ''}Retry uses
|
||||
the same source and submission key to recover that run.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-3 flex-wrap">
|
||||
<Button
|
||||
disabled={submitting || (!hasIntent && !canCreate)}
|
||||
onClick={() => void submit()}
|
||||
>
|
||||
{submitting
|
||||
? 'Submitting reproduction...'
|
||||
: hasIntent
|
||||
? 'Retry reproduction'
|
||||
: 'Confirm reproduction'}
|
||||
</Button>
|
||||
{hasIntent && (
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={submitting}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
'The previous request may already have created a run. Start a separate reproduction only after checking run history. Continue?'
|
||||
)
|
||||
) {
|
||||
intent.current = null;
|
||||
setHasIntent(false);
|
||||
setError('');
|
||||
setAmbiguous(false);
|
||||
setReload(value => value + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Start new reproduction
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" disabled={submitting} onClick={close}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,8 @@
|
|||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
CanonicalDatasetCatalogEntry,
|
||||
CanonicalReproductionComparison,
|
||||
CanonicalReproductionPreview,
|
||||
CanonicalRunCapability,
|
||||
ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
|
|
@ -29,6 +32,7 @@ export interface Backtest {
|
|||
|
||||
export interface Run {
|
||||
id: string;
|
||||
originalRunId?: string | null;
|
||||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
|
|
@ -84,7 +88,137 @@ async function requestError(response: Response, fallback: string): Promise<Error
|
|||
return new Error(message);
|
||||
}
|
||||
|
||||
export class ReproductionSubmissionError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number | null
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
get ambiguous() {
|
||||
return this.status === null || this.status >= 500;
|
||||
}
|
||||
}
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const nullableText = (value: unknown) => value === null || typeof value === 'string';
|
||||
const hashOrNull = (value: unknown) =>
|
||||
value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value));
|
||||
|
||||
export const backtestApiV2 = {
|
||||
async reproductionPreview(
|
||||
id: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<CanonicalReproductionPreview> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction`,
|
||||
{ signal }
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not check original-run reproduction');
|
||||
}
|
||||
const body: unknown = await response.json();
|
||||
if (
|
||||
!isRecord(body) ||
|
||||
body.originalRunId !== id ||
|
||||
typeof body.backtestId !== 'string' ||
|
||||
typeof body.available !== 'boolean' ||
|
||||
!nullableText(body.reason) ||
|
||||
!nullableText(body.currentReviewId)
|
||||
) {
|
||||
throw new Error('The original-run preview response could not be verified');
|
||||
}
|
||||
const request = body.request === null ? null : canonicalRunRequestSchema.parse(body.request);
|
||||
if (
|
||||
(request && (request.runId !== id || request.backtestId !== body.backtestId)) ||
|
||||
(body.available && (!request || !body.currentReviewId))
|
||||
) {
|
||||
throw new Error('The original-run preview does not match its retained source');
|
||||
}
|
||||
return {
|
||||
originalRunId: id,
|
||||
backtestId: body.backtestId,
|
||||
available: body.available,
|
||||
reason: body.reason as string | null,
|
||||
currentReviewId: body.currentReviewId as string | null,
|
||||
request,
|
||||
};
|
||||
},
|
||||
async reproduceRun(originalRunId: string, submissionKey: string): Promise<Run> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
|
||||
body: '{}',
|
||||
}
|
||||
);
|
||||
} catch {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
|
||||
null
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = await requestError(response, 'Could not reproduce original run');
|
||||
throw new ReproductionSubmissionError(error.message, response.status);
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null);
|
||||
if (
|
||||
response.status !== 202 ||
|
||||
!isRecord(body) ||
|
||||
typeof body.id !== 'string' ||
|
||||
!body.id ||
|
||||
body.id === originalRunId ||
|
||||
typeof body.backtestId !== 'string' ||
|
||||
body.originalRunId !== originalRunId ||
|
||||
!['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes(
|
||||
String(body.status)
|
||||
)
|
||||
) {
|
||||
throw new ReproductionSubmissionError(
|
||||
'The accepted reproduction response could not be verified. Retry with this same submission key.',
|
||||
null
|
||||
);
|
||||
}
|
||||
return body as unknown as Run;
|
||||
},
|
||||
async reproductionComparison(
|
||||
id: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<CanonicalReproductionComparison> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction-comparison`,
|
||||
{ signal }
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await requestError(response, 'Could not load reproduction comparison');
|
||||
}
|
||||
const body: unknown = await response.json();
|
||||
if (
|
||||
!isRecord(body) ||
|
||||
body.version !== 'canonical-reproduction/v1' ||
|
||||
body.runId !== id ||
|
||||
typeof body.backtestId !== 'string' ||
|
||||
!nullableText(body.originalRunId) ||
|
||||
!nullableText(body.reason) ||
|
||||
!hashOrNull(body.originalHash) ||
|
||||
!hashOrNull(body.reproducedHash) ||
|
||||
!['not-reproduction', 'pending', 'unavailable', 'match', 'mismatch'].includes(
|
||||
String(body.status)
|
||||
) ||
|
||||
(['match', 'mismatch'].includes(String(body.status)) &&
|
||||
(!body.originalRunId || !body.originalHash || !body.reproducedHash)) ||
|
||||
(body.status === 'match' && body.originalHash !== body.reproducedHash) ||
|
||||
(body.status === 'mismatch' && body.originalHash === body.reproducedHash)
|
||||
) {
|
||||
throw new Error('The reproduction comparison response could not be verified');
|
||||
}
|
||||
return body as unknown as CanonicalReproductionComparison;
|
||||
},
|
||||
|
||||
async canonicalCapability(id: string, signal?: AbortSignal): Promise<CanonicalRunCapability> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/v2/backtests/${encodeURIComponent(id)}/canonical-capability`,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue