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

@ -62,7 +62,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '19-canonical-research.sql' ||
f === '20-research-workspace.sql' ||
f === '21-run-reproduction.sql' ||
f === '22-experiments.sql')
f === '22-experiments.sql' ||
f === '23-experiment-retries.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -10,6 +10,7 @@ import {
parseExperimentInput,
parseExperimentSubmission,
} from '../services/experiment-input';
import { parseExperimentRetry } from '../services/experiment-retry';
import { ExperimentsService } from '../services/experiments.service';
/** Mounted HTTP security owns read authorization; every mutation additionally requires credential proof. */
@ -77,5 +78,25 @@ export function createExperimentRoutes(container: IServiceContainer) {
}
return c.json({ experiment: await service.cancel(id) });
});
app.get('/api/v2/experiments/:id/trials/:runId/retries', async c =>
c.json({
retries: await service.listTrialRetries(
experimentId(c.req.param('id')),
experimentId(c.req.param('runId'))
),
})
);
app.post('/api/v2/experiments/:id/trials/:runId/retry', async c => {
const id = experimentId(c.req.param('id')),
runId = experimentId(c.req.param('runId'));
const input = parseExperimentRetry(await body(c.req.raw));
const receipt = experimentReceipt({
principal: getCredentialHttpPrincipal(c.req.raw) ?? '',
key: c.req.header('Idempotency-Key') ?? '',
});
const result = await service.retryTrial(id, runId, input, receipt);
c.header('Location', `/api/v2/experiments/${id}`);
return c.json(result, 202);
});
return app;
}

View file

@ -0,0 +1,45 @@
import type { QueryResultRow } from 'pg';
import {
experimentRetrySchema,
type ExperimentRetryInput,
type ExperimentTrialRetry,
} from '@stock-bot/stock-config/experiments';
import { ExperimentError } from './experiment-input';
export function parseExperimentRetry(input: unknown): ExperimentRetryInput {
const parsed = experimentRetrySchema.safeParse(input);
if (!parsed.success) {
throw new ExperimentError(
400,
'Retry requires the observed nonnegative attempt number and retry count only'
);
}
return parsed.data;
}
/** Format in SQL to preserve PostgreSQL microseconds, including pre-JavaScript failure timestamps. */
const timestamp = (column: string) =>
`to_char(h.${column} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS ${column}`;
export const retryColumns = `h.id,h.experiment_id,h.run_id,h.trial_key,h.retry_number,h.previous_attempt_number,h.previous_attempt_id,
h.error,h.progress,h.principal,h.review_id,h.submission_key,h.submission_hash,
${['current_simulation_date', 'started_at', 'completed_at', 'paused_at', 'failure_updated_at', 'recorded_at'].map(timestamp).join(',')}`;
export function mapExperimentRetry(row: QueryResultRow): ExperimentTrialRetry {
return {
id: row.id,
experimentId: row.experiment_id,
runId: row.run_id,
trialKey: row.trial_key,
retryNumber: row.retry_number,
previousAttemptNumber: row.previous_attempt_number,
previousAttemptId: row.previous_attempt_id,
error: row.error,
progress: Number(row.progress),
currentDate: row.current_simulation_date,
startedAt: row.started_at,
completedAt: row.completed_at,
pausedAt: row.paused_at,
failureUpdatedAt: row.failure_updated_at,
recordedAt: row.recorded_at,
principal: row.principal,
reviewId: row.review_id,
};
}

View file

@ -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,