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
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
369
test/integration/experiment-retries-api.test.ts
Normal file
369
test/integration/experiment-retries-api.test.ts
Normal file
|
|
@ -0,0 +1,369 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { createExperimentRoutes } from '../../apps/stock/web-api/src/routes/experiments.routes';
|
||||
import {
|
||||
buildExperimentPreview,
|
||||
experimentHash,
|
||||
PREVIEW_RUN_ID,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
const tokens = {
|
||||
operator: 'experiment-admin-fixture-not-a-real-secret-1234',
|
||||
service: 'experiment-service-fixture-not-a-real-secret-1234',
|
||||
read: 'experiment-read-fixture-not-a-real-secret-1234',
|
||||
};
|
||||
const backtestId = randomUUID(),
|
||||
experimentId = randomUUID();
|
||||
const input = { backtestId, name: 'Sweep', grid: { fastPeriod: [1, 2] } };
|
||||
type Query = (sql: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;
|
||||
function fixture(
|
||||
mode: 'enabled' | 'disabled' | 'absent' = 'enabled',
|
||||
query: Query = async () => ({ rows: [] })
|
||||
) {
|
||||
const client = { query: mock(query) };
|
||||
const database = {
|
||||
...client,
|
||||
transaction: mock(async <T>(work: (client: { query: Query }) => Promise<T>) => work(client)),
|
||||
};
|
||||
const app = new Hono();
|
||||
if (mode !== 'absent') {
|
||||
createHttpSecurity({
|
||||
adminToken: tokens.operator,
|
||||
serviceToken: tokens.service,
|
||||
readToken: tokens.read,
|
||||
environment: 'test',
|
||||
hostname: '127.0.0.1',
|
||||
disabled: mode === 'disabled',
|
||||
}).mount(app);
|
||||
}
|
||||
app.route('/', createExperimentRoutes({ postgres: database } as unknown as IServiceContainer));
|
||||
return {
|
||||
database,
|
||||
request(path = '', method = 'GET', body?: string, role?: keyof typeof tokens, key?: string) {
|
||||
return app.request(`/api/v2/experiments${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(role ? { Authorization: `Bearer ${tokens[role]}` } : {}),
|
||||
...(key === undefined ? {} : { 'Idempotency-Key': key }),
|
||||
},
|
||||
...(body === undefined ? {} : { body }),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
function retainedPreview() {
|
||||
const version = randomUUID(),
|
||||
owner = `strategy:${version}`;
|
||||
const fixture = canonicalSmaFixture([owner]);
|
||||
const descriptor = builtinCatalogDescriptors[0]!;
|
||||
const policy = structuredClone(fixture.config);
|
||||
policy.matching.risk.ledger.sessionId = PREVIEW_RUN_ID;
|
||||
policy.matching.risk.ledger.accountId = `research:${PREVIEW_RUN_ID}`;
|
||||
const request = canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: PREVIEW_RUN_ID,
|
||||
backtestId,
|
||||
name: 'Template',
|
||||
strategy: {
|
||||
familyId: randomUUID(),
|
||||
versionId: version,
|
||||
origin: 'builtin',
|
||||
reviewId: randomUUID(),
|
||||
package: {
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'fixture',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
},
|
||||
selection: fixture.selections[0],
|
||||
},
|
||||
datasetHash: fixture.dataset.manifest.hash,
|
||||
policy,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: 'fixture',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
});
|
||||
return buildExperimentPreview(input, request, fixture.dataset.manifest);
|
||||
}
|
||||
|
||||
const runId = randomUUID();
|
||||
const retryBody = { expectedAttemptNumber: 1, expectedRetryCount: 0 };
|
||||
const path = `/${experimentId}/trials/${runId}`;
|
||||
function savedRetry(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: randomUUID(),
|
||||
experiment_id: experimentId,
|
||||
run_id: runId,
|
||||
trial_key: 'a'.repeat(64),
|
||||
retry_number: 1,
|
||||
previous_attempt_number: 1,
|
||||
previous_attempt_id: null,
|
||||
error: null,
|
||||
progress: '14.25',
|
||||
current_simulation_date: null,
|
||||
started_at: null,
|
||||
completed_at: '2026-10-24T10:00:00.123456Z',
|
||||
paused_at: null,
|
||||
failure_updated_at: '2026-10-24T10:00:00.654321Z',
|
||||
recorded_at: '2026-10-24T10:00:01.000001Z',
|
||||
principal: 'operator',
|
||||
review_id: randomUUID(),
|
||||
submission_hash: 'a'.repeat(64),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
function detailRow(preview: ReturnType<typeof retainedPreview>) {
|
||||
return {
|
||||
id: experimentId,
|
||||
backtest_id: backtestId,
|
||||
name: input.name,
|
||||
created_at: '2026-10-24T00:00:00Z',
|
||||
cancel_requested: true,
|
||||
trial_count: 2,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
strategy_version_id: preview.request.strategy.versionId,
|
||||
preview_hash: preview.previewHash,
|
||||
counts: {},
|
||||
preview,
|
||||
};
|
||||
}
|
||||
|
||||
describe('failed trial retry HTTP contract', () => {
|
||||
test('credential proof/read role/strict body/counters/IDs/receipt key gate storage', async () => {
|
||||
for (const mode of ['enabled', 'disabled', 'absent'] as const) {
|
||||
const f = fixture(mode);
|
||||
expect(
|
||||
(await f.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), undefined, 'key'))
|
||||
.status
|
||||
).toBe(401);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
const read = fixture();
|
||||
expect(
|
||||
(await read.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'read', 'key')).status
|
||||
).toBe(403);
|
||||
expect((await read.request(`${path}/retries`)).status).toBe(401);
|
||||
for (const [target, body, key] of [
|
||||
[path, '{}', 'key'],
|
||||
[path, '{', 'key'],
|
||||
[path, JSON.stringify({ ...retryBody, expectedRetryCount: -1 }), 'key'],
|
||||
[path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 1.5 }), 'key'],
|
||||
[path, JSON.stringify({ ...retryBody, expectedAttemptNumber: 2147483648 }), 'key'],
|
||||
[path, JSON.stringify({ ...retryBody, parameters: { fastPeriod: 2 } }), 'key'],
|
||||
[path, JSON.stringify(retryBody), undefined],
|
||||
[path, JSON.stringify(retryBody), 'bad key'],
|
||||
[path, JSON.stringify(retryBody), 'x'.repeat(201)],
|
||||
[`/bad/trials/${runId}`, JSON.stringify(retryBody), 'key'],
|
||||
[`/${experimentId}/trials/bad`, JSON.stringify(retryBody), 'key'],
|
||||
]) {
|
||||
const f = fixture();
|
||||
expect((await f.request(`${target}/retry`, 'POST', body, 'operator', key)).status).toBe(400);
|
||||
expect(f.database.query.mock.calls).toHaveLength(0);
|
||||
expect(f.database.transaction.mock.calls).toHaveLength(0);
|
||||
}
|
||||
expect(
|
||||
(await read.request(`/${experimentId}/trials/bad/retries`, 'GET', undefined, 'read')).status
|
||||
).toBe(400);
|
||||
});
|
||||
test('accepted receipt replay returns202/current detail before current eligibility and preserves historical timestamp precision', async () => {
|
||||
const preview = retainedPreview();
|
||||
const hash = experimentHash({
|
||||
version: 1,
|
||||
operation: 'retry-experiment-trial',
|
||||
experimentId,
|
||||
runId,
|
||||
...retryBody,
|
||||
});
|
||||
for (const principal of ['operator', 'service'] as const) {
|
||||
const saved = savedRetry({
|
||||
principal,
|
||||
submission_hash: hash,
|
||||
trial_key: preview.candidates[0]!.trialKey,
|
||||
});
|
||||
const f = fixture('enabled', async (sql, values) => {
|
||||
if (sql.includes('h.principal=$1')) {
|
||||
expect(values).toEqual([principal, 'accepted']);
|
||||
return { rows: [saved] };
|
||||
}
|
||||
if (sql.includes('SELECT r.id')) {
|
||||
return { rows: [] };
|
||||
}
|
||||
expect(sql).not.toContain('FROM backtests');
|
||||
expect(sql).not.toContain('FOR UPDATE');
|
||||
return { rows: [detailRow(preview)] };
|
||||
});
|
||||
const response = await f.request(
|
||||
`${path}/retry`,
|
||||
'POST',
|
||||
JSON.stringify(retryBody),
|
||||
principal,
|
||||
'accepted'
|
||||
);
|
||||
expect(response.status).toBe(202);
|
||||
expect(response.headers.get('Location')).toBe(`/api/v2/experiments/${experimentId}`);
|
||||
expect(response.headers.get('Cache-Control')).toBe('no-store');
|
||||
const result = await response.json();
|
||||
expect(result.retry).toMatchObject({
|
||||
id: saved.id,
|
||||
runId,
|
||||
experimentId,
|
||||
principal,
|
||||
previousAttemptId: null,
|
||||
error: null,
|
||||
progress: 14.25,
|
||||
completedAt: '2026-10-24T10:00:00.123456Z',
|
||||
failureUpdatedAt: '2026-10-24T10:00:00.654321Z',
|
||||
});
|
||||
expect(result.experiment.cancelRequested).toBe(true);
|
||||
expect(result.experiment.trials[0]).toMatchObject({
|
||||
status: 'missing',
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
});
|
||||
expect(result.retry).not.toHaveProperty('submission_hash');
|
||||
}
|
||||
});
|
||||
test('history returns ordered immutable snapshots and membership uses404/409 without accepting another experiment', async () => {
|
||||
const saved = savedRetry();
|
||||
const f = fixture('enabled', async sql => {
|
||||
if (sql.includes('SELECT id FROM research_experiments')) {
|
||||
return { rows: [{ id: experimentId }] };
|
||||
}
|
||||
if (sql.includes('SELECT experiment_id FROM runs')) {
|
||||
return { rows: [{ experiment_id: experimentId }] };
|
||||
}
|
||||
expect(sql).toContain('ORDER BY h.retry_number');
|
||||
expect(sql).not.toContain('canonical_result');
|
||||
return { rows: [saved] };
|
||||
});
|
||||
const response = await f.request(`${path}/retries`, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(200);
|
||||
expect((await response.json()).retries[0]).toMatchObject({ id: saved.id, retryNumber: 1 });
|
||||
const missing = fixture();
|
||||
expect((await missing.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(404);
|
||||
const wrong = fixture('enabled', async sql => ({
|
||||
rows: sql.includes('research_experiments')
|
||||
? [{ id: experimentId }]
|
||||
: [{ experiment_id: randomUUID() }],
|
||||
}));
|
||||
expect((await wrong.request(`${path}/retries`, 'GET', undefined, 'read')).status).toBe(409);
|
||||
});
|
||||
test('conflict/missing/stale are explicit and arbitrary database/schema faults remain sanitized500', async () => {
|
||||
const conflict = fixture('enabled', async () => ({ rows: [savedRetry()] }));
|
||||
expect(
|
||||
(
|
||||
await conflict.request(
|
||||
`${path}/retry`,
|
||||
'POST',
|
||||
JSON.stringify(retryBody),
|
||||
'operator',
|
||||
'key'
|
||||
)
|
||||
).status
|
||||
).toBe(409);
|
||||
const missing = fixture();
|
||||
expect(
|
||||
(await missing.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key'))
|
||||
.status
|
||||
).toBe(404);
|
||||
const stale = fixture('enabled', async sql => {
|
||||
if (sql.includes('experiment_trial_retries')) {
|
||||
return { rows: [] };
|
||||
}
|
||||
if (sql.includes('FROM backtests')) {
|
||||
return { rows: [{ id: backtestId, archived_at: null }] };
|
||||
}
|
||||
if (sql.includes('FROM research_experiments')) {
|
||||
return { rows: [{ id: experimentId, cancel_requested: false }] };
|
||||
}
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: runId,
|
||||
experiment_id: experimentId,
|
||||
status: 'failed',
|
||||
cancel_requested: false,
|
||||
attempt_number: 1,
|
||||
manual_retry_count: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
expect(
|
||||
(await stale.request(`${path}/retry`, 'POST', JSON.stringify(retryBody), 'operator', 'key'))
|
||||
.status
|
||||
).toBe(409);
|
||||
for (const failure of [new Error('private connection details'), new z.ZodError([])]) {
|
||||
const f = fixture('enabled', async () => {
|
||||
throw failure;
|
||||
});
|
||||
for (const [suffix, method, body] of [
|
||||
['retry', 'POST', JSON.stringify(retryBody)],
|
||||
['retries', 'GET', undefined],
|
||||
]) {
|
||||
const response = await f.request(`${path}/${suffix}`, method, body, 'operator', 'key');
|
||||
expect(response.status).toBe(500);
|
||||
expect(await response.text()).not.toContain('private');
|
||||
}
|
||||
}
|
||||
});
|
||||
test('counter projection uses the same child rows as statuses rather than previous summary observations', async () => {
|
||||
const preview = retainedPreview();
|
||||
const f = fixture('enabled', async sql =>
|
||||
sql.includes('SELECT r.id')
|
||||
? {
|
||||
rows: [
|
||||
{
|
||||
id: runId,
|
||||
trial_index: 0,
|
||||
trial_key: preview.candidates[0]!.trialKey,
|
||||
status: 'failed',
|
||||
attempt_number: 3,
|
||||
manual_retry_count: 2,
|
||||
progress: 14,
|
||||
cancel_requested: false,
|
||||
error: 'later failure',
|
||||
request_snapshot: null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
backtest_id: backtestId,
|
||||
},
|
||||
],
|
||||
}
|
||||
: { rows: [detailRow(preview)] }
|
||||
);
|
||||
const response = await f.request(`/${experimentId}`, 'GET', undefined, 'read');
|
||||
expect(response.status).toBe(200);
|
||||
expect((await response.json()).experiment.trials[0]).toMatchObject({
|
||||
status: 'failed',
|
||||
attemptNumber: 3,
|
||||
retryCount: 2,
|
||||
error: 'later failure',
|
||||
});
|
||||
});
|
||||
});
|
||||
801
test/integration/experiment-retries-ui.test.tsx
Normal file
801
test/integration/experiment-retries-ui.test.tsx
Normal file
|
|
@ -0,0 +1,801 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
|
||||
import type {
|
||||
ExperimentDetail,
|
||||
ExperimentPreview,
|
||||
ExperimentTrial,
|
||||
ExperimentTrialRetry,
|
||||
} from '@stock-bot/stock-config/experiments';
|
||||
import { builtinCatalogDescriptors } from '@stock-bot/stock-config/strategy';
|
||||
import { nativeReplayFixture } from '../fixtures/native-replay';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'Event', 'ResizeObserver', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let ExperimentDetailPage: typeof import('../../apps/stock/web-app/src/features/experiments').ExperimentDetailPage;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
const backtestId = '11111111-1111-4111-8111-111111111111';
|
||||
const experimentId = '33333333-3333-4333-8333-333333333333';
|
||||
const otherExperimentId = '44444444-4444-4444-8444-444444444444';
|
||||
const versionId = '55555555-5555-4555-8555-555555555555';
|
||||
const runId = (index: number) => `77777777-7777-4777-8777-${String(index + 1).padStart(12, '0')}`;
|
||||
const retryPath = (index = 0, id = experimentId) =>
|
||||
`/api/v2/experiments/${id}/trials/${runId(index)}/retry`;
|
||||
const historyPath = (index = 0, id = experimentId) =>
|
||||
`/api/v2/experiments/${id}/trials/${runId(index)}/retries`;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (cause: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
rawBody: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
signal?: AbortSignal | null;
|
||||
credentials?: RequestCredentials;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
`Missing ${method} ${path}: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, value: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(value, { status }));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function Probe() {
|
||||
navigate = router.useNavigate();
|
||||
location = router.useLocation().pathname;
|
||||
return null;
|
||||
}
|
||||
function preview(count = 2, parent = backtestId): ExperimentPreview {
|
||||
const owner = `strategy:${versionId}`;
|
||||
const { config, dataset } = nativeReplayFixture(3, 1, [owner]);
|
||||
const previewId = '00000000-0000-4000-8000-000000000001';
|
||||
config.matching.risk.ledger.sessionId = previewId;
|
||||
config.matching.risk.ledger.accountId = `research:${previewId}`;
|
||||
const builtin = builtinCatalogDescriptors[0]!;
|
||||
const candidates = Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
trialKey: String(index + 1).padStart(64, '0'),
|
||||
parameters: { fastPeriod: index + 2, slowPeriod: 20 },
|
||||
}));
|
||||
return {
|
||||
version: 'research-experiment-preview/v1',
|
||||
previewHash: 'e'.repeat(64),
|
||||
input: {
|
||||
backtestId: parent,
|
||||
name: 'Trend study',
|
||||
grid: { fastPeriod: candidates.map(item => item.parameters.fastPeriod) },
|
||||
},
|
||||
dataset: dataset.manifest,
|
||||
candidates,
|
||||
request: canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId: previewId,
|
||||
backtestId: parent,
|
||||
name: 'Frozen template name',
|
||||
strategy: {
|
||||
familyId: '66666666-6666-4666-8666-666666666666',
|
||||
versionId,
|
||||
origin: 'builtin',
|
||||
reviewId: '88888888-8888-4888-8888-888888888888',
|
||||
package: {
|
||||
version: 1,
|
||||
program: builtin.program,
|
||||
parameterSchema: builtin.parameterSchema,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: builtin.entryExport,
|
||||
content: 'Never execute fixture code',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: {
|
||||
format: 'bun-lock/v1',
|
||||
content: 'Retained lock',
|
||||
sha256: 'b'.repeat(64),
|
||||
},
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
},
|
||||
selection: {
|
||||
strategyId: builtin.program.strategyId,
|
||||
strategyVersion: builtin.program.strategyVersion,
|
||||
ownerId: owner,
|
||||
seed: 17,
|
||||
instrumentId: 'X0.US',
|
||||
seriesId: 'X0.US:1m',
|
||||
ownerBudget: '100',
|
||||
parameters: { fastPeriod: 2, slowPeriod: 20 },
|
||||
},
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: config,
|
||||
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
|
||||
build: {
|
||||
version: 1,
|
||||
workerSha256: 'a'.repeat(64),
|
||||
engineWrapperSha256: 'b'.repeat(64),
|
||||
engineBinarySha256: 'c'.repeat(64),
|
||||
dependencyLockSha256: 'd'.repeat(64),
|
||||
runtime: 'bun',
|
||||
runtimeVersion: '1.2.17',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
},
|
||||
modelArtifacts: [],
|
||||
}),
|
||||
};
|
||||
}
|
||||
function metrics(): NonNullable<ExperimentTrial['metrics']> {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
cagr: null,
|
||||
maxDrawdown: 0,
|
||||
exposureTime: 0,
|
||||
volatility: null,
|
||||
downsideDeviation: null,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
var95: null,
|
||||
cvar95: null,
|
||||
var99: null,
|
||||
alpha: null,
|
||||
beta: null,
|
||||
informationRatio: null,
|
||||
roundTripCount: null,
|
||||
winRate: null,
|
||||
profitFactor: null,
|
||||
avgWin: null,
|
||||
avgLoss: null,
|
||||
};
|
||||
}
|
||||
function detail(
|
||||
source = preview(),
|
||||
statuses: ExperimentTrial['status'][] = source.candidates.map(() => 'pending')
|
||||
): ExperimentDetail {
|
||||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
status: statuses[index]!,
|
||||
progress: statuses[index] === 'completed' ? 100 : 0,
|
||||
cancelRequested: false,
|
||||
error: statuses[index] === 'failed' ? 'Strategy callback failed' : null,
|
||||
comparable: statuses[index] === 'completed',
|
||||
diagnostic: statuses[index] === 'missing' ? 'Expected child run is missing' : null,
|
||||
metrics: statuses[index] === 'completed' ? metrics() : null,
|
||||
unavailable: statuses[index] === 'completed' ? { sharpeRatio: 'insufficient-periods' } : null,
|
||||
limitations: [],
|
||||
}));
|
||||
return {
|
||||
id: experimentId,
|
||||
name: source.input.name,
|
||||
backtestId: source.input.backtestId,
|
||||
createdAt: '2026-10-24T14:00:00Z',
|
||||
cancelRequested: false,
|
||||
trialCount: trials.length,
|
||||
counts: {
|
||||
pending: 0,
|
||||
running: 0,
|
||||
paused: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
cancelled: 0,
|
||||
...Object.fromEntries(
|
||||
['pending', 'running', 'paused', 'completed', 'failed', 'cancelled'].map(status => [
|
||||
status,
|
||||
trials.filter(item => item.status === status).length,
|
||||
])
|
||||
),
|
||||
},
|
||||
datasetHash: source.request.datasetHash,
|
||||
strategyVersionId: versionId,
|
||||
previewHash: source.previewHash,
|
||||
preview: source,
|
||||
trials,
|
||||
};
|
||||
}
|
||||
|
||||
function failure(attemptNumber = 1, retryCount = 0) {
|
||||
const value = detail(preview(2), ['failed', 'running']);
|
||||
value.trials[0]!.attemptNumber = attemptNumber;
|
||||
value.trials[0]!.retryCount = retryCount;
|
||||
value.trials[0]!.progress = 43;
|
||||
return value;
|
||||
}
|
||||
function transition(value: ExperimentDetail, index: number, change: Partial<ExperimentTrial>) {
|
||||
const next = structuredClone(value);
|
||||
Object.assign(next.trials[index]!, change);
|
||||
if (change.status) {
|
||||
next.trials[index]!.metrics = change.status === 'completed' ? metrics() : null;
|
||||
next.trials[index]!.unavailable = change.status === 'completed' ? {} : null;
|
||||
next.trials[index]!.comparable = change.status === 'completed';
|
||||
}
|
||||
for (const status of [
|
||||
'pending',
|
||||
'running',
|
||||
'paused',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
] as const) {
|
||||
next.counts[status] = next.trials.filter(item => item.status === status).length;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
function receipt(value: ExperimentDetail, index = 0): ExperimentTrialRetry {
|
||||
const trial = value.trials[index]!;
|
||||
return {
|
||||
id: `99999999-9999-4999-8999-${String(trial.retryCount + 1).padStart(12, '0')}`,
|
||||
experimentId: value.id,
|
||||
runId: trial.runId!,
|
||||
trialKey: trial.trialKey,
|
||||
retryNumber: trial.retryCount + 1,
|
||||
previousAttemptNumber: trial.attemptNumber,
|
||||
previousAttemptId: null,
|
||||
error: trial.error,
|
||||
progress: trial.progress,
|
||||
currentDate: null,
|
||||
startedAt: null,
|
||||
completedAt: '2026-10-24T14:00:00.123456Z',
|
||||
pausedAt: null,
|
||||
failureUpdatedAt: '2026-10-24T14:00:00.654321Z',
|
||||
recordedAt: '2026-10-24T14:01:00.000001Z',
|
||||
principal: 'operator',
|
||||
reviewId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
|
||||
};
|
||||
}
|
||||
function accepted(value: ExperimentDetail) {
|
||||
return {
|
||||
retry: receipt(value),
|
||||
experiment: transition(value, 0, {
|
||||
status: 'pending',
|
||||
retryCount: value.trials[0]!.retryCount + 1,
|
||||
error: null,
|
||||
progress: 0,
|
||||
}),
|
||||
};
|
||||
}
|
||||
async function show(value: ExperimentDetail) {
|
||||
root ??= createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(
|
||||
router.MemoryRouter,
|
||||
{ initialEntries: [`/experiments/${value.id}`] },
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/experiments/:experimentId',
|
||||
element: createElement(ExperimentDetailPage),
|
||||
})
|
||||
),
|
||||
createElement(Probe)
|
||||
)
|
||||
)
|
||||
);
|
||||
await flush(() => reply(request(`/api/v2/experiments/${value.id}`), { experiment: value }));
|
||||
}
|
||||
async function start(value = failure()) {
|
||||
await show(value);
|
||||
await flush(() => button('Retry trial 1').click());
|
||||
return value;
|
||||
}
|
||||
async function send(value = failure()) {
|
||||
await start(value);
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
return request(retryPath(), 'POST');
|
||||
}
|
||||
async function lose(post: Pending) {
|
||||
await flush(() => {
|
||||
post.settled = true;
|
||||
post.reject(new Error('Response lost'));
|
||||
});
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
Event: browser.Event,
|
||||
ResizeObserver: browser.ResizeObserver,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ ExperimentDetailPage } = await import('../../apps/stock/web-app/src/features/experiments'));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
Object.defineProperty(browser, 'fetch', {
|
||||
configurable: true,
|
||||
value: (input: unknown, init?: RequestInit) => {
|
||||
const url = new URL(String(input));
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: url.pathname + url.search,
|
||||
method: init?.method ?? 'GET',
|
||||
rawBody: init?.body,
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
headers: new Headers(init?.headers),
|
||||
signal: init?.signal,
|
||||
credentials: init?.credentials,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Deliberately ignore abort to exercise stale-response fences.
|
||||
},
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const old = originals.get(key);
|
||||
if (old) {
|
||||
Object.defineProperty(globalThis, key, old);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('exact failed-trial retry intent', () => {
|
||||
test('review is explicit and duplicate confirmation admits only one exact-counter intent', async () => {
|
||||
const value = await start(failure(3, 2));
|
||||
expect(host.textContent).toContain(
|
||||
'Reviewed failed attempt 3 · prior manual retries 2 · progress 43%'
|
||||
);
|
||||
expect(host.textContent).toContain('Strategy callback failed');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => {
|
||||
button('Confirm retry trial 1').click();
|
||||
button('Confirm retry trial 1').click();
|
||||
});
|
||||
const post = request(retryPath(), 'POST');
|
||||
expect(post.body).toEqual({ expectedAttemptNumber: 3, expectedRetryCount: 2 });
|
||||
expect(post.headers.get('Idempotency-Key')).toBeTruthy();
|
||||
expect(post.credentials).toBe('include');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(button('Refresh experiment').disabled).toBe(true);
|
||||
expect(button('Cancel remaining trials').disabled).toBe(true);
|
||||
await flush(() => reply(post, accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 3 accepted for trial 1');
|
||||
expect(host.textContent).toContain('Attempt 3 · Manual retries 3');
|
||||
expect(host.textContent).not.toContain('Reviewed failed attempt');
|
||||
});
|
||||
test.each(['cancelled-experiment', 'cancelled-run', 'completed', 'missing'] as const)(
|
||||
'%s cannot prepare a fresh retry',
|
||||
async state => {
|
||||
let value = failure();
|
||||
if (state === 'cancelled-experiment') {
|
||||
value.cancelRequested = true;
|
||||
}
|
||||
if (state === 'cancelled-run') {
|
||||
value.trials[0]!.cancelRequested = true;
|
||||
}
|
||||
if (state === 'completed') {
|
||||
value = transition(value, 0, { status: 'completed' });
|
||||
}
|
||||
if (state === 'missing') {
|
||||
value = transition(value, 0, {
|
||||
status: 'missing',
|
||||
runId: null,
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
});
|
||||
}
|
||||
await show(value);
|
||||
expect(host.textContent).not.toContain('Retry trial 1');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
}
|
||||
);
|
||||
test.each(['failed', 'completed', 'cancelled'] as const)(
|
||||
'ambiguous retry keeps exact body/key through refresh to newer %s state and accepts older receipt',
|
||||
async status => {
|
||||
const value = failure(0, 0);
|
||||
const post = await send(value);
|
||||
await lose(post);
|
||||
const newer = transition(value, 0, {
|
||||
status,
|
||||
attemptNumber: 2,
|
||||
retryCount: 2,
|
||||
error: status === 'failed' ? 'Later failure' : null,
|
||||
});
|
||||
if (status === 'cancelled') {
|
||||
newer.cancelRequested = true;
|
||||
newer.trials[0]!.cancelRequested = true;
|
||||
}
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer })
|
||||
);
|
||||
expect(host.textContent).toContain('Reviewed failed attempt 0 · prior manual retries 0');
|
||||
expect(host.textContent).toContain('current trial state has changed');
|
||||
await flush(() => button('Retry same request for trial 1').click());
|
||||
const retry = request(retryPath(), 'POST');
|
||||
expect(retry.rawBody).toBe(post.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, { retry: receipt(value), experiment: newer }, 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted for trial 1');
|
||||
expect(host.textContent).not.toContain('Acceptance is unconfirmed');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(2);
|
||||
if (status === 'failed') {
|
||||
await flush(() => button('Retry trial 1').click());
|
||||
expect(host.textContent).toContain('Reviewed failed attempt 2 · prior manual retries 2');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(2);
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
const fresh = request(retryPath(), 'POST');
|
||||
expect(fresh.body).toEqual({ expectedAttemptNumber: 2, expectedRetryCount: 2 });
|
||||
expect(fresh.headers.get('Idempotency-Key')).not.toBe(post.headers.get('Idempotency-Key'));
|
||||
}
|
||||
}
|
||||
);
|
||||
test('failed detail refresh retains mounted retry intent and same-key recovery', async () => {
|
||||
const value = failure();
|
||||
const post = await send(value);
|
||||
await lose(post);
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}`), { error: 'Read unavailable' }, 500)
|
||||
);
|
||||
expect(host.textContent).toContain('Showing the last loaded state');
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
await flush(() => button('Retry same request for trial 1').click());
|
||||
const retry = request(retryPath(), 'POST');
|
||||
expect(retry.rawBody).toBe(post.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
});
|
||||
test.each([
|
||||
'experiment',
|
||||
'run',
|
||||
'trial-key',
|
||||
'retry-number',
|
||||
'previous-attempt',
|
||||
'partial',
|
||||
'wrong-status',
|
||||
] as const)(
|
||||
'malformed %s acceptance keeps uncertain intent and never changes visible state',
|
||||
async kind => {
|
||||
const value = failure(2, 1);
|
||||
const post = await send(value);
|
||||
const result = accepted(value);
|
||||
if (kind === 'experiment') {
|
||||
result.retry.experimentId = otherExperimentId;
|
||||
}
|
||||
if (kind === 'run') {
|
||||
result.retry.runId = runId(1);
|
||||
}
|
||||
if (kind === 'trial-key') {
|
||||
result.retry.trialKey = 'f'.repeat(64);
|
||||
}
|
||||
if (kind === 'retry-number') {
|
||||
result.retry.retryNumber = 3;
|
||||
}
|
||||
if (kind === 'previous-attempt') {
|
||||
result.retry.previousAttemptNumber = 3;
|
||||
}
|
||||
await flush(() =>
|
||||
reply(
|
||||
post,
|
||||
kind === 'partial'
|
||||
? { retry: { id: result.retry.id }, experiment: result.experiment }
|
||||
: result,
|
||||
kind === 'wrong-status' ? 200 : 202
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('could not be verified');
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
expect(host.textContent).not.toContain('Retry 2 accepted');
|
||||
expect(host.textContent).toContain('Attempt 2 · Manual retries 1');
|
||||
await flush(() => button('Retry same request for trial 1').click());
|
||||
const retry = request(retryPath(), 'POST');
|
||||
expect(retry.rawBody).toBe(post.rawBody);
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key'));
|
||||
}
|
||||
);
|
||||
test.each([400, 401, 404, 409, 500])(
|
||||
'HTTP %s shows explicit failure with no automatic new intent',
|
||||
async status => {
|
||||
const post = await send();
|
||||
await flush(() => reply(post, { error: 'Retry admission refused' }, status));
|
||||
expect(host.textContent).toContain('Retry admission refused');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => false });
|
||||
await flush(() => button('Discard retry request for trial 1').click());
|
||||
expect(host.textContent).toContain('Retry same request for trial 1');
|
||||
Object.defineProperty(browser, 'confirm', { configurable: true, value: () => true });
|
||||
await flush(() => button('Discard retry request for trial 1').click());
|
||||
expect(host.textContent).not.toContain('Reviewed failed attempt');
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
}
|
||||
);
|
||||
test('refresh changing a reviewed but unsubmitted failure requires deliberate fresh review', async () => {
|
||||
const value = await start(failure(0, 1));
|
||||
const newer = transition(value, 0, { retryCount: 2, error: 'New preclaim failure' });
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer }));
|
||||
expect(button('Confirm retry trial 1').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('Reviewed failed attempt 0 · prior manual retries 1');
|
||||
await flush(() => button('Discard retry request for trial 1').click());
|
||||
await flush(() => button('Retry trial 1').click());
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
expect(request(retryPath(), 'POST').body).toEqual({
|
||||
expectedAttemptNumber: 0,
|
||||
expectedRetryCount: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('retry coordination and navigation', () => {
|
||||
test('an active detail refresh disables both retry and cancellation without discarding the review', async () => {
|
||||
const value = await start();
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
expect(button('Confirm retry trial 1').disabled).toBe(true);
|
||||
expect(button('Cancel remaining trials').disabled).toBe(true);
|
||||
await flush(() => {
|
||||
button('Confirm retry trial 1').click();
|
||||
button('Cancel remaining trials').click();
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(0);
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
expect(host.textContent).toContain('Reviewed failed attempt 1');
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
await flush(() => reply(request(retryPath(), 'POST'), accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
});
|
||||
test('cancel and retry share one synchronous mutation gate', async () => {
|
||||
await start();
|
||||
await flush(() => {
|
||||
button('Cancel remaining trials').click();
|
||||
button('Confirm retry trial 1').click();
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
expect(requests.find(item => item.method === 'POST')!.path).toBe(
|
||||
`/api/v2/experiments/${experimentId}/cancel`
|
||||
);
|
||||
expect(button('Confirm retry trial 1').disabled).toBe(true);
|
||||
});
|
||||
test('ambiguous intent survives explicit cancellation and receipt replay afterward', async () => {
|
||||
const value = failure();
|
||||
const post = await send(value);
|
||||
await lose(post);
|
||||
await flush(() => button('Cancel remaining trials').click());
|
||||
let cancelled = transition(value, 0, {
|
||||
status: 'cancelled',
|
||||
retryCount: 1,
|
||||
cancelRequested: true,
|
||||
});
|
||||
cancelled = transition(cancelled, 1, { status: 'cancelled', cancelRequested: true });
|
||||
cancelled.cancelRequested = true;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${experimentId}/cancel`, 'POST'), {
|
||||
experiment: cancelled,
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Acceptance is unconfirmed');
|
||||
await flush(() => button('Retry same request for trial 1').click());
|
||||
const retry = request(retryPath(), 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(post.headers.get('Idempotency-Key'));
|
||||
await flush(() => reply(retry, { retry: receipt(value), experiment: cancelled }, 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
expect(host.textContent).toContain('cancelled: 2');
|
||||
});
|
||||
test('owned navigation warns before discarding an uncertain request and refusal preserves its key', async () => {
|
||||
const post = await send();
|
||||
await lose(post);
|
||||
let prompts = 0;
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
prompts++;
|
||||
return false;
|
||||
},
|
||||
});
|
||||
await flush(() => (host.querySelector('a[href="/experiments"]') as HTMLAnchorElement).click());
|
||||
await flush(() =>
|
||||
(
|
||||
host.querySelector(
|
||||
`a[href="/backtests/${backtestId}/run/${runId(0)}"]`
|
||||
) as HTMLAnchorElement
|
||||
).click()
|
||||
);
|
||||
expect(prompts).toBe(2);
|
||||
expect(location).toBe(`/experiments/${experimentId}`);
|
||||
await flush(() => button('Retry same request for trial 1').click());
|
||||
expect(request(retryPath(), 'POST').headers.get('Idempotency-Key')).toBe(
|
||||
post.headers.get('Idempotency-Key')
|
||||
);
|
||||
});
|
||||
test('late retry success and old detail completion cannot overwrite another route', async () => {
|
||||
const value = failure();
|
||||
const post = await send(value);
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const otherRead = request(`/api/v2/experiments/${otherExperimentId}`);
|
||||
const other = failure();
|
||||
other.id = otherExperimentId;
|
||||
other.name = 'Other experiment';
|
||||
other.preview.input.name = other.name;
|
||||
await flush(() => reply(otherRead, { experiment: other }));
|
||||
await flush(() => reply(post, accepted(value), 202));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Other experiment');
|
||||
expect(host.textContent).not.toContain('Retry 1 accepted');
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const oldRead = request(`/api/v2/experiments/${otherExperimentId}`);
|
||||
await flush(() => navigate(`/experiments/${experimentId}`));
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: value }));
|
||||
await flush(() => reply(oldRead, { experiment: other }));
|
||||
expect(host.querySelector('h1')!.textContent).toBe('Trend study');
|
||||
});
|
||||
test('refresh and confirmation in one event cannot install a stale read over accepted retry state', async () => {
|
||||
const value = await start();
|
||||
await flush(() => {
|
||||
button('Refresh experiment').click();
|
||||
button('Confirm retry trial 1').click();
|
||||
});
|
||||
const post = request(retryPath(), 'POST');
|
||||
await flush(() => reply(post, accepted(value), 202));
|
||||
expect(host.textContent).toContain('Retry 1 accepted');
|
||||
expect(host.textContent).toContain('Attempt 1 · Manual retries 1');
|
||||
expect(host.textContent).not.toContain('Loading experiment...');
|
||||
});
|
||||
});
|
||||
|
||||
describe('immutable retry failure history', () => {
|
||||
test('a later retry count refresh fences an older history read without losing its newer snapshot', async () => {
|
||||
const value = failure();
|
||||
await show(value);
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
const old = request(historyPath());
|
||||
await flush(() => button('Refresh experiment').click());
|
||||
const newer = transition(value, 0, { retryCount: 1, attemptNumber: 2, error: 'Later failure' });
|
||||
await flush(() => reply(request(`/api/v2/experiments/${experimentId}`), { experiment: newer }));
|
||||
const current = requests.filter(item => item.path === historyPath() && !item.settled).at(-1)!;
|
||||
expect(current).not.toBe(old);
|
||||
await flush(() => reply(current, { retries: [receipt(value)] }));
|
||||
await flush(() => reply(old, { retries: [] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
|
||||
expect(host.textContent).not.toContain('No accepted manual retries');
|
||||
});
|
||||
test('history is lazy and renders empty/loading states then exact nullable failure snapshots', async () => {
|
||||
const value = failure(0, 0);
|
||||
value.trials[0]!.error = null;
|
||||
await show(value);
|
||||
expect(requests.some(item => item.path.endsWith('/retries'))).toBe(false);
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
expect(host.textContent).toContain('Loading retry history for trial 1');
|
||||
await flush(() => reply(request(historyPath()), { retries: [] }));
|
||||
expect(host.textContent).toContain('No accepted manual retries for this trial');
|
||||
await flush(() => button('Refresh retry history for trial 1').click());
|
||||
const saved = receipt(value);
|
||||
await flush(() => reply(request(historyPath()), { retries: [saved] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 0');
|
||||
expect(host.textContent).toContain('No error was recorded for this failure');
|
||||
expect(host.textContent).toContain('No attempt ID was recorded');
|
||||
expect(host.textContent).toContain(saved.failureUpdatedAt);
|
||||
expect(host.textContent).toContain(saved.completedAt!);
|
||||
expect(host.textContent).toContain(saved.recordedAt);
|
||||
expect(host.textContent).toContain(saved.reviewId);
|
||||
expect(host.textContent).toContain('not a complete history of automatic recovery attempts');
|
||||
});
|
||||
test.each(['partial', 'foreign', 'unordered', 'duplicate', 'http'] as const)(
|
||||
'%s history is an error, never a false empty/success state, and explicit refresh recovers',
|
||||
async kind => {
|
||||
const value = failure();
|
||||
await show(value);
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
const saved = receipt(value);
|
||||
const bad = structuredClone(saved);
|
||||
if (kind === 'foreign') {
|
||||
bad.runId = runId(1);
|
||||
}
|
||||
if (kind === 'unordered') {
|
||||
bad.retryNumber = 2;
|
||||
}
|
||||
const rows =
|
||||
kind === 'partial' ? [{ id: saved.id }] : kind === 'duplicate' ? [saved, saved] : [bad];
|
||||
await flush(() =>
|
||||
reply(
|
||||
request(historyPath()),
|
||||
kind === 'http' ? { error: 'History unavailable' } : { retries: rows },
|
||||
kind === 'http' ? 500 : 200
|
||||
)
|
||||
);
|
||||
expect(
|
||||
host.querySelector('[aria-label="Retry history for trial 1"] [role="alert"]')
|
||||
).not.toBeNull();
|
||||
expect(host.textContent).not.toContain('No accepted manual retries');
|
||||
expect(host.textContent).not.toContain('Retry 1 · previous attempt');
|
||||
await flush(() => button('Refresh retry history for trial 1').click());
|
||||
await flush(() => reply(request(historyPath()), { retries: [saved] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
|
||||
}
|
||||
);
|
||||
test('hide/reopen fences a delayed history response and a successful retry refreshes open history', async () => {
|
||||
const value = await start();
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
const old = request(historyPath());
|
||||
await flush(() => button('Hide retry history for trial 1').click());
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
const current = requests.filter(item => item.path === historyPath() && !item.settled).at(-1)!;
|
||||
await flush(() => reply(current, { retries: [] }));
|
||||
await flush(() => reply(old, { error: 'Old failure' }, 500));
|
||||
expect(host.textContent).toContain('No accepted manual retries');
|
||||
expect(host.textContent).not.toContain('Old failure');
|
||||
await flush(() => button('Confirm retry trial 1').click());
|
||||
await flush(() => reply(request(retryPath(), 'POST'), accepted(value), 202));
|
||||
expect(host.textContent).toContain('Loading retry history for trial 1');
|
||||
await flush(() => reply(request(historyPath()), { retries: [receipt(value)] }));
|
||||
expect(host.textContent).toContain('Retry 1 · previous attempt 1');
|
||||
});
|
||||
test('late history response cannot appear in another selected experiment', async () => {
|
||||
const value = failure();
|
||||
await show(value);
|
||||
await flush(() => button('Show retry history for trial 1').click());
|
||||
const old = request(historyPath());
|
||||
await flush(() => navigate(`/experiments/${otherExperimentId}`));
|
||||
const other = failure();
|
||||
other.id = otherExperimentId;
|
||||
await flush(() =>
|
||||
reply(request(`/api/v2/experiments/${otherExperimentId}`), { experiment: other })
|
||||
);
|
||||
await flush(() => reply(old, { retries: [receipt(value)] }));
|
||||
expect(host.querySelector('[aria-label="Retry history for trial 1"]')).toBeNull();
|
||||
expect(host.textContent).not.toContain('Retry 1 · previous attempt 1');
|
||||
});
|
||||
});
|
||||
|
|
@ -272,6 +272,8 @@ describe('experiment HTTP contract', () => {
|
|||
status: index === 0 ? 'completed' : 'failed',
|
||||
progress: index === 0 ? 100 : 50,
|
||||
cancel_requested: false,
|
||||
attempt_number: 1,
|
||||
manual_retry_count: 0,
|
||||
error: index === 1 ? 'failure' : null,
|
||||
dataset_hash: preview.request.datasetHash,
|
||||
request_snapshot: experimentTrialRequest(preview, candidate, id),
|
||||
|
|
|
|||
|
|
@ -239,6 +239,8 @@ function detail(
|
|||
const trials: ExperimentTrial[] = source.candidates.map((item, index) => ({
|
||||
...item,
|
||||
runId: statuses[index] === 'missing' ? null : runId(index),
|
||||
attemptNumber: 0,
|
||||
retryCount: 0,
|
||||
status: statuses[index]!,
|
||||
progress: statuses[index] === 'completed' ? 100 : 0,
|
||||
cancelRequested: false,
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ async function fixture(options: { corruptDataset?: boolean; buildMismatch?: bool
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ async function fixture(dataset = canonicalSmaFixture().dataset) {
|
|||
'19-canonical-research.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')
|
||||
|
|
|
|||
|
|
@ -102,6 +102,7 @@ async function fixture() {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ async function fixture() {
|
|||
'19-canonical-research.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')
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@ async function fixture() {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
837
test/postgres/experiment-retries.test.ts
Normal file
837
test/postgres/experiment-retries.test.ts
Normal file
|
|
@ -0,0 +1,837 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { Queue } from '@stock-bot/queue';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import {
|
||||
experimentHash,
|
||||
experimentTrialRequest,
|
||||
} from '../../apps/stock/web-api/src/services/experiment-input';
|
||||
import { ExperimentsService } from '../../apps/stock/web-api/src/services/experiments.service';
|
||||
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
|
||||
import { retainResearchDataset } from '../../scripts/import-research-dataset';
|
||||
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
|
||||
import { canonicalSettings } from '../fixtures/canonical-research';
|
||||
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('experiment-retries');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
let packages: ReturnType<typeof packageBuiltinStrategies> | undefined;
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
async function fixture(poolMax = 4, withRetries = true) {
|
||||
const dataset = canonicalSmaFixture().dataset;
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Disposable safety database required');
|
||||
}
|
||||
const schema = 'stock_bot_safety_retries_' + randomUUID().replaceAll('-', '');
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
application_name: schema,
|
||||
max: poolMax,
|
||||
options: `-c search_path=${schema} -c statement_timeout=10000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
for (const name of [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
...(withRetries ? ['23-experiment-retries.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const container = { postgres, logger };
|
||||
const api = new BacktestServiceV2(container);
|
||||
const experiments = new ExperimentsService(container);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const catalog = new StrategyCatalogService(container);
|
||||
const pkg = (await (packages ??= packageBuiltinStrategies()))[0]!;
|
||||
const version = await catalog.seedBuiltin('Retained SMA', pkg, 'seed');
|
||||
await retainResearchDataset(pool, dataset);
|
||||
const definition = {
|
||||
name: 'Canonical API',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 3 },
|
||||
symbols: dataset.manifest.executionSeries.map(s => s.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 draft = await api.createBacktest(definition, { autoStart: false });
|
||||
const approve = async () => {
|
||||
await catalog.reviewVersion(
|
||||
version.id,
|
||||
{ decision: 'approve', reason: 'Reviewed retained builtin' },
|
||||
'operator'
|
||||
);
|
||||
return (await catalog.getVersionReviews(version.id)).at(-1)!;
|
||||
};
|
||||
const execute = async (id: string) => {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Canonical execution must never load provider data');
|
||||
},
|
||||
},
|
||||
});
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres),
|
||||
logger,
|
||||
});
|
||||
try {
|
||||
await runner.runQueued(id);
|
||||
} finally {
|
||||
await runner.shutdown();
|
||||
}
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
postgres,
|
||||
schema,
|
||||
api,
|
||||
experiments,
|
||||
repository,
|
||||
catalog,
|
||||
pkg,
|
||||
version,
|
||||
draft,
|
||||
definition,
|
||||
dataset,
|
||||
approve,
|
||||
execute,
|
||||
};
|
||||
}
|
||||
|
||||
const receipt = (key: string = randomUUID()) => ({ principal: 'operator' as const, key });
|
||||
type Fixture = Awaited<ReturnType<typeof fixture>>;
|
||||
async function prepare(f: Fixture) {
|
||||
await f.approve();
|
||||
const input = { backtestId: f.draft.id, name: 'Retry fixture', grid: {} };
|
||||
const preview = await f.experiments.preview(input);
|
||||
const experiment = await f.experiments.submit(
|
||||
{ ...input, previewHash: preview.previewHash },
|
||||
receipt()
|
||||
);
|
||||
const runId = experiment.trials[0]!.runId!;
|
||||
const request = (await f.pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId]))
|
||||
.rows[0].request_snapshot as CanonicalRunRequest;
|
||||
return { experiment, runId, request };
|
||||
}
|
||||
async function row(f: Fixture, id: string) {
|
||||
return (await f.pool.query('SELECT to_jsonb(r) AS value FROM runs r WHERE id=$1', [id])).rows[0]
|
||||
.value;
|
||||
}
|
||||
async function failBeforeClaim(
|
||||
f: Fixture,
|
||||
id: string,
|
||||
error: string | null = 'Preclaim diagnostic'
|
||||
) {
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET status='failed',error=$2,completed_at=clock_timestamp() WHERE id=$1",
|
||||
[id, error]
|
||||
);
|
||||
}
|
||||
async function nativeResult(f: Fixture, request: CanonicalRunRequest): Promise<CanonicalRunResult> {
|
||||
const engine = new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: {
|
||||
async getHistoricalBars() {
|
||||
throw new Error('Provider access forbidden');
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
return {
|
||||
kind: 'canonical-result/v1',
|
||||
runId: request.runId,
|
||||
backtestId: request.backtestId,
|
||||
status: 'completed',
|
||||
completedAt: new Date().toISOString(),
|
||||
executionTime: 0,
|
||||
financialEngine: 'rust',
|
||||
strategyExecution: 'typescript-retained-builtin/v1',
|
||||
request,
|
||||
...(await engine.runCanonical(request, async () => f.dataset)),
|
||||
};
|
||||
} finally {
|
||||
await engine.shutdown();
|
||||
}
|
||||
}
|
||||
async function snapshotCounts(f: Fixture) {
|
||||
return (
|
||||
await f.pool.query(`SELECT (SELECT count(*)::int FROM experiment_trial_retries) AS retries,
|
||||
(SELECT count(*)::int FROM runs) AS runs,(SELECT count(*)::int FROM backtest_results) AS results,(SELECT count(*)::int FROM backtest_dispatch) AS dispatch`)
|
||||
).rows[0];
|
||||
}
|
||||
const observed = (attempt = 0, retry = 0) => ({
|
||||
expectedAttemptNumber: attempt,
|
||||
expectedRetryCount: retry,
|
||||
});
|
||||
async function rawReceipt(
|
||||
f: Fixture,
|
||||
runId: string,
|
||||
reviewId: string,
|
||||
changes: Record<string, unknown> = {}
|
||||
) {
|
||||
const retryId = randomUUID();
|
||||
return f.pool.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,COALESCE($4::uuid,experiment_id),id,trial_key,COALESCE($5::int,manual_retry_count+1),attempt_number,attempt_id,
|
||||
CASE WHEN $6::text IS NULL THEN error ELSE $6::text END,progress,current_simulation_date,started_at,completed_at,paused_at,
|
||||
${changes.roundTime ? "date_trunc('milliseconds',updated_at)" : 'updated_at'},'operator',$3,$7,$8
|
||||
FROM runs WHERE id=$2 RETURNING id`,
|
||||
[
|
||||
retryId,
|
||||
runId,
|
||||
reviewId,
|
||||
changes.experiment ?? null,
|
||||
changes.retryNumber ?? null,
|
||||
changes.error ?? null,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('guarded failed experiment trial retry', () => {
|
||||
test('failed worker retry retains exact failure timestamps and frozen identity, fences every stale callback, and completes once in real Rust', async () => {
|
||||
const f = await fixture(1),
|
||||
{ experiment, runId, request } = await prepare(f);
|
||||
const claim = await f.repository.startCanonical(request);
|
||||
await f.repository.updateProgress(runId, 37.25, '2024-01-01T09:03:00.123Z', claim.attemptId);
|
||||
await f.pool.query(
|
||||
"UPDATE runs SET started_at='2026-10-24T10:00:00.123456Z',paused_at='2026-10-24T10:01:00.654321Z' WHERE id=$1",
|
||||
[runId]
|
||||
);
|
||||
const result = await nativeResult(f, request);
|
||||
await f.repository.fail(runId, 'Observed failure after computation', claim.attemptId);
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET attempt_number=0 WHERE id=$1', [runId])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
const before = await row(f, runId),
|
||||
key = receipt();
|
||||
const latest = await f.approve();
|
||||
expect(latest.id).not.toBe(request.strategy.reviewId);
|
||||
const retried = await f.experiments.retryTrial(experiment.id, runId, observed(1), key);
|
||||
expect(retried.retry).toMatchObject({
|
||||
runId,
|
||||
experimentId: experiment.id,
|
||||
retryNumber: 1,
|
||||
previousAttemptNumber: 1,
|
||||
previousAttemptId: claim.attemptId,
|
||||
error: before.error,
|
||||
progress: 37.25,
|
||||
reviewId: latest.id,
|
||||
});
|
||||
expect(retried.retry.startedAt).toBe('2026-10-24T10:00:00.123456Z');
|
||||
expect(retried.retry.pausedAt).toBe('2026-10-24T10:01:00.654321Z');
|
||||
const exact = (
|
||||
await f.pool.query(
|
||||
`SELECT h.started_at=($2::jsonb->>'started_at')::timestamptz AND h.paused_at=($2::jsonb->>'paused_at')::timestamptz
|
||||
AND h.completed_at=($2::jsonb->>'completed_at')::timestamptz AND h.failure_updated_at=($2::jsonb->>'updated_at')::timestamptz AS exact
|
||||
FROM experiment_trial_retries h WHERE run_id=$1`,
|
||||
[runId, before]
|
||||
)
|
||||
).rows[0];
|
||||
expect(exact.exact).toBe(true);
|
||||
const pending = await row(f, runId);
|
||||
expect(pending).toMatchObject({
|
||||
status: 'pending',
|
||||
attempt_number: 1,
|
||||
manual_retry_count: 1,
|
||||
attempt_id: null,
|
||||
lease_expires_at: null,
|
||||
progress: 0,
|
||||
error: null,
|
||||
current_simulation_date: null,
|
||||
started_at: null,
|
||||
completed_at: null,
|
||||
paused_at: null,
|
||||
request_snapshot: request,
|
||||
dataset_hash: request.datasetHash,
|
||||
});
|
||||
expect(pending.request_snapshot.strategy.reviewId).toBe(request.strategy.reviewId);
|
||||
const assertStale = async () => {
|
||||
const current = await row(f, runId);
|
||||
await expect(f.repository.heartbeat(runId, claim.attemptId)).rejects.toThrow();
|
||||
await expect(
|
||||
f.repository.updateProgress(runId, 99, undefined, claim.attemptId)
|
||||
).rejects.toThrow();
|
||||
await f.repository.fail(runId, 'Stale overwrite', claim.attemptId);
|
||||
await expect(f.repository.cancel(runId, claim.attemptId)).rejects.toThrow();
|
||||
await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toThrow();
|
||||
expect(await row(f, runId)).toEqual(current);
|
||||
};
|
||||
await assertStale();
|
||||
const next = await f.repository.startCanonical(request);
|
||||
expect(next.attemptId).not.toBe(claim.attemptId);
|
||||
await assertStale();
|
||||
await f.repository.completeCanonical(result, next.attemptId);
|
||||
expect((await f.api.getRunResults(runId))!.runId).toBe(runId);
|
||||
expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 });
|
||||
expect((await f.experiments.get(experiment.id)).trials[0]).toMatchObject({
|
||||
attemptNumber: 2,
|
||||
retryCount: 1,
|
||||
status: 'completed',
|
||||
comparable: true,
|
||||
});
|
||||
expect((await f.experiments.retryTrial(experiment.id, runId, observed(1), key)).retry).toEqual(
|
||||
retried.retry
|
||||
);
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(2, 1), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await f.experiments.listTrialRetries(experiment.id, runId)).toEqual([retried.retry]);
|
||||
});
|
||||
|
||||
test('preclaim failure0 can recur; both counters prevent stale intent and null prior identifiers stay honest', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId, null);
|
||||
const key = receipt(),
|
||||
first = await f.experiments.retryTrial(experiment.id, runId, observed(), key);
|
||||
expect(first.retry).toMatchObject({
|
||||
previousAttemptNumber: 0,
|
||||
previousAttemptId: null,
|
||||
error: null,
|
||||
retryNumber: 1,
|
||||
startedAt: null,
|
||||
pausedAt: null,
|
||||
currentDate: null,
|
||||
});
|
||||
await failBeforeClaim(f, runId, 'second preclaim failure');
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual(
|
||||
first.retry
|
||||
);
|
||||
const second = await f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt());
|
||||
expect(second.retry).toMatchObject({
|
||||
retryNumber: 2,
|
||||
previousAttemptNumber: 0,
|
||||
previousAttemptId: null,
|
||||
error: 'second preclaim failure',
|
||||
});
|
||||
expect(
|
||||
(await f.experiments.listTrialRetries(experiment.id, runId)).map(h => h.retryNumber)
|
||||
).toEqual([1, 2]);
|
||||
expect((await row(f, runId)).attempt_number).toBe(0);
|
||||
});
|
||||
|
||||
test('same-key race replays one receipt; different keys or cross-experiment reuse cannot reset twice', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
const key = receipt();
|
||||
const [a, b] = await Promise.all([
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), key),
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), key),
|
||||
]);
|
||||
expect(a.retry.id).toBe(b.retry.id);
|
||||
await failBeforeClaim(f, runId);
|
||||
const race = await Promise.allSettled([
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()),
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt()),
|
||||
]);
|
||||
expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(
|
||||
race.filter(r => r.status === 'rejected').map(r => (r as PromiseRejectedResult).reason.status)
|
||||
).toEqual([409]);
|
||||
await expect(
|
||||
f.experiments.retryTrial(randomUUID(), runId, observed(), key)
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 0, retries: 2, dispatch: 1 });
|
||||
const secondParent = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Second retry parent' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const secondInput = { backtestId: secondParent.id, name: 'Other parent experiment', grid: {} };
|
||||
const secondPreview = await f.experiments.preview(secondInput);
|
||||
const secondExperiment = await f.experiments.submit(
|
||||
{ ...secondInput, previewHash: secondPreview.previewHash },
|
||||
receipt()
|
||||
);
|
||||
const secondRunId = secondExperiment.trials[0]!.runId!;
|
||||
await failBeforeClaim(f, runId);
|
||||
await failBeforeClaim(f, secondRunId);
|
||||
const crossKey = receipt();
|
||||
const cross = await Promise.allSettled([
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(0, 2), crossKey),
|
||||
f.experiments.retryTrial(secondExperiment.id, secondRunId, observed(), crossKey),
|
||||
]);
|
||||
expect(cross.filter(item => item.status === 'fulfilled')).toHaveLength(1);
|
||||
expect(
|
||||
cross
|
||||
.filter(item => item.status === 'rejected')
|
||||
.map(item => (item as PromiseRejectedResult).reason.status)
|
||||
).toEqual([409]);
|
||||
expect(await snapshotCounts(f)).toEqual({ runs: 2, results: 0, retries: 3, dispatch: 2 });
|
||||
});
|
||||
|
||||
test('latest original-version approval governs retries despite template edits; accepted receipts survive revocation/archive/cancellation', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId, request } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
const other = (await (packages ??= packageBuiltinStrategies()))[1]!;
|
||||
const version = await f.catalog.seedBuiltin('Different template version', other, 'seed-other');
|
||||
await f.api.updateBacktest(f.draft.id, {
|
||||
name: 'Different template',
|
||||
strategyVersionId: version.id,
|
||||
strategyParameters: {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0.1,
|
||||
minTrendReturn: -0.5,
|
||||
minMomentumReturn: -0.5,
|
||||
maxVolatility: 1,
|
||||
minNotionalVolume: '0',
|
||||
regimeFilter: 'none',
|
||||
},
|
||||
initialCapital: 20000,
|
||||
});
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'No new execution' },
|
||||
'operator'
|
||||
);
|
||||
const before = await row(f, runId);
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await row(f, runId)).toEqual(before);
|
||||
const latest = await f.approve(),
|
||||
key = receipt();
|
||||
const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key);
|
||||
expect(accepted.retry.reviewId).toBe(latest.id);
|
||||
expect((await row(f, runId)).request_snapshot).toEqual(request);
|
||||
await f.catalog.reviewVersion(
|
||||
f.version.id,
|
||||
{ decision: 'revoke', reason: 'Pause' },
|
||||
'operator'
|
||||
);
|
||||
await f.pool.query('UPDATE backtests SET archived_at=NOW() WHERE id=$1', [f.draft.id]);
|
||||
await f.pool.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
await f.experiments.cancel(experiment.id);
|
||||
expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual(
|
||||
accepted.retry
|
||||
);
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
|
||||
test('outbox fault rolls back history and reset; due redispatch survives publication outage without resetting lifetime attempt budget', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId, request } = await prepare(f);
|
||||
const claim = await f.repository.startCanonical(request);
|
||||
await f.repository.fail(runId, 'worker failure', claim.attemptId);
|
||||
await f.pool.query(
|
||||
"UPDATE backtest_dispatch SET publish_count=9,last_published_at='2026-10-24T10:00:00.123456Z',next_publish_at=NOW()+interval '1 day' WHERE run_id=$1",
|
||||
[runId]
|
||||
);
|
||||
await f.pool
|
||||
.query(`CREATE FUNCTION reject_retry_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture outage'; END $$;
|
||||
CREATE TRIGGER fixture_dispatch_outage BEFORE UPDATE ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_retry_dispatch()`);
|
||||
const before = await row(f, runId),
|
||||
key = receipt();
|
||||
await expect(f.experiments.retryTrial(experiment.id, runId, observed(1), key)).rejects.toThrow(
|
||||
'fixture outage'
|
||||
);
|
||||
expect(await row(f, runId)).toEqual(before);
|
||||
expect((await snapshotCounts(f)).retries).toBe(0);
|
||||
await f.pool.query('DROP TRIGGER fixture_dispatch_outage ON backtest_dispatch');
|
||||
await f.experiments.retryTrial(experiment.id, runId, observed(1), key);
|
||||
const dispatch = (
|
||||
await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])
|
||||
).rows[0];
|
||||
expect(dispatch.publish_count).toBe(9);
|
||||
expect(dispatch.last_published_at.toISOString()).toBe('2026-10-24T10:00:00.123Z');
|
||||
let failed = true;
|
||||
const delivered: string[] = [];
|
||||
const dispatcher = new BacktestDispatcher(
|
||||
f.postgres,
|
||||
{
|
||||
async add(_name: string, data: unknown) {
|
||||
if (failed) {
|
||||
throw new Error('Redis unavailable');
|
||||
}
|
||||
delivered.push((data as { payload: { runId: string } }).payload.runId);
|
||||
return {};
|
||||
},
|
||||
} as never,
|
||||
logger,
|
||||
{ intervalMs: 20, republishMs: 5, maxAttempts: 1 }
|
||||
);
|
||||
await expect(dispatcher.tick()).rejects.toThrow('Redis unavailable');
|
||||
expect((await row(f, runId)).status).toBe('pending');
|
||||
failed = false;
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
await dispatcher.tick();
|
||||
expect(delivered).toEqual([runId]);
|
||||
const next = await f.repository.startCanonical(request);
|
||||
expect((await row(f, runId)).attempt_number).toBe(2);
|
||||
await f.pool.query("UPDATE runs SET lease_expires_at=NOW()-interval '1 second' WHERE id=$1", [
|
||||
runId,
|
||||
]);
|
||||
await dispatcher.tick();
|
||||
expect(await row(f, runId)).toMatchObject({
|
||||
status: 'failed',
|
||||
attempt_number: 2,
|
||||
manual_retry_count: 1,
|
||||
attempt_id: null,
|
||||
error: 'Execution lease expired; retry limit reached',
|
||||
});
|
||||
await expect(f.repository.heartbeat(runId, next.attemptId)).rejects.toThrow();
|
||||
await dispatcher.shutdown();
|
||||
});
|
||||
|
||||
test('SQL rejects missing receipts, altered or rounded snapshots, history tampering, count changes and incomplete resets', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
const review = (await f.catalog.getVersionReviews(f.version.id)).at(-1)!;
|
||||
const original = await row(f, runId);
|
||||
for (const patch of ["status='pending'", "status='running'", 'manual_retry_count=1']) {
|
||||
await expect(
|
||||
f.pool.query(`UPDATE runs SET ${patch} WHERE id=$1`, [runId])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
for (const changes of [
|
||||
{ error: 'invented failure' },
|
||||
{ retryNumber: 2 },
|
||||
{ experiment: randomUUID() },
|
||||
{ roundTime: true },
|
||||
{},
|
||||
]) {
|
||||
await expect(rawReceipt(f, runId, review.id, changes)).rejects.toMatchObject({
|
||||
code: '23514',
|
||||
});
|
||||
}
|
||||
expect(await row(f, runId)).toEqual(original);
|
||||
const client = await f.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
// Use the SQL capture itself, then prove a partial reset cannot consume the receipt.
|
||||
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,1,attempt_number,attempt_id,error,progress,current_simulation_date,started_at,completed_at,paused_at,updated_at,'operator',$3,$4,$5 FROM runs WHERE id=$2`,
|
||||
[randomUUID(), runId, review.id, randomUUID(), 'a'.repeat(64)]
|
||||
);
|
||||
await expect(
|
||||
client.query("UPDATE runs SET status='pending',manual_retry_count=1 WHERE id=$1", [runId])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
} finally {
|
||||
await client.query('ROLLBACK');
|
||||
client.release();
|
||||
}
|
||||
const retry = await f.experiments.retryTrial(experiment.id, runId, observed(), receipt());
|
||||
for (const sql of [
|
||||
"UPDATE experiment_trial_retries SET error='changed' WHERE id=$1",
|
||||
'DELETE FROM experiment_trial_retries WHERE id=$1',
|
||||
]) {
|
||||
await expect(f.pool.query(sql, [retry.retry.id])).rejects.toMatchObject({ code: '23514' });
|
||||
}
|
||||
await expect(f.pool.query('TRUNCATE experiment_trial_retries')).rejects.toMatchObject({
|
||||
code: '23514',
|
||||
});
|
||||
await expect(
|
||||
f.pool.query('UPDATE runs SET manual_retry_count=0 WHERE id=$1', [runId])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
expect((await snapshotCounts(f)).retries).toBe(1);
|
||||
});
|
||||
|
||||
test('cancellation race either rejects retry or cancels its reset run; wrong membership/results/current terminal states reject', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, randomUUID(), observed(), receipt())
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
const ordinary = await f.api.createRun({ backtestId: f.draft.id });
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, ordinary.id, observed(), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
await expect(f.experiments.listTrialRetries(experiment.id, ordinary.id)).rejects.toMatchObject({
|
||||
status: 409,
|
||||
});
|
||||
await failBeforeClaim(f, runId);
|
||||
await Promise.allSettled([
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(), receipt()),
|
||||
f.experiments.cancel(experiment.id),
|
||||
]);
|
||||
const current = await row(f, runId);
|
||||
expect(current.status === 'failed' || current.status === 'cancelled').toBe(true);
|
||||
expect((await f.experiments.get(experiment.id)).cancelRequested).toBe(true);
|
||||
await expect(
|
||||
f.experiments.retryTrial(
|
||||
experiment.id,
|
||||
runId,
|
||||
observed(0, current.manual_retry_count),
|
||||
receipt()
|
||||
)
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
const completed = await prepare(f);
|
||||
await f.execute(completed.runId);
|
||||
// Deliberate corruption in this disposable schema proves retained results still forbid retry.
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query("UPDATE runs SET status='failed' WHERE id=$1", [completed.runId]);
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
const evidence = await row(f, completed.runId);
|
||||
await expect(
|
||||
f.experiments.retryTrial(completed.experiment.id, completed.runId, observed(1), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await row(f, completed.runId)).toEqual(evidence);
|
||||
await expect(
|
||||
f.pool.query("UPDATE runs SET status='pending' WHERE id=$1", [completed.runId])
|
||||
).rejects.toMatchObject({ code: '23514' });
|
||||
});
|
||||
test('real Redis publication outage recovers the same retried run and real Rust result once', async () => {
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (!redisUrl || new URL(redisUrl).pathname !== '/15') {
|
||||
throw new Error('Dedicated Redis database15 required');
|
||||
}
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
await f.experiments.retryTrial(experiment.id, runId, observed(), receipt());
|
||||
const endpoint = new URL(redisUrl),
|
||||
redis = { host: endpoint.hostname, port: Number(endpoint.port), db: 15 };
|
||||
const name = `stock-bot-safety-retry-${randomUUID()}`;
|
||||
const producer = new Queue(name, redis, {}, { workers: 0 }, logger);
|
||||
await producer.getBullQueue().waitUntilReady();
|
||||
cleanup.push(async () => {
|
||||
await producer.getBullQueue().obliterate({ force: true });
|
||||
await producer.close();
|
||||
});
|
||||
const dispatcher = new BacktestDispatcher(f.postgres, producer, logger, {
|
||||
intervalMs: 20,
|
||||
republishMs: 30,
|
||||
maxAttempts: 3,
|
||||
});
|
||||
cleanup.push(() => dispatcher.shutdown());
|
||||
const connection = await producer.getBullQueue().client;
|
||||
connection.disconnect();
|
||||
await expect(dispatcher.tick()).rejects.toThrow();
|
||||
expect((await row(f, runId)).status).toBe('pending');
|
||||
await connection.connect();
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
await dispatcher.tick();
|
||||
const registry = new HandlerRegistry();
|
||||
registry.registerConfiguration({
|
||||
name: 'orchestrator',
|
||||
operations: {
|
||||
'run-backtest': async payload => f.execute((payload as { runId: string }).runId),
|
||||
},
|
||||
});
|
||||
const worker = new Queue(
|
||||
name,
|
||||
redis,
|
||||
{},
|
||||
{ workers: 1, concurrency: 1, handlerRegistry: registry },
|
||||
logger
|
||||
);
|
||||
cleanup.push(() => worker.close());
|
||||
let done = false;
|
||||
for (let i = 0; i < 150; i++) {
|
||||
if ((await row(f, runId)).status === 'completed') {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
expect(done).toBe(true);
|
||||
expect(await snapshotCounts(f)).toEqual({ runs: 1, results: 1, retries: 1, dispatch: 1 });
|
||||
await f.execute(runId); // Repeat delivery is harmless after completion.
|
||||
expect((await snapshotCounts(f)).results).toBe(1);
|
||||
expect((await row(f, runId)).attempt_number).toBe(1);
|
||||
});
|
||||
|
||||
test('first SQL23 upgrade preserves old failed experiment evidence with count0 and no invented history; reapplication preserves accepted retry', async () => {
|
||||
const f = await fixture(4, false);
|
||||
await f.approve();
|
||||
const input = { backtestId: f.draft.id, name: 'Pre-migration experiment', grid: {} };
|
||||
const preview = await f.experiments.preview(input),
|
||||
experimentId = randomUUID(),
|
||||
runId = randomUUID();
|
||||
const candidate = preview.candidates[0]!,
|
||||
request = experimentTrialRequest(preview, candidate, runId);
|
||||
await f.pool.query(
|
||||
`INSERT INTO research_experiments(id,backtest_id,name,preview,preview_hash,submission_principal,submission_key,submission_hash)
|
||||
VALUES($1,$2,$3,$4,$5,'operator',$6,$7)`,
|
||||
[
|
||||
experimentId,
|
||||
f.draft.id,
|
||||
input.name,
|
||||
preview,
|
||||
preview.previewHash,
|
||||
randomUUID(),
|
||||
'a'.repeat(64),
|
||||
]
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO runs(id,backtest_id,run_number,status,speed_multiplier,request_snapshot,dataset_hash,experiment_id,trial_key,trial_index)
|
||||
VALUES($1,$2,1,'pending',NULL,$3,$4,$5,$6,0)`,
|
||||
[runId, f.draft.id, request, request.datasetHash, experimentId, candidate.trialKey]
|
||||
);
|
||||
await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]);
|
||||
await failBeforeClaim(f, runId);
|
||||
const before = await row(f, runId),
|
||||
outbox = (await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows;
|
||||
const sql = readFileSync(
|
||||
new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
await f.pool.query(sql);
|
||||
expect(await row(f, runId)).toEqual({ ...before, manual_retry_count: 0 });
|
||||
expect(
|
||||
(await f.pool.query('SELECT to_jsonb(d) AS value FROM backtest_dispatch d')).rows
|
||||
).toEqual(outbox);
|
||||
expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([]);
|
||||
const accepted = await f.experiments.retryTrial(experimentId, runId, observed(), receipt());
|
||||
const after = await row(f, runId);
|
||||
await f.pool.query(sql);
|
||||
expect(await row(f, runId)).toEqual(after);
|
||||
expect(await f.experiments.listTrialRetries(experimentId, runId)).toEqual([accepted.retry]);
|
||||
await f.execute(runId);
|
||||
expect((await f.experiments.get(experimentId)).trials[0]).toMatchObject({
|
||||
status: 'completed',
|
||||
attemptNumber: 1,
|
||||
retryCount: 1,
|
||||
});
|
||||
});
|
||||
test('current-family archive serializes fresh retry and leaves the prior failure intact', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
const before = await row(f, runId);
|
||||
const blocker = await f.pool.connect();
|
||||
let pending: Promise<unknown> | undefined;
|
||||
try {
|
||||
await blocker.query('BEGIN');
|
||||
await blocker.query('UPDATE strategies SET archived_at=NOW() WHERE id=$1', [
|
||||
f.version.strategyId,
|
||||
]);
|
||||
pending = f.experiments.retryTrial(experiment.id, runId, observed(), receipt()).then(
|
||||
value => ({ value }),
|
||||
error => ({ error })
|
||||
);
|
||||
let waiting = false;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (
|
||||
(
|
||||
await f.pool.query(
|
||||
"SELECT 1 FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
|
||||
[f.schema]
|
||||
)
|
||||
).rows.length
|
||||
) {
|
||||
waiting = true;
|
||||
break;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
await blocker.query('COMMIT');
|
||||
expect(await pending).toMatchObject({ error: { status: 409 } });
|
||||
} finally {
|
||||
await blocker.query('ROLLBACK');
|
||||
blocker.release();
|
||||
await pending;
|
||||
}
|
||||
expect(await row(f, runId)).toEqual(before);
|
||||
expect((await snapshotCounts(f)).retries).toBe(0);
|
||||
});
|
||||
|
||||
test('unsupported retained build rejects fresh retry while accepted receipt replays before current build eligibility', async () => {
|
||||
const f = await fixture(),
|
||||
{ experiment, runId } = await prepare(f);
|
||||
await failBeforeClaim(f, runId);
|
||||
const key = receipt();
|
||||
const accepted = await f.experiments.retryTrial(experiment.id, runId, observed(), key);
|
||||
await failBeforeClaim(f, runId, 'Later failure');
|
||||
// Alter retained evidence only in this disposable schema to model a no-longer-installed historical build.
|
||||
const altered = structuredClone(experiment.preview);
|
||||
altered.request.build.runtimeVersion = 'unavailable-historical-build';
|
||||
const { previewHash: _oldHash, ...manifest } = altered;
|
||||
altered.previewHash = experimentHash(manifest);
|
||||
const request = experimentTrialRequest(altered, altered.candidates[0]!, runId);
|
||||
await f.pool.query('ALTER TABLE research_experiments DISABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE runs DISABLE TRIGGER USER');
|
||||
await f.pool.query('UPDATE research_experiments SET preview=$2,preview_hash=$3 WHERE id=$1', [
|
||||
experiment.id,
|
||||
altered,
|
||||
altered.previewHash,
|
||||
]);
|
||||
await f.pool.query('UPDATE runs SET request_snapshot=$2 WHERE id=$1', [runId, request]);
|
||||
await f.pool.query('ALTER TABLE research_experiments ENABLE TRIGGER USER');
|
||||
await f.pool.query('ALTER TABLE runs ENABLE TRIGGER USER');
|
||||
const before = await row(f, runId);
|
||||
await expect(
|
||||
f.experiments.retryTrial(experiment.id, runId, observed(0, 1), receipt())
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
expect(await row(f, runId)).toEqual(before);
|
||||
expect((await f.experiments.retryTrial(experiment.id, runId, observed(), key)).retry).toEqual(
|
||||
accepted.retry
|
||||
);
|
||||
expect((await snapshotCounts(f)).retries).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -64,7 +64,7 @@ async function fixture(poolMax = 4, withExperiments = true) {
|
|||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
...(withExperiments ? ['22-experiments.sql'] : []),
|
||||
...(withExperiments ? ['22-experiments.sql', '23-experiment-retries.sql'] : []),
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
|
|
@ -702,6 +702,13 @@ describe.skipIf(!url)('retained-input experiments', () => {
|
|||
expect((await f.api.getReproductionComparison(reproduction.id)).status).toBe('match');
|
||||
const ordinary = await f.api.createRun({ backtestId: f.draft.id }, receipt());
|
||||
expect(ordinary.status).toBe('pending');
|
||||
// The current experiment reader includes retry counters introduced after SQL22.
|
||||
await f.pool.query(
|
||||
readFileSync(
|
||||
new URL('../../database/postgres/init/23-experiment-retries.sql', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
);
|
||||
const input = { backtestId: f.draft.id, name: 'After upgrade', grid: {} };
|
||||
const preview = await f.experiments.preview(input);
|
||||
expect(
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ const migrations = [
|
|||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
];
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,9 @@ const retention =
|
|||
sql('19-canonical-research.sql') +
|
||||
'\n' +
|
||||
sql('21-run-reproduction.sql') +
|
||||
sql('22-experiments.sql');
|
||||
sql('22-experiments.sql') +
|
||||
'\n' +
|
||||
sql('23-experiment-retries.sql');
|
||||
const request = {
|
||||
name: 'Retained evidence',
|
||||
strategy: 'sma-crossover',
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ async function fixture() {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8')
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ async function fixture(applyWorkspace = true, maxConnections = 10) {
|
|||
'19-canonical-research.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
]) {
|
||||
await pool.query(sql(name));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +61,9 @@ async function fixture(poolMax = 4, withReproduction = true) {
|
|||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
...(withReproduction ? ['21-run-reproduction.sql', '22-experiments.sql'] : []),
|
||||
...(withReproduction
|
||||
? ['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')
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue