more stuff
This commit is contained in:
parent
c3cb36c8d6
commit
7dec0be3b4
26 changed files with 1394 additions and 275 deletions
40
test/fixtures/backtest-crash-owner.ts
vendored
Normal file
40
test/fixtures/backtest-crash-owner.ts
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
/** Dedicated fixture process: claim a real SQL run, heartbeat, then await a hard kill. */
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
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';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const schema = process.env.BACKTEST_FIXTURE_SCHEMA;
|
||||
const runId = process.env.BACKTEST_FIXTURE_RUN_ID;
|
||||
if (
|
||||
!url ||
|
||||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
|
||||
!schema ||
|
||||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
|
||||
!runId
|
||||
)
|
||||
throw new Error('Unsafe crash fixture target');
|
||||
const logger = getLogger('crash-owner');
|
||||
const pool = new Pool({ connectionString: url, options: `-c search_path=${schema}` });
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 500);
|
||||
const runner = new BacktestRunner({
|
||||
engine: new RustBacktestAdapter({ logger }),
|
||||
engineName: 'native',
|
||||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
prepare: async () => {
|
||||
process.send?.({ type: 'claimed' });
|
||||
await new Promise<void>(() => {});
|
||||
},
|
||||
});
|
||||
await runner.runQueued(runId);
|
||||
|
|
@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { newDb } from 'pg-mem';
|
||||
import { DataType, newDb } from 'pg-mem';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
|
|
@ -17,6 +17,7 @@ import {
|
|||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { normalizeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/result';
|
||||
import { BacktestLeaseLostError } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
||||
|
|
@ -60,6 +61,12 @@ async function fixture(
|
|||
) {
|
||||
// PostgreSQL protocol is replaced with an in-process database; SQL and transaction manager are real.
|
||||
const db = newDb();
|
||||
db.public.registerFunction({
|
||||
name: 'clock_timestamp',
|
||||
returns: DataType.timestamptz,
|
||||
impure: true,
|
||||
implementation: () => new Date(),
|
||||
});
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||
|
|
@ -68,7 +75,11 @@ async function fixture(
|
|||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), 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,
|
||||
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0,
|
||||
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
|
||||
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
|
||||
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
|
||||
execution_time numeric, configuration jsonb, engine text);`);
|
||||
|
|
@ -115,7 +126,14 @@ async function fixture(
|
|||
engineOptions
|
||||
);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository,
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
heartbeatTimeoutMs: 500,
|
||||
});
|
||||
cleanup.unshift(() => runner.shutdown());
|
||||
const services = { logger, postgres, custom: { BacktestRunner: runner } };
|
||||
const routes = new Hono().route('/api/backtest', createBacktestRoutes(services));
|
||||
|
|
@ -203,51 +221,39 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => {
|
||||
const f = await fixture();
|
||||
let finish!: () => void;
|
||||
const finished = new Promise<void>(resolve => {
|
||||
finish = resolve;
|
||||
});
|
||||
let forwarded: Record<string, unknown> = {};
|
||||
const api = new BacktestServiceV2(f.services, async (url, init) => {
|
||||
forwarded = JSON.parse(String(init?.body));
|
||||
const response = await f.routes.request(new URL(url).pathname, init);
|
||||
finish();
|
||||
return response;
|
||||
const api = new BacktestServiceV2(f.services, async () => {
|
||||
throw new Error('Queued execution must not use HTTP dispatch');
|
||||
});
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: config.name!, config: { ...config.config, commission: 0, slippage: 0 } },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
|
||||
await finished;
|
||||
expect(forwarded.config).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(forwarded.speed).toBe('max');
|
||||
expect(run.status).toBe('pending');
|
||||
const snapshot = (
|
||||
await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])
|
||||
).rows[0]?.request_snapshot;
|
||||
expect(snapshot.config).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(snapshot.speed).toBe('max');
|
||||
await f.runner.runQueued(run.id);
|
||||
expect((await api.getRun(run.id))?.status).toBe('completed');
|
||||
const saved = await api.getRunResults(run.id);
|
||||
expect(saved?.config.parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(saved?.engine).toBe('native');
|
||||
expect(saved?.trades.length).toBeGreaterThan(0);
|
||||
await api.updateRunProgress(run.id, { progress: 2 });
|
||||
await api.updateRunProgress(run.id, { progress: 2, attemptId: randomUUID() });
|
||||
expect((await api.getRun(run.id))?.status).toBe('completed');
|
||||
expect((await api.getRun(run.id))?.progress).toBe(100);
|
||||
});
|
||||
|
||||
test('the V1 facade creates runs instead of writing removed backtest status columns', async () => {
|
||||
const f = await fixture();
|
||||
let finish!: () => void;
|
||||
const finished = new Promise<void>(resolve => {
|
||||
finish = resolve;
|
||||
});
|
||||
const api = new BacktestService(f.services, async (url, init) => {
|
||||
const response = await f.routes.request(new URL(url).pathname, init);
|
||||
finish();
|
||||
return response;
|
||||
});
|
||||
const api = new BacktestService(f.services);
|
||||
const created = await api.createBacktest({
|
||||
...config,
|
||||
config: { ...config.config, commission: 0, slippage: 0 },
|
||||
});
|
||||
await finished;
|
||||
await f.runner.runQueued(created.runId!);
|
||||
expect((await api.getBacktest(created.id))?.status).toBe('completed');
|
||||
expect((await api.getBacktestResults(created.id))?.runId).toBe(created.runId);
|
||||
});
|
||||
|
|
@ -321,9 +327,9 @@ describe('one backtest execution workflow', () => {
|
|||
},
|
||||
}),
|
||||
});
|
||||
await expect(new PostgresBacktestRunRepository(postgres).complete(result)).rejects.toThrow(
|
||||
'Insert failed'
|
||||
);
|
||||
await expect(
|
||||
new PostgresBacktestRunRepository(postgres).complete(result, randomUUID())
|
||||
).rejects.toThrow('Insert failed');
|
||||
expect(statements[0]).toBe('BEGIN');
|
||||
expect(statements.at(-1)).toBe('ROLLBACK');
|
||||
expect(statements).not.toContain('COMMIT');
|
||||
|
|
@ -357,7 +363,7 @@ describe('one backtest execution workflow', () => {
|
|||
expect(JSON.parse(String(init?.body)).runId).toBe(result.runId);
|
||||
return new Response('Unsupported', { status: 501 });
|
||||
});
|
||||
await expect(api.cancelRun(result.runId)).rejects.toThrow('was not acknowledged');
|
||||
await expect(api.cancelRun(result.runId)).rejects.toThrow('No cancellable run');
|
||||
expect((await api.getRun(result.runId))?.status).toBe('completed');
|
||||
});
|
||||
|
||||
|
|
@ -619,10 +625,10 @@ describe('isolated native backtest workers', () => {
|
|||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
f.repository.complete = async result => {
|
||||
f.repository.complete = async (result, attemptId) => {
|
||||
entered();
|
||||
await gate;
|
||||
await complete(result);
|
||||
await complete(result, attemptId);
|
||||
};
|
||||
const running = f.runner.runBacktest(config);
|
||||
await committing;
|
||||
|
|
@ -675,6 +681,25 @@ describe('isolated native backtest workers', () => {
|
|||
expect(result.engine).toBe('native');
|
||||
});
|
||||
|
||||
test.each(['rejected', 'hung'])(
|
||||
'%s heartbeat kills a blocking worker and leaves the abandoned attempt recoverable',
|
||||
async behavior => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const ready = workerReady(f.runner);
|
||||
const execution = f.runner.runBacktest(blockingConfig).catch(error => error);
|
||||
const { pid } = await ready;
|
||||
f.repository.heartbeat = async () => {
|
||||
if (behavior === 'hung') return new Promise(() => {});
|
||||
throw new Error('Database unavailable');
|
||||
};
|
||||
expect(await execution).toBeInstanceOf(BacktestLeaseLostError);
|
||||
expectWorkerExited(pid);
|
||||
// Do not label a lost attempt failed/cancelled; the lease reaper owns its recovery.
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('running');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
}
|
||||
);
|
||||
|
||||
test('V2 cancellation publishes cancelled state, not a dispatch error or fabricated result', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const api = new BacktestServiceV2(f.services, (url, init) =>
|
||||
|
|
@ -699,14 +724,16 @@ describe('isolated native backtest workers', () => {
|
|||
);
|
||||
const ready = workerReady(f.runner);
|
||||
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
|
||||
const execution = f.runner.runQueued(run.id).catch(error => error);
|
||||
const { pid, runId } = await ready;
|
||||
expect(runId).toBe(run.id);
|
||||
await api.cancelRun(run.id);
|
||||
await cancelled;
|
||||
await execution;
|
||||
expectWorkerExited(pid);
|
||||
expect(notifications).toContainEqual({
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: expect.any(String) },
|
||||
data: { status: 'running', cancelRequested: true, timestamp: expect.any(String) },
|
||||
});
|
||||
expect(notifications.some(update => update.type === 'error')).toBe(false);
|
||||
expect((await api.getRun(run.id))?.status).toBe('cancelled');
|
||||
|
|
|
|||
494
test/postgres/durable-backtest.test.ts
Normal file
494
test/postgres/durable-backtest.test.ts
Normal file
|
|
@ -0,0 +1,494 @@
|
|||
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 { 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<void>)[] = [];
|
||||
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<boolean>, 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']) {
|
||||
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'],
|
||||
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 engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger,
|
||||
custom: {
|
||||
StorageService: {
|
||||
async getHistoricalBars() {
|
||||
return Array.from({ length: 70 }, (_, i) => {
|
||||
const close = 100 + Math.sin((i * Math.PI) / 6) * 8;
|
||||
return {
|
||||
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,
|
||||
},
|
||||
},
|
||||
{ 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,
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(!url || !redisUrl)('durable backtests on real PostgreSQL and Redis', () => {
|
||||
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'],
|
||||
});
|
||||
// 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']);
|
||||
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.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<unknown> | 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<void>(resolve => child.once('close', () => resolve()));
|
||||
cleanup.push(async () => {
|
||||
child.kill('SIGKILL');
|
||||
await closed;
|
||||
});
|
||||
await new Promise<void>((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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue