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 { 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 { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; 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 } from '../../apps/stock/web-api/src/services/backtest-v2.service'; import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; 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() { 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, 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', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${filename}`, import.meta.url), 'utf8') ); } const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', user: '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 definition = 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 } ); const repository = new PostgresBacktestRunRepository(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, custom: { StorageService: storage, }, }, { timeoutMs: 5_000 } ); const runner = new BacktestRunner({ engine, engineName: 'native', 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) => BacktestConfigSchema.parse( (await pool.query('SELECT request_snapshot FROM runs WHERE id = $1', [runId])).rows[0] .request_snapshot ); 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, repository, runner, engine, queue, dispatcher, enqueueWorker, snapshot, expire, history, storage, }; } describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => { test('a lease expiring during snapshot insertion cannot pin or leave an orphan snapshot', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); const config = await f.snapshot(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 PostgresBacktestRunRepository(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('prepared snapshots survive owner loss and replay through JSONB without provider reads', async () => { const f = await fixture(); const first = await f.runner.runQueued( (await f.api.createRun({ backtestId: f.definition.id })).id ); const baseline = (await f.api.getRunResults(first.runId))!; const run = await f.api.createRun({ backtestId: f.definition.id }); const old = await f.repository.start(await f.snapshot(run.id)); const frozen = await f.repository.loadDataset( run.id, old.attemptId, baseline.config.dataset!.hash ); expect(frozen?.bars).toHaveLength(70); await f.expire(run.id); await expect(f.repository.loadDataset(run.id, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError ); await expect(f.repository.freezeDataset(run.id, old.attemptId, frozen!)).rejects.toBeInstanceOf( BacktestLeaseLostError ); const reads = f.history.reads; f.history.unavailable = true; await f.dispatcher.tick(); await f.runner.runQueued(run.id); const replay = (await f.api.getRunResults(run.id))!; expect(f.history.reads).toBe(reads); expect(replay.config.dataset).toEqual(baseline.config.dataset); expect(replay.trades).toEqual(baseline.trades); expect(replay.metrics).toEqual(baseline.metrics); 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(); const run = await f.api.createRun({ backtestId: f.definition.id }); const config = await f.snapshot(run.id); const claim = await f.repository.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.repository.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.repository.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.repository.freezeDataset(run.id, claim.attemptId, different)).rejects.toThrow( 'already frozen' ); expect((await f.repository.loadDataset(run.id, claim.attemptId))?.manifest.hash).toBe( dataset.manifest.hash ); }); test('an explicit dataset replay rejects a different listing or date range', async () => { const f = await fixture(); const run = await f.api.createRun({ backtestId: f.definition.id }); await f.runner.runQueued(run.id); const result = (await f.api.getRunResults(run.id))!; await expect( f.runner.runBacktest({ ...(await f.snapshot(run.id)), runId: undefined, endDate: '2024-03-16T00:00:00.000Z', datasetHash: result.config.dataset!.hash, }) ).rejects.toThrow('does not match'); }); 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, { config: { fastPeriod: 999 }, symbols: ['MUTATED.TEST'], }); // 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?.config.symbols).toEqual(['FIXTURE.TEST']); expect(result?.config.parameters.fastPeriod).toBe(3); 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.start(config), f.repository.start(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 baseline = await f.runner.runBacktest({ ...(await f.snapshot((await f.api.createRun({ backtestId: f.definition.id })).id)), }); const run = await f.api.createRun({ backtestId: f.definition.id }); const old = await f.repository.start(await f.snapshot(run.id)); await f.expire(run.id); await f.dispatcher.tick(); const replacement = await f.repository.start(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.repository.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); const result = { ...baseline, runId: run.id }; await expect(f.repository.complete(result, old.attemptId)).rejects.toBeInstanceOf( BacktestLeaseLostError ); expect((await f.api.getRun(run.id))?.status).toBe('running'); await f.repository.loadDataset(run.id, replacement.attemptId, baseline.config.dataset!.hash); await f.repository.complete(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.start(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.start(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.start(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.complete( { runId: run.id, backtestId: f.definition.id, status: 'completed', completedAt: new Date().toISOString(), } as never, 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.start(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(); const run = await f.api.createRun({ backtestId: f.definition.id }); await f.pool.query("UPDATE runs SET request_snapshot = '{}' WHERE id = $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(); const pending = await f.api.createRun({ backtestId: f.definition.id }); const active = await f.api.createRun({ backtestId: f.definition.id }); const oldActive = await f.api.createRun({ backtestId: f.definition.id }); const claim = await f.repository.start(await f.snapshot(active.id)); await f.pool.query('DELETE FROM backtest_dispatch WHERE run_id = $1', [pending.id]); await f.pool.query('UPDATE runs SET request_snapshot = NULL WHERE id = $1', [pending.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.snapshot(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('completed'); }); });