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

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

View file

@ -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

View file

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

View file

@ -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`,