844 lines
35 KiB
TypeScript
844 lines
35 KiB
TypeScript
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', '24-chronological-validation.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);
|
|
// Current services require the later validation columns; verify SQL23 evidence first.
|
|
await f.pool.query(
|
|
readFileSync(
|
|
new URL('../../database/postgres/init/24-chronological-validation.sql', import.meta.url),
|
|
'utf8'
|
|
)
|
|
);
|
|
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);
|
|
});
|
|
});
|