feat(research): retry failed experiment trials with retained history
This commit is contained in:
parent
6f64ef62ba
commit
b373410320
32 changed files with 3336 additions and 61 deletions
|
|
@ -7,8 +7,10 @@ import type {
|
|||
ExperimentDetail,
|
||||
ExperimentInput,
|
||||
ExperimentPreview,
|
||||
ExperimentRetryResult,
|
||||
ExperimentSummary,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { HistoricalDataRequestError, type CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
|
|
@ -25,6 +27,8 @@ import {
|
|||
PREVIEW_RUN_ID,
|
||||
retainedExperimentPreview,
|
||||
} from './experiment-input';
|
||||
import { mapExperimentRetry, parseExperimentRetry, retryColumns } from './experiment-retry';
|
||||
import { RunReproductionError, verifyReproductionInputs } from './run-reproduction';
|
||||
import { StrategyCatalogError } from './strategy-catalog.service';
|
||||
|
||||
interface Query {
|
||||
|
|
@ -289,6 +293,185 @@ export class ExperimentsService {
|
|||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async listTrialRetries(id: string, runId: string): Promise<ExperimentTrialRetry[]> {
|
||||
experimentId(id);
|
||||
experimentId(runId);
|
||||
const experiment = (
|
||||
await this.database.query('SELECT id FROM research_experiments WHERE id=$1', [id])
|
||||
).rows[0];
|
||||
if (!experiment) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const run = (await this.database.query('SELECT experiment_id FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0];
|
||||
if (!run) {
|
||||
throw new ExperimentError(404, 'Trial run not found');
|
||||
}
|
||||
if (run.experiment_id !== id) {
|
||||
throw new ExperimentError(409, 'Run does not belong to this experiment');
|
||||
}
|
||||
return (
|
||||
await this.database.query(
|
||||
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.run_id=$1 ORDER BY h.retry_number`,
|
||||
[runId]
|
||||
)
|
||||
).rows.map(mapExperimentRetry);
|
||||
}
|
||||
async retryTrial(
|
||||
id: string,
|
||||
runId: string,
|
||||
raw: unknown,
|
||||
actor: { principal: string; key: string }
|
||||
): Promise<ExperimentRetryResult> {
|
||||
experimentId(id);
|
||||
experimentId(runId);
|
||||
const input = parseExperimentRetry(raw);
|
||||
const receipt = experimentReceipt(actor);
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'retry-experiment-trial',
|
||||
experimentId: id,
|
||||
runId,
|
||||
...input,
|
||||
});
|
||||
return this.database.transaction(async client => {
|
||||
const replay = async (): Promise<ExperimentRetryResult | null> => {
|
||||
const saved = (
|
||||
await client.query(
|
||||
`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.principal=$1 AND h.submission_key=$2`,
|
||||
[receipt.principal, receipt.key]
|
||||
)
|
||||
).rows[0];
|
||||
if (!saved) {
|
||||
return null;
|
||||
}
|
||||
if (saved.submission_hash !== hash) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Idempotency-Key already belongs to a different trial retry intent'
|
||||
);
|
||||
}
|
||||
return {
|
||||
retry: mapExperimentRetry(saved),
|
||||
experiment: await this.readDetail(client, saved.experiment_id),
|
||||
};
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
// Same ordering as admission, followed by the existing original-family verification lock.
|
||||
const parent = (
|
||||
await client.query(
|
||||
'SELECT id,archived_at FROM backtests WHERE id=(SELECT backtest_id FROM research_experiments WHERE id=$1) FOR UPDATE',
|
||||
[id]
|
||||
)
|
||||
).rows[0];
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
if (!parent) {
|
||||
throw new ExperimentError(404, 'Experiment not found');
|
||||
}
|
||||
const experiment = (
|
||||
await client.query('SELECT * FROM research_experiments WHERE id=$1 FOR UPDATE', [id])
|
||||
).rows[0];
|
||||
const run = (
|
||||
await client.query('SELECT * FROM runs WHERE id=$1 AND experiment_id=$2 FOR UPDATE', [
|
||||
runId,
|
||||
id,
|
||||
])
|
||||
).rows[0];
|
||||
if (!run) {
|
||||
const exists = (await client.query('SELECT id FROM runs WHERE id=$1', [runId])).rows.length;
|
||||
throw new ExperimentError(
|
||||
exists ? 409 : 404,
|
||||
exists ? 'Run does not belong to this experiment' : 'Trial run not found'
|
||||
);
|
||||
}
|
||||
if (
|
||||
parent.archived_at !== null ||
|
||||
experiment.cancel_requested ||
|
||||
run.cancel_requested ||
|
||||
run.status !== 'failed'
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'Retry requires an active backtest and a failed, uncancelled experiment trial'
|
||||
);
|
||||
}
|
||||
if (
|
||||
run.attempt_number !== input.expectedAttemptNumber ||
|
||||
run.manual_retry_count !== input.expectedRetryCount
|
||||
) {
|
||||
throw new ExperimentError(
|
||||
409,
|
||||
'The trial failure changed; refresh before requesting a new retry'
|
||||
);
|
||||
}
|
||||
if (run.manual_retry_count === 2147483647 || run.attempt_number === 2147483647) {
|
||||
throw new ExperimentError(409, 'Trial attempt or retry counter is exhausted');
|
||||
}
|
||||
if (
|
||||
(await client.query('SELECT 1 FROM backtest_results WHERE run_id=$1', [runId])).rows.length
|
||||
) {
|
||||
throw new ExperimentError(409, 'A run with a retained result cannot be retried');
|
||||
}
|
||||
const preview = retainedExperimentPreview(experiment.preview);
|
||||
const candidate = preview.candidates[run.trial_index];
|
||||
if (!candidate || candidate.trialKey !== run.trial_key || run.backtest_id !== parent.id) {
|
||||
throw new ExperimentError(409, 'Trial does not match its retained experiment candidate');
|
||||
}
|
||||
const request = experimentTrialRequest(preview, candidate, runId);
|
||||
if (!equal(request, run.request_snapshot) || request.datasetHash !== run.dataset_hash) {
|
||||
throw new ExperimentError(409, 'Trial frozen request does not match its experiment');
|
||||
}
|
||||
let reviewId;
|
||||
try {
|
||||
reviewId = await verifyReproductionInputs(client, this.container, request);
|
||||
} catch (error) {
|
||||
if (error instanceof RunReproductionError) {
|
||||
throw new ExperimentError(409, error.message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const retryId = randomUUID();
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO experiment_trial_retries
|
||||
(id,experiment_id,run_id,trial_key,retry_number,previous_attempt_number,previous_attempt_id,error,progress,current_simulation_date,
|
||||
started_at,completed_at,paused_at,failure_updated_at,principal,review_id,submission_key,submission_hash)
|
||||
SELECT $1,experiment_id,id,trial_key,manual_retry_count+1,attempt_number,attempt_id,error,progress,current_simulation_date,
|
||||
started_at,completed_at,paused_at,updated_at,$3,$4,$5,$6 FROM runs WHERE id=$2
|
||||
ON CONFLICT (principal,submission_key) DO NOTHING RETURNING id`,
|
||||
[retryId, runId, receipt.principal, reviewId, receipt.key, hash]
|
||||
);
|
||||
if (!inserted.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent retry receipt disappeared');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE runs SET status='pending',manual_retry_count=manual_retry_count+1,
|
||||
attempt_id=NULL,lease_expires_at=NULL,error=NULL,current_simulation_date=NULL,started_at=NULL,completed_at=NULL,paused_at=NULL,
|
||||
progress=0,updated_at=NOW() WHERE id=$1`,
|
||||
[runId]
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO backtest_dispatch (run_id,next_publish_at) VALUES ($1,NOW())
|
||||
ON CONFLICT (run_id) DO UPDATE SET next_publish_at=NOW()`,
|
||||
[runId]
|
||||
);
|
||||
const saved = (
|
||||
await client.query(`SELECT ${retryColumns} FROM experiment_trial_retries h WHERE h.id=$1`, [
|
||||
retryId,
|
||||
])
|
||||
).rows[0];
|
||||
return { retry: mapExperimentRetry(saved), experiment: await this.readDetail(client, id) };
|
||||
});
|
||||
}
|
||||
private async readDetail(database: Query, id: string): Promise<ExperimentDetail> {
|
||||
const row = (
|
||||
await database.query(
|
||||
|
|
@ -303,7 +486,7 @@ export class ExperimentsService {
|
|||
// Deliberately project only compact result metadata; never load financial, trades, OHLC or return arrays.
|
||||
const runs = (
|
||||
await database.query(
|
||||
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
|
||||
`SELECT r.id,r.backtest_id,r.trial_index,r.trial_key,r.status,r.attempt_number,r.manual_retry_count,r.progress,r.cancel_requested,r.error,r.dataset_hash,r.request_snapshot,
|
||||
br.canonical_result->>'kind' AS result_kind,br.canonical_result->>'status' AS result_status,
|
||||
br.canonical_result->>'runId' AS result_run_id,br.canonical_result->>'backtestId' AS result_backtest_id,
|
||||
br.canonical_result->>'financialEngine' AS financial_engine,br.canonical_result->>'strategyExecution' AS strategy_execution,
|
||||
|
|
@ -321,6 +504,8 @@ export class ExperimentsService {
|
|||
const trial: ExperimentTrial = {
|
||||
...candidate,
|
||||
runId: run?.id ?? null,
|
||||
attemptNumber: run ? Number(run.attempt_number) : 0,
|
||||
retryCount: run ? Number(run.manual_retry_count) : 0,
|
||||
status: run?.status ?? 'missing',
|
||||
progress: Number(run?.progress ?? 0),
|
||||
cancelRequested: run?.cancel_requested ?? false,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue