feat(research): retry failed experiment trials with retained history

This commit is contained in:
Boki 2026-10-24 10:56:58 -04:00
parent 6f64ef62ba
commit b373410320
32 changed files with 3336 additions and 61 deletions

View file

@ -294,6 +294,7 @@ export async function fixture(browser: Browser, native = false) {
'20-research-workspace.sql',
'21-run-reproduction.sql',
'22-experiments.sql',
'23-experiment-retries.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -345,6 +346,17 @@ export async function fixture(browser: Browser, native = false) {
const engine = native
? new RustBacktestAdapter({ logger, storage: runStorage }, { timeoutMs: 15000 })
: controlled;
const canonicalFailures: string[] = [];
if (engine instanceof RustBacktestAdapter) {
const executeCanonical = engine.runCanonical.bind(engine);
engine.runCanonical = async (...args) => {
const failure = canonicalFailures.shift();
if (failure) {
throw new Error(failure);
}
return executeCanonical(...args);
};
}
const runner = new BacktestRunner({
engine,
engineName: 'native',
@ -570,6 +582,12 @@ export async function fixture(browser: Browser, native = false) {
frames,
delayResponse,
controlled,
failNextCanonical: (message: string) => {
if (!native) {
throw new Error('A native fixture is required for canonical failure injection');
}
canonicalFailures.push(message);
},
dispatcher,
request,
login,

View file

@ -5,7 +5,12 @@ import {
canonicalResearchSettingsSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { ExperimentDetail, ExperimentPreview } from '@stock-bot/stock-config/experiments';
import type {
ExperimentDetail,
ExperimentPreview,
ExperimentRetryResult,
ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { retainResearchDataset } from '../../scripts/import-research-dataset';
import { canonicalSettings } from '../fixtures/canonical-research';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
@ -31,6 +36,166 @@ afterAll(async () => {
});
const fixture = (native = false) => createFixture(browser, native);
test('failed_experiment_trial_retry_preserves_history_and_reopens_native_result_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());
try {
const { dataset } = canonicalSmaFixture();
await retainResearchDataset(f.pool, dataset);
const selected = (await f.seedCatalog()).find(
item => item.package.program.strategyId === 'sma_crossover'
)!;
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reviewed retained failure/retry fixture',
});
const definition = {
name: 'Retry original inputs',
strategy: 'catalog',
strategyVersionId: selected.id,
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
symbols: dataset.manifest.executionSeries.map(series => series.instrumentId),
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
initialCapital: 10000,
config: {
datasetHash: dataset.manifest.hash,
dataFrequency: dataset.manifest.series[0]!.interval,
canonical: canonicalSettings,
},
};
const backtest = await f.request('/api/v2/backtests', 'POST', {
...definition,
autoStart: false,
});
const input = { backtestId: backtest.id, name: 'Recovered experiment', grid: {} };
const { preview } = (await f.request('/api/v2/experiments/preview', 'POST', input)) as {
preview: ExperimentPreview;
};
const { experiment } = (await f.request(
'/api/v2/experiments',
'POST',
{ ...input, previewHash: preview.previewHash },
{ 'Idempotency-Key': randomUUID() }
)) as { experiment: ExperimentDetail };
const runId = experiment.trials[0]!.runId!;
f.failNextCanonical('Injected canonical worker failure before financial replay');
f.dispatcher.start();
await until(
async () =>
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status ===
'failed',
'original canonical attempt fails durably'
);
const failed = (
await f.pool.query(
`SELECT *,to_char(completed_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS completed_at_exact
FROM runs WHERE id=$1`,
[runId]
)
).rows[0];
expect(failed.attempt_number).toBe(1);
expect(failed.manual_retry_count).toBe(0);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(0);
// A retry uses the original request even after edits and a later approval.
await f.request(`/api/v2/backtests/${backtest.id}`, 'PUT', {
...definition,
name: 'Changed template after failure',
initialCapital: 20000,
strategyParameters: { fastPeriod: 1, slowPeriod: 2 },
});
await f.request(`/api/v2/strategy-versions/${selected.id}/reviews`, 'POST', {
decision: 'approve',
reason: 'Reapproved original version for the manual retry',
});
await f.login();
await f.page.goto(`${f.origin}/experiments/${experiment.id}`);
await visible(f.page, /failed: 1/);
await f.page.getByRole('button', { name: 'Retry trial 1', exact: true }).click();
const retrying = f.page.waitForResponse(response =>
response.url().endsWith(`/experiments/${experiment.id}/trials/${runId}/retry`)
);
await f.page.getByRole('button', { name: 'Confirm retry trial 1', exact: true }).click();
const response = await retrying;
expect(response.status()).toBe(202);
expect(response.request().postDataJSON()).toEqual({
expectedAttemptNumber: 1,
expectedRetryCount: 0,
});
const accepted = (await response.json()) as ExperimentRetryResult;
expect(accepted.retry.runId).toBe(runId);
expect(accepted.retry.previousAttemptId).toBe(failed.attempt_id);
expect(accepted.retry.previousAttemptNumber).toBe(1);
expect(accepted.retry.retryNumber).toBe(1);
expect(accepted.retry.error).toBe(failed.error);
expect(accepted.retry.completedAt).toBe(failed.completed_at_exact);
expect(accepted.retry.reviewId).not.toBe(failed.request_snapshot.strategy.reviewId);
await until(
async () =>
(await f.pool.query('SELECT status FROM runs WHERE id=$1', [runId])).rows[0].status ===
'completed',
'retried trial redispatches and completes in the native engine'
);
const complete = (await f.pool.query('SELECT * FROM runs WHERE id=$1', [runId])).rows[0];
expect(complete.attempt_number).toBe(2);
expect(complete.attempt_id).not.toBe(failed.attempt_id);
expect(complete.manual_retry_count).toBe(1);
expect(complete.request_snapshot).toEqual(failed.request_snapshot);
expect(complete.dataset_hash).toBe(failed.dataset_hash);
expect(complete.trial_key).toBe(failed.trial_key);
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
expect((await f.pool.query('SELECT * FROM backtest_results')).rowCount).toBe(1);
const replay = await f.page.evaluate(
async ({ path, key, body }) => {
const reply = await fetch(path, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': key,
},
body: JSON.stringify(body),
});
return { status: reply.status, body: await reply.json() };
},
{
path: `/api/v2/experiments/${experiment.id}/trials/${runId}/retry`,
key: response.request().headers()['idempotency-key']!,
body: response.request().postDataJSON(),
}
);
expect(replay.status).toBe(202);
expect(replay.body.retry.id).toBe(accepted.retry.id);
await f.page.getByRole('button', { name: 'Refresh experiment', exact: true }).click();
await visible(f.page, /completed: 1/);
expect(await f.page.getByRole('cell', { name: 'Comparable', exact: true }).count()).toBe(1);
await f.page
.getByRole('button', { name: 'Show retry history for trial 1', exact: true })
.click();
await visible(f.page, /Injected canonical worker failure before financial replay/);
const { retries } = (await f.request(
`/api/v2/experiments/${experiment.id}/trials/${runId}/retries`
)) as {
retries: ExperimentTrialRetry[];
};
expect(retries).toEqual([accepted.retry]);
await f.page.reload();
await visible(f.page, /completed: 1/);
await f.page
.getByRole('button', { name: 'Show retry history for trial 1', exact: true })
.click();
await visible(f.page, /Injected canonical worker failure before financial replay/);
await f.page.locator(`a[href="/backtests/${backtest.id}/run/${runId}"]`).click();
await visible(f.page, 'Canonical research result');
const result = (await f.request(`/api/v2/runs/${runId}/results`)) as CanonicalRunResult;
expect(result.request).toEqual(failed.request_snapshot);
expect(f.historicalDataReads).toEqual([]);
expect(f.unexpectedNetwork).toEqual([]);
} finally {
await f.close();
}
});
test('retained_experiment_preview_submit_compare_cancel_and_reopen_browser', async () => {
const f = await fixture(true);
f.page.on('dialog', dialog => void dialog.accept());