import { fork } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { Hono } from 'hono'; import { Pool } from 'pg'; import { createHttpSecurity } from '@stock-bot/di'; 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 { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest'; import { canonicalRunRequestSchema, type CanonicalRunRequest, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { LegacyBacktestRunWriter } from '../../apps/stock/orchestrator/src/backtest/compatibility/LegacyBacktestRunWriter'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { loadDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes'; import { BacktestServiceV2, RunSubmissionConflictError, } from '../../apps/stock/web-api/src/services/backtest-v2.service'; import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; import { canonicalAdmissionFixture } from '../fixtures/canonical-admission'; import { canonicalSettings } from '../fixtures/canonical-research'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('durable-backtest-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); async function until(check: () => Promise, timeoutMs = 3_000) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { if (await check()) { return; } await sleep(20); } throw new Error('Timed out waiting for durable workflow'); } async function fixture(historical = false) { if ( !url || !new URL(url).pathname.startsWith('/stock_bot_safety') || !redisUrl || new URL(redisUrl).pathname !== '/15' ) { throw new Error('Dedicated stock_bot_safety database and Redis database 15 required'); } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, application_name: schema, options: `-c search_path=${schema}`, }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused'); CREATE TABLE backtests (id uuid PRIMARY KEY, name text NOT NULL, strategy text NOT NULL, symbols jsonb NOT NULL, start_date timestamptz NOT NULL, end_date timestamptz NOT NULL, initial_capital numeric NOT NULL, config jsonb, created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW()); CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id) ON DELETE CASCADE, run_number integer, status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text, started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz, created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number)); CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz, metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`); for (const filename of [ '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', '23-experiment-retries.sql', '24-chronological-validation.sql', '25-walk-forward.sql', '26-cost-sensitivity.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, 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 endpoint = new URL(redisUrl); const redis = { host: endpoint.hostname, port: Number(endpoint.port || 6379), db: 15, ...(endpoint.password ? { password: decodeURIComponent(endpoint.password) } : {}), }; const queueName = `stock-bot-safety-${randomUUID()}`; const queue = new Queue(queueName, redis, {}, { workers: 0 }, logger); await queue.getBullQueue().waitUntilReady(); cleanup.push(async () => { await queue.getBullQueue().obliterate({ force: true }); await queue.close(); }); const dispatcher = new BacktestDispatcher(postgres, queue, logger, { intervalMs: 20, republishMs: 50, maxAttempts: 3, }); cleanup.push(() => dispatcher.shutdown()); const api = new BacktestServiceV2({ postgres, logger }, async () => { throw new Error('No HTTP execution dispatch allowed'); }); const legacyDefinition = historical ? await api.createBacktest( { name: 'Durable fixture', strategy: 'sma-crossover', symbols: ['FIXTURE.TEST'], startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-03-15T00:00:00.000Z', initialCapital: 100000, config: { fastPeriod: 3, slowPeriod: 7, commission: 0, slippage: 0 }, }, { autoStart: false } ) : undefined; const canonical = historical ? undefined : await canonicalAdmissionFixture(pool, postgres, false); const definition = canonical?.draft ?? legacyDefinition!; const definitionInput = canonical?.definition ?? { name: definition.name, strategy: definition.strategy, symbols: definition.symbols, startDate: definition.startDate.toISOString(), endDate: definition.endDate.toISOString(), initialCapital: definition.initialCapital, config: definition.config, }; // This raw insertion represents already accepted pre-cutover history. It is // deliberately not exposed through a service or production admission switch. const historicalRun = async (_request: { backtestId: string }) => { if (!historical) { throw new Error('Historical fixture only'); } const runId = randomUUID(); const snapshot = backtestRequestFromDefinition(definitionInput, { runId, backtestId: definition.id, }); await pool.query( `INSERT INTO runs(id,backtest_id,run_number,request_snapshot) SELECT $1,$2,COALESCE(MAX(run_number),0)+1,$3 FROM runs WHERE backtest_id=$2`, [runId, definition.id, snapshot] ); await pool.query('INSERT INTO backtest_dispatch(run_id) VALUES($1)', [runId]); return { id: runId }; }; const repository = new PostgresBacktestRunRepository(postgres, 2_000); const legacyWriter = new LegacyBacktestRunWriter(postgres, 2_000); const history = { reads: 0, unavailable: false }; const storage = { async getHistoricalBars() { history.reads++; if (history.unavailable) { throw new Error('Provider history unavailable'); } return Array.from({ length: 70 }, (_, i) => { const close = 100 + Math.sin((i * Math.PI) / 6) * 8; return { symbol: 'FIXTURE.TEST', source: 'eod', timestamp: new Date(Date.parse(definition.startDate.toISOString()) + i * 86400000), open: close, high: close + 1, low: close - 1, close, volume: 1000000, }; }); }, } as unknown as StorageService; const engine = new RustBacktestAdapter({ logger }, { timeoutMs: 5_000 }); const runner = new BacktestRunner({ engine, repository, logger, heartbeatMs: 50, }); cleanup.push(() => runner.shutdown()); const enqueueWorker = () => { const registry = new HandlerRegistry(); registry.registerConfiguration({ name: 'orchestrator', operations: { 'run-backtest': async payload => runner.runQueued((payload as { runId: string }).runId), }, }); const worker = new Queue( queueName, redis, {}, { workers: 1, concurrency: 1, handlerRegistry: registry }, logger ); cleanup.push(async () => { await runner.shutdown(); await worker.close(); }); return worker; }; const snapshot = async (runId: string) => canonicalRunRequestSchema.parse( (await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0] .request_snapshot ); const legacySnapshot = async (runId: string) => BacktestConfigSchema.parse( (await pool.query('SELECT request_snapshot FROM runs WHERE id=$1', [runId])).rows[0] .request_snapshot ); const report = async (request: CanonicalRunRequest): Promise => ({ kind: 'canonical-result/v1', runId: request.runId, backtestId: request.backtestId, status: 'completed', completedAt: new Date().toISOString(), executionTime: 1, financialEngine: 'rust', strategyExecution: 'typescript-retained-builtin/v1', request, ...(await engine.runCanonical(request, async () => canonical!.dataset)), }); const expire = async (runId: string) => { await pool.query( "UPDATE runs SET lease_expires_at = NOW() - INTERVAL '1 second' WHERE id = $1", [runId] ); }; return { schema, pool, postgres, api, definition, definitionInput, repository, legacyWriter, runner, engine, queue, dispatcher, enqueueWorker, snapshot, legacySnapshot, historicalRun, report, canonical, expire, history, storage, }; } describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => { test('idempotent_submission_postgres_race: one snapshot/outbox, canonical null speed and stable original intent after edits', async () => { const f = await fixture(); const submission = { principal: 'operator' as const, key: 'same-intent' }; const runs = await Promise.all( Array.from({ length: 8 }, (_, i) => f.api.createRun( { backtestId: f.definition.id, ...(i % 2 ? { speedMultiplier: null } : {}) }, submission ) ) ); expect(new Set(runs.map(run => run.id)).size).toBe(1); const original = await f.snapshot(runs[0]!.id); await f.api.updateBacktest(f.definition.id, { initialCapital: 12345, strategyParameters: { fastPeriod: 3, slowPeriod: 4 }, }); expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( runs[0]!.id ); expect(await f.snapshot(runs[0]!.id)).toEqual(original); expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(1); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); await expect( f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 2 }, submission) ).rejects.toBeInstanceOf(RunSubmissionConflictError); }); test('submission_key_conflict: different definitions racing for one principal/key cannot both commit', async () => { const f = await fixture(); const second = await f.api.createBacktest( { ...f.definitionInput, startDate: f.definition.startDate.toISOString(), endDate: f.definition.endDate.toISOString(), name: 'Second', }, { autoStart: false } ); const barrierKey = parseInt(randomUUID().slice(0, 7), 16); await f.pool .query(`CREATE FUNCTION delay_submission() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock_shared(40303, ${barrierKey}); RETURN NEW; END $$; CREATE TRIGGER delay_submission BEFORE INSERT ON runs FOR EACH ROW EXECUTE FUNCTION delay_submission()`); const submission = { principal: 'operator' as const, key: 'cross-definition' }; const barrier = await f.pool.connect(); await barrier.query('SELECT pg_advisory_lock(40303, $1)', [barrierKey]); const submissions = Promise.allSettled( [f.definition.id, second.id].map(backtestId => f.api.createRun({ backtestId }, submission)) ); try { // Both requests passed their initial receipt lookup and hold distinct parent // locks. One waits inside INSERT; the other waits on the shared strategy // family lock. The stale second receipt lookup must still conflict after // the first transaction commits, rather than returning its unrelated run. await until( async () => ( await f.pool.query( "SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'", [f.schema] ) ).rows[0].count === 2 ); expect( ( await f.pool.query( "SELECT count(*)::int AS count FROM pg_locks WHERE locktype='advisory' AND classid=40303 AND objid=$1 AND NOT granted", [barrierKey] ) ).rows[0].count ).toBe(1); expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); } finally { await barrier.query('SELECT pg_advisory_unlock(40303, $1)', [barrierKey]); barrier.release(); } const outcomes = await submissions; expect(outcomes.filter(outcome => outcome.status === 'fulfilled')).toHaveLength(1); const rejection = outcomes.find(outcome => outcome.status === 'rejected'); expect(rejection?.status === 'rejected' && rejection.reason).toBeInstanceOf( RunSubmissionConflictError ); const committed = (await f.pool.query('SELECT * FROM runs')).rows; expect(committed).toHaveLength(1); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); const otherId = committed[0].backtest_id === f.definition.id ? second.id : f.definition.id; await expect(f.api.createRun({ backtestId: otherId }, submission)).rejects.toBeInstanceOf( RunSubmissionConflictError ); }); test('different principals can reuse keys; concurrent distinct and unkeyed submissions preserve run numbering', async () => { const f = await fixture(); const runs = await Promise.all([ f.api.createRun({ backtestId: f.definition.id }, { principal: 'operator', key: 'shared' }), f.api.createRun({ backtestId: f.definition.id }, { principal: 'service', key: 'shared' }), ...Array.from({ length: 4 }, (_, i) => f.api.createRun( { backtestId: f.definition.id }, { principal: 'operator', key: `intent-${i}` } ) ), f.api.createRun({ backtestId: f.definition.id }), f.api.createRun({ backtestId: f.definition.id }), ]); expect(new Set(runs.map(run => run.id)).size).toBe(8); expect(runs.map(run => run.runNumber).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]); expect( (await f.pool.query('SELECT * FROM runs WHERE submission_key IS NULL')).rows ).toHaveLength(2); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(8); }); test('outbox failure rolls back the submission claim and retry creates exactly one run', async () => { const f = await fixture(); await f.pool .query(`CREATE FUNCTION reject_submission_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected submission outbox failure'; END $$; CREATE TRIGGER reject_submission_outbox BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_submission_outbox()`); const submission = { principal: 'operator' as const, key: 'retry-after-rollback' }; await expect(f.api.createRun({ backtestId: f.definition.id }, submission)).rejects.toThrow( 'injected submission' ); expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); await f.pool.query('DROP TRIGGER reject_submission_outbox ON backtest_dispatch'); const created = await f.api.createRun({ backtestId: f.definition.id }, submission); expect((await f.api.createRun({ backtestId: f.definition.id }, submission)).id).toBe( created.id ); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(1); }); test('save_only catalog route requires explicit false; authenticated keyed submissions return202/Location or409', async () => { const f = await fixture(); const app = new Hono(); createHttpSecurity({ disabled: true, environment: 'test' }).mount(app); app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); const body = { ...f.definitionInput, autoStart: false }; expect( ( await app.request('/api/v2/backtests', { method: 'POST', body: JSON.stringify({ ...body, autoStart: 'false' }), }) ).status ).toBe(400); const saved = await app.request('/api/v2/backtests', { method: 'POST', body: JSON.stringify(body), }); expect(saved.status).toBe(201); const definition = await saved.json(); expect(await f.api.listRuns(definition.id)).toHaveLength(0); const post = (payload: object) => app.request(`/api/v2/backtests/${definition.id}/runs`, { method: 'POST', headers: { 'Idempotency-Key': 'route-retry' }, body: JSON.stringify(payload), }); const response = await post({}); expect(response.status).toBe(202); const run = await response.json(); expect(response.headers.get('Location')).toBe(`/api/v2/runs/${run.id}`); expect((await (await post({ speedMultiplier: null })).json()).id).toBe(run.id); expect((await post({ speedMultiplier: 2 })).status).toBe(409); const saveOnly = await app.request('/api/v2/backtests', { method: 'POST', body: JSON.stringify({ ...body, autoStart: undefined }), }); expect(saveOnly.status).toBe(400); expect((await f.pool.query('SELECT count(*)::int AS count FROM backtests')).rows[0].count).toBe( 2 ); }); test('cookie renewal and admin bearer replay the same operator submission while service keys are separate', async () => { const f = await fixture(); const adminToken = 'submission-fixture-admin-not-a-secret-123456'; const serviceToken = 'submission-fixture-service-not-a-secret-123456'; const app = new Hono(); createHttpSecurity({ adminToken, serviceToken, browserSessions: true, origins: ['http://ui.test'], }).mount(app); app.route('/', createBacktestV2Routes({ postgres: f.postgres, logger })); const submit = async (headers: Record) => { const response = await app.request(`/api/v2/backtests/${f.definition.id}/runs`, { method: 'POST', headers: { 'Idempotency-Key': 'authenticated-intent', 'X-Principal': 'spoofed', ...headers, }, body: '{}', }); expect(response.status).toBe(202); return (await response.json()).id as string; }; const original = await submit({ Authorization: `Bearer ${adminToken}` }); for (let i = 0; i < 2; i++) { const login = await app.request('/api/auth/session', { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: 'http://ui.test' }, body: JSON.stringify({ token: adminToken }), }); expect(login.status).toBe(200); expect( await submit({ Cookie: login.headers.get('Set-Cookie')!.split(';')[0]!, Origin: 'http://ui.test', }) ).toBe(original); } expect(await submit({ Authorization: `Bearer ${serviceToken}` })).not.toBe(original); expect( (await f.pool.query('SELECT submission_principal FROM runs ORDER BY run_number')).rows ).toEqual([{ submission_principal: 'operator' }, { submission_principal: 'service' }]); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(2); }); test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => { const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); const dataset = await loadDataset(f.storage, config); await f.pool .query(`CREATE FUNCTION delay_snapshot() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(0.35); RETURN NEW; END $$; CREATE TRIGGER delay_snapshot BEFORE INSERT ON backtest_datasets FOR EACH ROW EXECUTE FUNCTION delay_snapshot()`); const short = new LegacyBacktestRunWriter(f.postgres, 250); const claim = await short.start(config); await expect(short.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toBeInstanceOf( BacktestLeaseLostError ); expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); expect( (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] .dataset_hash ).toBeNull(); }); test('retained canonical inputs survive owner loss and replay without provider reads', async () => { const f = await fixture(); const first = await f.api.createRun({ backtestId: f.definition.id }); await f.runner.runQueued(first.id); const baseline = await f.api.getRunResults(first.id); const run = await f.api.createRun({ backtestId: f.definition.id }); const old = await f.repository.startCanonical(await f.snapshot(run.id)); const frozen = await f.repository.loadCanonicalDataset( run.id, old.attemptId, f.canonical!.dataset.manifest.hash ); await f.expire(run.id); await expect( f.repository.loadCanonicalDataset(run.id, old.attemptId, frozen.manifest.hash) ).rejects.toBeInstanceOf(BacktestLeaseLostError); f.history.unavailable = true; await f.dispatcher.tick(); await f.runner.runQueued(run.id); const replay = await f.api.getRunResults(run.id); if (!baseline || !replay || !('financial' in baseline) || !('financial' in replay)) { throw new Error('Canonical results required'); } expect(f.history.reads).toBe(0); expect(replay.financial.projection.valuation).toEqual(baseline.financial.projection.valuation); expect(replay.financial.projection.fills).toEqual(baseline.financial.projection.fills); expect(replay.analytics).toEqual(baseline.analytics); expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1); }); test('snapshot insertion and the run pointer roll back together; frozen inputs cannot be replaced', async () => { const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); await f.pool .query(`CREATE FUNCTION reject_dataset_pointer() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.dataset_hash IS NOT NULL THEN RAISE EXCEPTION 'injected snapshot pointer failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_dataset_pointer BEFORE UPDATE ON runs FOR EACH ROW EXECUTE FUNCTION reject_dataset_pointer()`); await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset)).rejects.toThrow( 'injected' ); expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); expect( (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] .dataset_hash ).toBeNull(); await f.pool.query('DROP TRIGGER reject_dataset_pointer ON runs'); await f.legacyWriter.freezeDataset(run.id, claim.attemptId, dataset); const different = await loadDataset(f.storage, { ...config, dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' }, endDate: '2024-03-16T00:00:00.000Z', }); await expect(f.legacyWriter.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow( 'already frozen' ); expect((await f.legacyWriter.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe( dataset.manifest.hash ); }); test('cancellation after snapshot insertion aborts preparation and rolls back the run pointer and payload', async () => { const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); const controller = new AbortController(); const reason = new BacktestCancelledError(); const repository = new LegacyBacktestRunWriter({ transaction: work => f.postgres.transaction(client => work( new Proxy(client, { get(target, key) { if (key !== 'query') { return Reflect.get(target, key); } return async (sql: string, params?: unknown[]) => { const result = await target.query(sql, params); if (sql.startsWith('INSERT INTO backtest_datasets')) { controller.abort(reason); } return result; }; }, }) ) ), }); await expect( repository.freezeDataset(run.id, claim.attemptId, dataset, controller.signal) ).rejects.toBe(reason); expect((await f.pool.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); expect( (await f.pool.query('SELECT dataset_hash FROM runs WHERE id = $1', [run.id])).rows[0] .dataset_hash ).toBeNull(); await expect( repository.loadDataset(run.id, claim.attemptId, undefined, controller.signal) ).rejects.toBe(reason); }); test('restored snapshots are revalidated rather than trusted by their content-addressed key', async () => { const f = await fixture(true); const run = await f.historicalRun({ backtestId: f.definition.id }); const config = await f.legacySnapshot(run.id); const claim = await f.legacyWriter.start(config); const dataset = await loadDataset(f.storage, config); // Model corrupt historical storage at initial insertion; retained evidence cannot be edited. const corrupt = structuredClone(dataset); corrupt.bars[0]!.volume = 0; await f.pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [ dataset.manifest.hash, corrupt, ]); await f.pool.query('UPDATE runs SET dataset_hash=$2 WHERE id=$1', [ run.id, dataset.manifest.hash, ]); const reads = f.history.reads; f.history.unavailable = true; await expect(f.legacyWriter.loadDataset(run.id, claim.attemptId)).rejects.toThrow( 'hash/content' ); await f.expire(run.id); await f.dispatcher.tick(); expect((await f.runner.runQueued(run.id)).status).toBe('failed'); expect((await f.api.getRun(run.id))?.error).toContain('Legacy backtest execution is retired'); expect((await f.api.getRun(run.id))?.status).toBe('failed'); expect(await f.api.getRunResults(run.id)).toBeNull(); expect(f.history.reads).toBe(reads); }); test('a missing retained dataset fails a historical request without provider fallback', async () => { const f = await fixture(true); const runId = randomUUID(); const snapshot = backtestRequestFromDefinition( { ...f.definitionInput, config: { ...f.definition.config, datasetHash: 'f'.repeat(64) } }, { runId, backtestId: f.definition.id } ); // Imported history can reference unavailable storage; retain its request and report the loss. await f.pool.query( 'INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,$3)', [runId, f.definition.id, snapshot] ); await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [runId]); f.history.unavailable = true; expect((await f.runner.runQueued(runId)).status).toBe('failed'); expect((await f.api.getRun(runId))?.error).toContain('Legacy backtest execution is retired'); expect(f.history.reads).toBe(0); expect((await f.api.getRun(runId))?.status).toBe('failed'); expect(await f.api.getRunResults(runId)).toBeNull(); }); test('canonical admission rejects template ranges inconsistent with its retained dataset', async () => { const f = await fixture(); await expect( f.api.updateBacktest(f.definition.id, { endDate: '2025-01-01T00:00:00.000Z' }) ).rejects.toThrow('trade bounds'); await f.pool.query('UPDATE backtests SET end_date=$2 WHERE id=$1', [ f.definition.id, '2025-01-01T00:00:00.000Z', ]); await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(); expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0); }); test('canonical admission rejects malformed policy and legacy pacing before run/outbox writes', async () => { const f = await fixture(); await expect( f.api.createRun({ backtestId: f.definition.id, speedMultiplier: 7 }) ).rejects.toThrow('maximum speed'); await f.pool.query('UPDATE backtests SET config=$2 WHERE id=$1', [ f.definition.id, { ...f.definition.config, canonical: { ...canonicalSettings, feeRate: '-1' } }, ]); await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow(); expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rows).toHaveLength(0); }); test('acceptance commits run + immutable snapshot + intent atomically, with no Redis/HTTP dependency', async () => { const f = await fixture(); await f.pool .query(`CREATE FUNCTION reject_dispatch() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox failure'; END $$; CREATE TRIGGER reject_dispatch BEFORE INSERT ON backtest_dispatch FOR EACH ROW EXECUTE FUNCTION reject_dispatch();`); await expect(f.api.createRun({ backtestId: f.definition.id })).rejects.toThrow( 'injected outbox' ); expect((await f.pool.query('SELECT * FROM runs')).rows).toHaveLength(0); await f.pool.query('DROP TRIGGER reject_dispatch ON backtest_dispatch'); const response = await createBacktestV2Routes({ postgres: f.postgres, logger }).request( `/api/v2/backtests/${f.definition.id}/runs`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' } ); expect(response.status).toBe(202); const run = (await response.json()) as { id: string; status: string }; expect(response.headers.get('location')).toBe(`/api/v2/runs/${run.id}`); expect(f.queue.getWorkerCount()).toBe(0); expect(run.status).toBe('pending'); expect( (await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [run.id])).rows ).toHaveLength(1); await f.api.updateBacktest(f.definition.id, { strategyParameters: { fastPeriod: 3, slowPeriod: 4 }, name: 'Mutated after admission', }); // A fresh dispatcher models an API restart after SQL commit but before the first publish. const restarted = new BacktestDispatcher(f.postgres, f.queue, logger); await restarted.tick(); await restarted.shutdown(); f.enqueueWorker(); await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); const result = await f.api.getRunResults(run.id); expect(result).toHaveProperty('kind', 'canonical-result/v1'); if (!result || !('request' in result)) { throw new Error('Canonical result required'); } expect(result.request.strategy.selection.instrumentId).toBe(f.definition.symbols[0]!); expect(result.request.strategy.selection.parameters).toMatchObject({ fastPeriod: 2 }); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); }); test('duplicate deliveries and competing claims execute once and persist exactly one result', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const config = await f.snapshot(run.id); const claims = await Promise.allSettled([ f.repository.startCanonical(config), f.repository.startCanonical(config), ]); expect(claims.filter(result => result.status === 'fulfilled')).toHaveLength(1); expect(claims.filter(result => result.status === 'rejected')).toHaveLength(1); await f.expire(run.id); await f.dispatcher.tick(); f.enqueueWorker(); await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); await f.runner.runQueued(run.id); await f.runner.runQueued(run.id); await f.queue.add('duplicate', { handler: 'orchestrator', operation: 'run-backtest', payload: { runId: run.id }, }); await until(async () => (await f.queue.getStats()).completed > 0); expect( (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows ).toHaveLength(1); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2); }); test('expired owners cannot heartbeat, write progress/control/failure/cancellation, or commit a stale result', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const request = await f.snapshot(run.id); const old = await f.repository.startCanonical(request); const result = await f.report(request); await f.expire(run.id); await f.dispatcher.tick(); const replacement = await f.repository.startCanonical(await f.snapshot(run.id)); await expect(f.repository.heartbeat(run.id, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError ); await expect( f.repository.updateProgress(run.id, 99, undefined, old.attemptId) ).rejects.toBeInstanceOf(BacktestLeaseLostError); await expect( f.legacyWriter.updateControl(run.id, { status: 'paused' }, old.attemptId) ).rejects.toBeInstanceOf(BacktestLeaseLostError); await expect(f.repository.cancel(run.id, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError ); await f.repository.fail(run.id, 'stale failure', old.attemptId); await expect(f.repository.completeCanonical(result, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError ); expect((await f.api.getRun(run.id))?.status).toBe('running'); await f.repository.loadCanonicalDataset(run.id, replacement.attemptId, request.datasetHash); await f.repository.completeCanonical(result, replacement.attemptId); expect( (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows ).toHaveLength(1); }); test('healthy heartbeats prevent reclamation; cancellation before claim never executes', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const shortLease = new PostgresBacktestRunRepository(f.postgres, 300); const claim = await shortLease.startCanonical(await f.snapshot(run.id)); await sleep(200); await shortLease.heartbeat(run.id, claim.attemptId); await sleep(150); await f.dispatcher.tick(); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); expect((await f.api.getRun(run.id))?.status).toBe('running'); const queued = await f.api.createRun({ backtestId: f.definition.id }); await f.api.cancelRun(queued.id); await f.api.cancelRun(queued.id); expect((await f.runner.runQueued(queued.id)).status).toBe('cancelled'); expect((await f.api.getRun(queued.id))?.attemptNumber).toBe(0); expect(await f.api.getRunResults(queued.id)).toBeNull(); }); test('a heartbeat blocked behind a row lock cannot resurrect an expired lease using transaction-start time', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const shortLease = new PostgresBacktestRunRepository(f.postgres, 300); const claim = await shortLease.startCanonical(await f.snapshot(run.id)); const lock = await f.pool.connect(); let renewal: Promise | undefined; try { await lock.query('BEGIN'); await lock.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [run.id]); renewal = shortLease.heartbeat(run.id, claim.attemptId).catch(error => error); await sleep(400); await lock.query('COMMIT'); expect(await renewal).toBeInstanceOf(BacktestLeaseLostError); } finally { await lock.query('ROLLBACK'); lock.release(); } await f.dispatcher.tick(); expect((await f.api.getRun(run.id))?.status).toBe('pending'); }); test('cancellation wins against late completion and expires an abandoned cancelled owner truthfully', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const claim = await f.repository.startCanonical(await f.snapshot(run.id)); const result = await f.report(await f.snapshot(run.id)); await f.api.cancelRun(run.id); expect((await f.repository.heartbeat(run.id, claim.attemptId)).cancelRequested).toBe(true); await expect(f.repository.completeCanonical(result, claim.attemptId)).rejects.toBeInstanceOf( BacktestCancelledError ); await f.expire(run.id); await f.dispatcher.tick(); expect((await f.api.getRun(run.id))?.status).toBe('cancelled'); expect(await f.api.getRunResults(run.id)).toBeNull(); }); test('expired attempts retry at most three times, then become failed without a result', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); for (let attempt = 1; attempt <= 3; attempt++) { await f.repository.startCanonical(await f.snapshot(run.id)); await f.expire(run.id); await f.dispatcher.tick(); expect((await f.api.getRun(run.id))?.status).toBe(attempt === 3 ? 'failed' : 'pending'); } expect((await f.api.getRun(run.id))?.error).toContain('retry limit'); expect((await f.runner.runQueued(run.id)).status).toBe('failed'); expect(await f.api.getRunResults(run.id)).toBeNull(); }); test('a hard-killed execution process is recovered by a fresh dispatcher and owner', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const child = fork( fileURLToPath(new URL('../fixtures/backtest-crash-owner.ts', import.meta.url)), [], { execPath: process.execPath, execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'], env: { ...process.env, BACKTEST_FIXTURE_SCHEMA: f.schema, BACKTEST_FIXTURE_RUN_ID: run.id }, } ); const closed = new Promise(resolve => child.once('close', () => resolve())); cleanup.push(async () => { child.kill('SIGKILL'); await closed; }); await new Promise((resolve, reject) => { const timeout = setTimeout(() => reject(new Error('Crash owner did not claim')), 3_000); child.once('message', () => { clearTimeout(timeout); resolve(); }); child.once('error', reject); child.once('exit', code => { clearTimeout(timeout); if (code) { reject(new Error(`Crash owner exited: ${code}`)); } }); }); expect((await f.api.getRun(run.id))?.status).toBe('running'); child.kill('SIGKILL'); await closed; // Wait for the real lease; do not alter the crashed owner's SQL state. await sleep(550); await f.dispatcher.tick(); f.enqueueWorker(); await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(2); expect( (await f.pool.query('SELECT * FROM backtest_results WHERE run_id = $1', [run.id])).rows ).toHaveLength(1); }); test('publication failure retains intent; a restarted publisher recovers the same accepted run', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const connection = await f.queue.getBullQueue().client; connection.disconnect(); await expect(f.dispatcher.tick()).rejects.toThrow(); // Only this fixture producer's socket is disconnected; no shared Redis data is touched. await connection.connect(); expect((await f.api.getRun(run.id))?.status).toBe('pending'); await sleep(60); await f.dispatcher.tick(); f.enqueueWorker(); await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); }); test('lost Redis notifications are republished; concurrent publishers reserve each SQL intent once', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const second = new BacktestDispatcher(f.postgres, f.queue, logger, { intervalMs: 20, republishMs: 50, maxAttempts: 3, }); await Promise.all([f.dispatcher.tick(), second.tick()]); expect( ( await f.pool.query('SELECT publish_count FROM backtest_dispatch WHERE run_id = $1', [ run.id, ]) ).rows[0].publish_count ).toBe(1); const notification = await f.queue.getJob(`backtest-${run.id}`); await notification!.remove(); await sleep(60); await second.tick(); await second.shutdown(); f.enqueueWorker(); await until(async () => (await f.api.getRun(run.id))?.status === 'completed'); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(1); }); test('invalid persisted snapshots become failed instead of remaining stranded pending', async () => { const f = await fixture(true); const run = { id: randomUUID() }; // A legacy malformed snapshot is inserted as found, not fabricated by editing retained evidence. await f.pool.query( "INSERT INTO runs(id,backtest_id,run_number,request_snapshot) VALUES ($1,$2,1,'{}')", [run.id, f.definition.id] ); await f.pool.query('INSERT INTO backtest_dispatch(run_id) VALUES ($1)', [run.id]); await expect(f.runner.runQueued(run.id)).rejects.toThrow(); expect((await f.api.getRun(run.id))?.status).toBe('failed'); expect((await f.api.getRun(run.id))?.attemptNumber).toBe(0); }); test('migration replay preserves leased owners, backfills legacy pending snapshots, and fails ownerless legacy runs', async () => { const f = await fixture(true); const pending = { id: randomUUID() }; await f.pool.query('INSERT INTO runs(id,backtest_id,run_number) VALUES ($1,$2,1)', [ pending.id, f.definition.id, ]); const active = await f.historicalRun({ backtestId: f.definition.id }); const oldActive = await f.historicalRun({ backtestId: f.definition.id }); const claim = await f.legacyWriter.start(await f.legacySnapshot(active.id)); await f.pool.query("UPDATE runs SET status = 'running' WHERE id = $1", [oldActive.id]); const migration = readFileSync( new URL('../../database/postgres/init/10-durable-backtest-dispatch.sql', import.meta.url), 'utf8' ); await f.pool.query(migration); await f.pool.query(migration); expect((await f.legacySnapshot(pending.id)).startDate).toBe('2024-01-01T00:00:00.000Z'); expect( (await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id = $1', [pending.id])).rows ).toHaveLength(1); expect((await f.api.getRun(oldActive.id))?.status).toBe('failed'); expect((await f.repository.heartbeat(active.id, claim.attemptId)).cancelRequested).toBe(false); await f.runner.runQueued(pending.id); expect((await f.api.getRun(pending.id))?.status).toBe('failed'); expect((await f.api.getRun(pending.id))?.error).toContain( 'Legacy backtest execution is retired' ); }); });