feat(research): run retained strategies through durable canonical engine
This commit is contained in:
parent
d929db707a
commit
618fb9e33c
58 changed files with 6596 additions and 779 deletions
|
|
@ -1,18 +1,25 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { CanonicalRunCapability } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
|
||||
import type {
|
||||
Backtest,
|
||||
CreateBacktestRequest,
|
||||
ResearchRunResult,
|
||||
Run,
|
||||
} from '../services/backtestApiV2';
|
||||
|
||||
interface RunSelection {
|
||||
id: string;
|
||||
backtestId: string | null;
|
||||
controller: AbortController;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
request?: Promise<void>;
|
||||
refreshRequested: boolean;
|
||||
results: RunResult | null;
|
||||
results: ResearchRunResult | null;
|
||||
}
|
||||
|
||||
const isActive = (run: Run) => ['pending', 'running', 'paused'].includes(run.status);
|
||||
|
|
@ -23,7 +30,7 @@ export function useBacktestV2() {
|
|||
const [backtest, setBacktest] = useState<Backtest | null>(null);
|
||||
const [runs, setRuns] = useState<Run[]>([]);
|
||||
const [currentRun, setCurrentRun] = useState<Run | null>(null);
|
||||
const [runResults, setRunResults] = useState<RunResult | null>(null);
|
||||
const [runResults, setRunResults] = useState<ResearchRunResult | null>(null);
|
||||
const [isBacktestLoading, setIsBacktestLoading] = useState(false);
|
||||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
@ -45,9 +52,65 @@ export function useBacktestV2() {
|
|||
} | null>(null);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
const [capabilityRetry, setCapabilityRetry] = useState(0);
|
||||
const [capabilityState, setCapabilityState] = useState<{
|
||||
definition: Backtest;
|
||||
retry: number;
|
||||
capability: CanonicalRunCapability | null;
|
||||
error: string | null;
|
||||
} | null>(null);
|
||||
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
|
||||
useEffect(() => {
|
||||
if (!backtest || !catalog || backtest.archivedAt) {
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
setCapabilityState({
|
||||
definition: backtest,
|
||||
retry: capabilityRetry,
|
||||
capability: null,
|
||||
error: null,
|
||||
});
|
||||
void backtestApiV2
|
||||
.canonicalCapability(backtest.id, controller.signal)
|
||||
.then(capability => {
|
||||
if (!controller.signal.aborted && mounted.current) {
|
||||
setCapabilityState({
|
||||
definition: backtest,
|
||||
retry: capabilityRetry,
|
||||
capability,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (!controller.signal.aborted && mounted.current) {
|
||||
setCapabilityState({
|
||||
definition: backtest,
|
||||
retry: capabilityRetry,
|
||||
capability: null,
|
||||
error: messageOf(error, 'Could not check execution eligibility'),
|
||||
});
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [backtest, catalog, capabilityRetry]);
|
||||
const currentCapability =
|
||||
capabilityState?.definition === backtest && capabilityState?.retry === capabilityRetry
|
||||
? capabilityState
|
||||
: null;
|
||||
const canonicalCapability =
|
||||
!backtest?.archivedAt && !isBacktestLoading ? (currentCapability?.capability ?? null) : null;
|
||||
const capabilityError = currentCapability?.error ?? null;
|
||||
const isCapabilityLoading =
|
||||
catalog && !backtest?.archivedAt && !capabilityError && canonicalCapability === null;
|
||||
const refreshCanonicalCapability = useCallback(() => setCapabilityRetry(value => value + 1), []);
|
||||
|
||||
const isSelected = useCallback(
|
||||
(selected: RunSelection) => mounted.current && selection.current === selected,
|
||||
(selected: RunSelection) =>
|
||||
mounted.current &&
|
||||
selection.current === selected &&
|
||||
selected.backtestId === loadedBacktestId.current,
|
||||
[]
|
||||
);
|
||||
|
||||
|
|
@ -81,6 +144,17 @@ export function useBacktestV2() {
|
|||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.id !== selected.id ||
|
||||
(selected.backtestId !== null && run.backtestId !== selected.backtestId)
|
||||
) {
|
||||
monitorAgain = false;
|
||||
selected.refreshRequested = false;
|
||||
selected.results = null;
|
||||
setCurrentRun(null);
|
||||
setRunResults(null);
|
||||
throw new Error('Received a run for a different backtest or run selection');
|
||||
}
|
||||
|
||||
setCurrentRun(run);
|
||||
setRuns(previous =>
|
||||
|
|
@ -106,8 +180,12 @@ export function useBacktestV2() {
|
|||
if (!isSelected(selected)) {
|
||||
return;
|
||||
}
|
||||
if (results && results.runId !== selected.id) {
|
||||
throw new Error('Received results for a different run');
|
||||
if (
|
||||
results &&
|
||||
(results.runId !== selected.id || results.backtestId !== run.backtestId)
|
||||
) {
|
||||
selected.refreshRequested = false;
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
selected.results = results;
|
||||
setRunResults(results);
|
||||
|
|
@ -155,7 +233,11 @@ export function useBacktestV2() {
|
|||
|
||||
const selectRun = useCallback(
|
||||
(runId: string | undefined) => {
|
||||
if (runId && selection.current?.id === runId) {
|
||||
if (
|
||||
runId &&
|
||||
selection.current?.id === runId &&
|
||||
selection.current.backtestId === loadedBacktestId.current
|
||||
) {
|
||||
return refreshSelection(selection.current);
|
||||
}
|
||||
stopMonitoring();
|
||||
|
|
@ -170,6 +252,7 @@ export function useBacktestV2() {
|
|||
|
||||
const selected: RunSelection = {
|
||||
id: runId,
|
||||
backtestId: loadedBacktestId.current,
|
||||
controller: new AbortController(),
|
||||
refreshRequested: false,
|
||||
results: null,
|
||||
|
|
@ -180,45 +263,55 @@ export function useBacktestV2() {
|
|||
[refreshSelection, stopMonitoring]
|
||||
);
|
||||
|
||||
const loadBacktest = useCallback(async (id: string) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
if (loadedBacktestId.current !== id) {
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
loadedBacktestId.current = id;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
try {
|
||||
const [loadedBacktest, loadedRuns] = await Promise.all([
|
||||
backtestApiV2.getBacktest(id),
|
||||
backtestApiV2.listRuns(id),
|
||||
]);
|
||||
if (!mounted.current || generation !== backtestGeneration.current) {
|
||||
return;
|
||||
const loadBacktest = useCallback(
|
||||
async (id: string) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
if (loadedBacktestId.current !== id) {
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
// Parent-only route changes do not rerun the page's runId effect. Fence
|
||||
// the old request chain and validate the same selection against its new parent.
|
||||
loadedBacktestId.current = id;
|
||||
void selectRun(selection.current?.id);
|
||||
}
|
||||
setBacktest(loadedBacktest);
|
||||
// Run polling may already have a newer version of the selected row.
|
||||
setRuns(previous =>
|
||||
loadedRuns.map(run =>
|
||||
run.id === selection.current?.id
|
||||
? (previous.find(item => item.id === run.id) ?? run)
|
||||
: run
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to load backtest'));
|
||||
loadedBacktestId.current = id;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
try {
|
||||
const [loadedBacktest, loadedRuns] = await Promise.all([
|
||||
backtestApiV2.getBacktest(id),
|
||||
backtestApiV2.listRuns(id),
|
||||
]);
|
||||
if (!mounted.current || generation !== backtestGeneration.current) {
|
||||
return;
|
||||
}
|
||||
if (loadedBacktest.id !== id || loadedRuns.some(run => run.backtestId !== id)) {
|
||||
throw new Error('Received a definition or run history for a different backtest');
|
||||
}
|
||||
setBacktest(loadedBacktest);
|
||||
// Run polling may already have a newer version of the selected row.
|
||||
setRuns(previous =>
|
||||
loadedRuns.map(run =>
|
||||
run.id === selection.current?.id
|
||||
? (previous.find(item => item.id === run.id) ?? run)
|
||||
: run
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to load backtest'));
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
},
|
||||
[selectRun]
|
||||
);
|
||||
|
||||
const createBacktest = useCallback(
|
||||
async (request: CreateBacktestRequest) => {
|
||||
|
|
@ -334,11 +427,13 @@ export function useBacktestV2() {
|
|||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if ((backtest.strategyVersionId || backtest.strategy === 'catalog') && !submission.current) {
|
||||
setSubmissionError(catalogExecutionReason);
|
||||
if (catalog && !canonicalCapability?.available && !submission.current) {
|
||||
setSubmissionError(
|
||||
capabilityError ?? canonicalCapability?.reason ?? catalogExecutionReason
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (!supportedLegacyStrategy(backtest.strategy) && !submission.current) {
|
||||
if (!catalog && !supportedLegacyStrategy(backtest.strategy) && !submission.current) {
|
||||
setSubmissionError(
|
||||
'This legacy strategy is not supported for new submissions by this form.'
|
||||
);
|
||||
|
|
@ -351,7 +446,7 @@ export function useBacktestV2() {
|
|||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
body: { speedMultiplier },
|
||||
body: { speedMultiplier: catalog ? null : speedMultiplier },
|
||||
pending: false,
|
||||
});
|
||||
intent.pending = true;
|
||||
|
|
@ -386,7 +481,7 @@ export function useBacktestV2() {
|
|||
}
|
||||
}
|
||||
},
|
||||
[backtest]
|
||||
[backtest, catalog, canonicalCapability, capabilityError]
|
||||
);
|
||||
|
||||
const cancelRun = useCallback(async () => {
|
||||
|
|
@ -431,6 +526,10 @@ export function useBacktestV2() {
|
|||
runs,
|
||||
currentRun,
|
||||
runResults,
|
||||
canonicalCapability,
|
||||
capabilityError,
|
||||
isCapabilityLoading,
|
||||
refreshCanonicalCapability,
|
||||
isLoading: isBacktestLoading || isRunLoading,
|
||||
error: runError ?? error,
|
||||
submissionError,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue