fix(backtest): keep run history available while metrics load (RP12)
This commit is contained in:
parent
32f40ee753
commit
a050c71012
4 changed files with 312 additions and 53 deletions
|
|
@ -6,11 +6,10 @@ import {
|
|||
XCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { isCanonicalRunResult } from '@stock-bot/stock-config/canonical-research';
|
||||
import { DataTable } from '@/components/ui/DataTable';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
import type { Run } from '../services/backtestApiV2';
|
||||
import { backtestApiV2 } from '../services/backtestApiV2';
|
||||
|
||||
|
|
@ -30,62 +29,108 @@ interface RunWithMetrics extends Run {
|
|||
totalProfit?: number | null;
|
||||
};
|
||||
resultKind?: 'canonical' | 'legacy';
|
||||
initialCapital?: number;
|
||||
metricsState?: MetricsState;
|
||||
}
|
||||
|
||||
type MetricsState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'failed'; error: string }
|
||||
| { status: 'ready'; metrics: RunWithMetrics['metrics']; resultKind: 'canonical' | 'legacy' };
|
||||
|
||||
const metricsKey = (run: Run) => JSON.stringify([run.backtestId, run.id]);
|
||||
|
||||
export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) {
|
||||
const navigate = useNavigate();
|
||||
const { id: backtestId } = useParams<{ id: string }>();
|
||||
const [runsWithMetrics, setRunsWithMetrics] = useState<RunWithMetrics[]>([]);
|
||||
const [loadingMetrics, setLoadingMetrics] = useState(false);
|
||||
const [metrics, setMetrics] = useState<Record<string, MetricsState>>({});
|
||||
const requests = useRef(new Map<string, { controller: AbortController; pending: boolean }>());
|
||||
|
||||
// Fetch metrics for completed runs
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const fetchMetrics = async () => {
|
||||
setLoadingMetrics(true);
|
||||
const updatedRuns: RunWithMetrics[] = await Promise.all(
|
||||
runs.map(async run => {
|
||||
if (run.status === 'completed') {
|
||||
try {
|
||||
const results = await backtestApiV2.getRunResults(run.id, controller.signal);
|
||||
if (results.runId !== run.id || results.backtestId !== run.backtestId) {
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
return {
|
||||
...run,
|
||||
metrics: isCanonicalRunResult(results)
|
||||
? results.analytics.metrics
|
||||
: results.metrics,
|
||||
resultKind: isCanonicalRunResult(results)
|
||||
? ('canonical' as const)
|
||||
: ('legacy' as const),
|
||||
initialCapital: isCanonicalRunResult(results)
|
||||
? undefined
|
||||
: results.config?.initialCapital,
|
||||
};
|
||||
} catch (error) {
|
||||
browserLog.error(`Failed to fetch metrics for run ${run.id}:`, error);
|
||||
return run;
|
||||
}
|
||||
}
|
||||
return run;
|
||||
})
|
||||
);
|
||||
if (!controller.signal.aborted) {
|
||||
setRunsWithMetrics(updatedRuns);
|
||||
setLoadingMetrics(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (runs.length > 0) {
|
||||
void fetchMetrics();
|
||||
} else {
|
||||
setRunsWithMetrics([]);
|
||||
setLoadingMetrics(false);
|
||||
const loadMetrics = useCallback((run: Run) => {
|
||||
const key = metricsKey(run);
|
||||
const previous = requests.current.get(key);
|
||||
if (previous?.pending) {
|
||||
return;
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [runs]);
|
||||
previous?.controller.abort();
|
||||
const controller = new AbortController();
|
||||
const owned = { controller, pending: true };
|
||||
requests.current.set(key, owned);
|
||||
const current = () => !controller.signal.aborted && requests.current.get(key) === owned;
|
||||
setMetrics(previous => ({ ...previous, [key]: { status: 'loading' } }));
|
||||
void backtestApiV2
|
||||
.getRunResults(run.id, controller.signal)
|
||||
.then(results => {
|
||||
if (results.runId !== run.id || results.backtestId !== run.backtestId) {
|
||||
throw new Error('Received results for a different backtest or run');
|
||||
}
|
||||
if (current()) {
|
||||
setMetrics(previous => ({
|
||||
...previous,
|
||||
[key]: {
|
||||
status: 'ready',
|
||||
metrics: isCanonicalRunResult(results) ? results.analytics.metrics : results.metrics,
|
||||
resultKind: isCanonicalRunResult(results) ? 'canonical' : 'legacy',
|
||||
},
|
||||
}));
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (current()) {
|
||||
setMetrics(previous => ({
|
||||
...previous,
|
||||
[key]: {
|
||||
status: 'failed',
|
||||
error: error instanceof Error ? error.message : 'Could not load saved metrics',
|
||||
},
|
||||
}));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
owned.pending = false;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Polling changes run records, not ownership of unchanged completed-result reads.
|
||||
useEffect(() => {
|
||||
const completed = runs.filter(run => run.status === 'completed');
|
||||
const retained = new Set(completed.map(metricsKey));
|
||||
for (const [key, request] of requests.current) {
|
||||
if (!retained.has(key)) {
|
||||
request.controller.abort();
|
||||
requests.current.delete(key);
|
||||
}
|
||||
}
|
||||
setMetrics(previous =>
|
||||
Object.keys(previous).some(key => !retained.has(key))
|
||||
? Object.fromEntries(Object.entries(previous).filter(([key]) => retained.has(key)))
|
||||
: previous
|
||||
);
|
||||
for (const run of completed) {
|
||||
if (!requests.current.has(metricsKey(run))) {
|
||||
loadMetrics(run);
|
||||
}
|
||||
}
|
||||
}, [runs, loadMetrics]);
|
||||
useEffect(() => {
|
||||
const owned = requests.current;
|
||||
return () => {
|
||||
for (const request of owned.values()) {
|
||||
request.controller.abort();
|
||||
}
|
||||
owned.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const runsWithMetrics: RunWithMetrics[] = runs.map(run => {
|
||||
const state = run.status === 'completed' ? metrics[metricsKey(run)] : undefined;
|
||||
return {
|
||||
...run,
|
||||
metricsState: state,
|
||||
...(state?.status === 'ready'
|
||||
? { metrics: state.metrics, resultKind: state.resultKind }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const getStatusIcon = (status: Run['status']) => {
|
||||
switch (status) {
|
||||
|
|
@ -345,6 +390,40 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'metricsState',
|
||||
header: 'Result metrics',
|
||||
size: 220,
|
||||
cell: ({ row }) => {
|
||||
const run = row.original;
|
||||
if (run.status !== 'completed') {
|
||||
return <span className="text-text-secondary">Not completed</span>;
|
||||
}
|
||||
if (run.metricsState?.status === 'failed') {
|
||||
return (
|
||||
<span className="text-text-secondary" title={run.metricsState.error}>
|
||||
Metrics unavailable{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="text-primary-500 underline"
|
||||
aria-label={`Retry metrics for run ${run.runNumber}`}
|
||||
onClick={event => {
|
||||
event.stopPropagation();
|
||||
loadMetrics(run);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="text-text-secondary">
|
||||
{run.metricsState?.status === 'ready' ? 'Loaded' : 'Loading metrics...'}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
if (runs.length === 0) {
|
||||
|
|
@ -365,7 +444,6 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
}}
|
||||
className="bg-surface-secondary rounded-lg border border-border"
|
||||
height={400}
|
||||
loading={loadingMetrics}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue