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
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue