fix(backtest): keep run history available while metrics load (RP12)

This commit is contained in:
Boki 2026-10-27 14:14:30 -04:00
parent 32f40ee753
commit a050c71012
4 changed files with 312 additions and 53 deletions

View file

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

View file

@ -456,7 +456,7 @@ export async function fixture(browser: Browser, native = false) {
const response = await routes.fetch(request);
const delay = responseDelay;
if (delay?.path === pathname) {
responseDelay = undefined; // Only the selected read, not run-list metric reads.
responseDelay = undefined; // Delay only the next matching read.
delay.captured.resolve();
await delay.release.promise;
delay.delivered.resolve();

View file

@ -1893,6 +1893,29 @@ test('browser_reopen_and_switch', async () => {
await visible(f.page, secondId);
expect(f.page.url()).toBe(secondUrl);
expect(await f.page.getByText(firstId, { exact: true }).count()).toBe(0);
// Optional history metrics must not hide saved runs while one result is delayed.
const beforeHistorySelection = (
await f.pool.query('SELECT id, status FROM runs WHERE backtest_id=$1 ORDER BY id', [
definitionId,
])
).rows;
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
await delayed.captured.wait('delayed history metrics');
await visible(f.page, /^#1$/);
await visible(f.page, /^#2\s*Canonical$/);
await f.page.getByText(/^#2\s*Canonical$/).click();
await visible(f.page, 'Completed');
expect(f.page.url()).toBe(secondUrl);
delayed.release.resolve();
await delayed.delivered.wait('history metrics released after selection');
expect(
(
await f.pool.query('SELECT id, status FROM runs WHERE backtest_id=$1 ORDER BY id', [
definitionId,
])
).rows
).toEqual(beforeHistorySelection);
// A real missing row, not an invented empty result.
await f.page.goto(`${f.origin}/backtests/${definitionId}/run/${randomUUID()}`);
await visible(f.page, 'Failed to get run: Not Found');

View file

@ -648,6 +648,164 @@ describe('canonical research workbench', () => {
expect(host.textContent).not.toContain('Canonical');
});
describe('nonblocking run history metrics', () => {
const rows = () => [...host.querySelectorAll('tbody tr[data-index]')];
const view = (runs: Run[], onSelectRun = (_id: string) => {}) =>
createElement(
VirtuosoMockContext.Provider,
{ value: { viewportHeight: 1000, itemHeight: 40 } },
createElement(RunsListWithMetrics, { runs, onSelectRun })
);
const update = (runs: Run[]) =>
flush(() =>
root!.render(
createElement(
router.MemoryRouter,
{ initialEntries: ['/'] },
view(runs),
createElement(Probe)
)
)
);
const resultFor = (run: Run, totalReturn: number) => {
const value = report();
value.runId = run.id;
value.backtestId = run.backtestId;
value.analytics.metrics.totalReturn = totalReturn;
return value;
};
test('pending metrics leave every current row visible and selectable without submitting', async () => {
const selected: string[] = [];
const runs = [
completedRun(),
completedRun({ id: 'failed', runNumber: 2, status: 'failed' }),
completedRun({ id: 'active', runNumber: 3, status: 'pending', progress: 0 }),
];
await mount(view(runs, id => selected.push(id)));
expect(request('/api/v2/runs/run/results')).toBeTruthy();
expect(rows()).toHaveLength(3);
expect(rows()[0]!.textContent).toContain('Loading metrics...');
expect(rows()[0]!.querySelectorAll('td')[3]!.textContent).toBe('-');
expect(rows()[1]!.textContent).toContain('Failed');
expect(rows()[2]!.textContent).toContain('Pending');
await flush(() => (rows()[1] as HTMLElement).click());
expect(selected).toEqual(['failed']);
expect(requests).toHaveLength(1);
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test('status polls and another completion preserve pending reads and publish healthy metrics independently', async () => {
const first = completedRun();
const slow = completedRun({ id: 'slow', runNumber: 2 });
const active = completedRun({ id: 'active', runNumber: 3, status: 'running', progress: 20 });
await mount(view([first, slow, active]));
const firstRead = request('/api/v2/runs/run/results');
const slowRead = request('/api/v2/runs/slow/results');
await update([{ ...first }, { ...slow }, { ...active, status: 'paused', progress: 40 }]);
expect(requests).toHaveLength(2);
expect(firstRead.signal?.aborted).toBe(false);
expect(slowRead.signal?.aborted).toBe(false);
expect(rows()[2]!.textContent).toContain('Paused');
expect(rows()[2]!.textContent).toContain('40%');
await flush(() => reply(firstRead, resultFor(first, 0.125)));
expect(rows()[0]!.textContent).toContain('12.50%');
expect(rows()[1]!.textContent).toContain('Loading metrics...');
await update([first, slow, { ...active, status: 'completed', progress: 100 }]);
expect(requests).toHaveLength(3);
expect(request('/api/v2/runs/active/results')).toBeTruthy();
expect(slowRead.signal?.aborted).toBe(false);
expect(rows()[0]!.textContent).toContain('12.50%');
await flush(() => reply(slowRead, resultFor(slow, 0.25)));
expect(rows()[1]!.textContent).toContain('25.00%');
expect(rows()[2]!.textContent).toContain('Loading metrics...');
});
test('failed metrics stay unavailable until explicit row-local retry without navigation or duplicate reads', async () => {
const selected: string[] = [];
const first = completedRun();
const healthy = completedRun({ id: 'healthy', runNumber: 2 });
await mount(view([first, healthy], id => selected.push(id)));
await flush(() => {
reply(request('/api/v2/runs/run/results'), { error: 'Result store offline' }, 503);
reply(request('/api/v2/runs/healthy/results'), resultFor(healthy, 0.25));
});
expect(rows()).toHaveLength(2);
expect(rows()[0]!.textContent).toContain('Metrics unavailable');
expect(rows()[0]!.querySelector('[title="Result store offline"]')).not.toBeNull();
expect(rows()[0]!.querySelectorAll('td')[3]!.textContent).toBe('-');
expect(rows()[1]!.textContent).toContain('25.00%');
const retry = button('Retry metrics for run 1');
await flush(() => {
retry.click();
retry.click();
});
expect(selected).toEqual([]);
expect(requests).toHaveLength(3);
expect(requests.filter(item => item.path === '/api/v2/runs/healthy/results')).toHaveLength(1);
expect(rows()[0]!.textContent).toContain('Loading metrics...');
await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(first, 0.125)));
expect(rows()[0]!.textContent).toContain('12.50%');
expect(host.textContent).not.toContain('Metrics unavailable');
expect(requests.every(item => item.method === 'GET')).toBe(true);
});
test.each(['removed', 'parent', 'status'] as const)(
'%s collection change fences late metrics and keeps current records authoritative',
async change => {
const original = completedRun();
await mount(view([original]));
const stale = request('/api/v2/runs/run/results');
const current =
change === 'removed'
? []
: [
change === 'parent'
? { ...original, backtestId: 'other-definition' }
: { ...original, status: 'failed' as const },
];
await update(current);
expect(stale.signal?.aborted).toBe(true);
await flush(() => reply(stale, resultFor(original, 1.23)));
expect(host.textContent).not.toContain('123.00%');
expect(rows()).toHaveLength(current.length);
if (change === 'removed') {
expect(host.textContent).toContain('No runs yet');
await update([original]);
expect(rows()[0]!.textContent).toContain('Loading metrics...');
await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(original, 0.25)));
expect(rows()[0]!.textContent).toContain('25.00%');
} else if (change === 'parent') {
expect(rows()[0]!.textContent).toContain('Loading metrics...');
await flush(() =>
reply(request('/api/v2/runs/run/results'), resultFor(current[0]!, 0.25))
);
expect(rows()[0]!.textContent).toContain('25.00%');
} else {
expect(rows()[0]!.textContent).toContain('Failed');
expect(rows()[0]!.textContent).toContain('Not completed');
expect(requests).toHaveLength(1);
}
}
);
test('unmount aborts ownership and a late result cannot affect a remounted history', async () => {
const original = completedRun();
await mount(view([original]));
const stale = request('/api/v2/runs/run/results');
await flush(() => root!.unmount());
root = undefined;
expect(stale.signal?.aborted).toBe(true);
await mount(view([original]));
await flush(() => reply(stale, resultFor(original, 1.23)));
expect(rows()).toHaveLength(1);
expect(rows()[0]!.textContent).toContain('Loading metrics...');
expect(host.textContent).not.toContain('123.00%');
await flush(() => reply(request('/api/v2/runs/run/results'), resultFor(original, 0.25)));
expect(rows()[0]!.textContent).toContain('25.00%');
});
});
test('history uses positive canonical drawdown severity and preserves signed legacy thresholds', async () => {
const cases = [
{ kind: 'canonical', value: 0, color: 'text-success' },