import { randomUUID } from 'node:crypto'; import { asValue } from 'awilix'; import { afterEach, describe, expect, test } from 'bun:test'; import { Hono } from 'hono'; 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'; import type { MongoDBClient } from '@stock-bot/services'; import type { BacktestRunResult } from '@stock-bot/types'; import { persistEodPrices } from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage'; import { runMultiStrategyBacktest } from '../../apps/stock/orchestrator/examples/multi-strategy-backtest'; import { createBacktestRoutes } from '../../apps/stock/orchestrator/src/api/rest/backtest'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { BacktestCancelledError, BacktestTimeoutError, } 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'; import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/backtest/backtest.handler'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; import { createBacktestRoutes as createV1Routes } from '../../apps/stock/web-api/src/routes/backtest.routes'; 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 { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service'; import { createWebSocketHandler, type RunUpdateMessage, } from '../../apps/stock/web-api/src/websocket/run-updates'; import { CounterStrategy } from '../fixtures/strategy-recovery'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('workflow-test'); const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0)) { await close(); } }); const config = BacktestConfigSchema.parse({ mode: 'backtest', name: 'Workflow fixture', strategy: 'sma-crossover', symbols: ['FIXTURE.TEST'], startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-03-15T00:00:00.000Z', initialCapital: 100000, dataFrequency: '1d', commission: 0, slippage: 0, config: { fastPeriod: 3, slowPeriod: 7 }, }); async function fixture( empty = false, engineOptions: ConstructorParameters[1] = {}, barCount = 70 ) { // 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, start_date timestamptz, end_date timestamptz, initial_capital numeric, 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), 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, dataset_hash text, 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_datasets (hash text PRIMARY KEY, payload jsonb, created_at timestamptz DEFAULT NOW()); 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);`); const { Pool } = db.adapters.createPg(); const pool = new Pool(); cleanup.push(() => pool.end()); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'fixture', user: 'fixture', password: 'fixture' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); const documents: Record[] = []; const mongodb = { async batchUpsert(_collection: string, rows: typeof documents) { documents.push(...rows); }, async find() { return documents; }, } as unknown as MongoDBClient; if (!empty) { await persistEodPrices( mongodb, { symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' }, Array.from({ length: barCount }, (_, index) => { const close = 100 + Math.sin((index * Math.PI) / 6) * 8 + index * 0.02; return { date: new Date(Date.parse(config.startDate) + index * 86400000) .toISOString() .slice(0, 10), open: close, high: close + 1, low: close - 1, close, volume: 1000000, }; }) ); } const storage = new StorageService({ logger }, mongodb, null, null); const engine = new RustBacktestAdapter({ logger, storage }, engineOptions); const repository = new PostgresBacktestRunRepository(postgres); 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)); return { postgres, mongodb, storage, engine, repository, runner, services, routes }; } async function composedRuntime( f: Awaited>, options: { strategyRegistry?: StrategyRegistry; useRustEngine?: boolean } = {} ) { const di = await new ServiceContainerBuilder() .withOptions({ enableCache: false, enableQueue: false, enableMongoDB: false, enablePostgres: false, enableQuestDB: false, enableBrowser: false, enableProxy: false, }) .build(); const services: OrchestratorServices = { logger, postgres: f.postgres, mongodb: f.mongodb, }; di.register({ serviceContainer: asValue(services) }); await registerOrchestratorServices(di, { initializeMode: false, ...options, }); expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner); return services; } describe('one backtest execution workflow', () => { for (const backend of ['native', 'typescript'] as const) { test(`${backend} composed runtime uses injected peers when application service lookups are unavailable`, async () => { const f = await fixture(); const services = await composedRuntime(f, { useRustEngine: backend === 'native' }); const { BacktestRunner: runner, ModeManager: mode, MarketDataService: market, StrategyManager: manager, } = services.custom!; cleanup.unshift(async () => { await runner!.shutdown(); await mode!.shutdown(); await manager!.shutdown(); }); for (const key of Object.keys(services.custom!)) { Object.defineProperty(services.custom, key, { get() { throw new Error(`Unexpected runtime service lookup: ${key}`); }, }); } const history = await market!.loadHistoricalData( config.symbols, new Date(config.startDate), new Date(config.endDate), config.dataFrequency ); expect(history).toHaveLength(70); const result = await runner!.runBacktest(config); expect(result.engine).toBe(backend); expect(result.trades.length).toBeGreaterThan(0); expect(market!.listenerCount('marketDataBatch')).toBe(1); await mode!.shutdown(); await manager!.shutdown(); expect(market!.listenerCount('marketDataBatch')).toBe(0); }); } for (const backend of ['native', 'typescript'] as const) { test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => { const f = await fixture(); const services = backend === 'typescript' ? await composedRuntime(f) : f.services; const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); if (backend === 'typescript') await (services as OrchestratorServices).custom?.ModeManager?.shutdown(); }); const api = new BacktestServiceV2(services); const parameters = { fastPeriod: 3, slowPeriod: 7, dataFrequency: '1d', commission: 0, slippage: 0, dataPolicy: { adjustment: 'raw', timestamp: 'utc-session-date' }, }; const definition = await api.createBacktest( { ...config, name: 'Mixed parameters', config: parameters }, { autoStart: false } ); const run = await api.createRun({ backtestId: definition.id }); const before = ( await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id]) ).rows[0]!.request_snapshot; const result = await runner.runQueued(run.id); const saved = (await api.getRunResults(result.runId))!; expect(saved.engine).toBe(backend); expect(saved.trades.length).toBeGreaterThan(0); expect(saved.config.parameters).toEqual(parameters); expect(saved.config.dataFrequency).toBe('1d'); expect(saved.config.commission).toBe(0); const request = { ...before, runId: undefined, backtestId: undefined, datasetHash: saved.config.dataset!.hash, }; const replayed = await runner.runBacktest(request); expect(replayed.config.parameters).toEqual(parameters); expect(replayed.config.dataset).toEqual(saved.config.dataset); expect(replayed.trades).toEqual(saved.trades); expect(replayed.metrics).toEqual(saved.metrics); expect( (await f.postgres.query('SELECT request_snapshot FROM runs WHERE id = $1', [run.id])) .rows[0]!.request_snapshot ).toEqual(before); if (backend === 'typescript') { const strategies = ( services as OrchestratorServices ).custom!.StrategyManager!.getAllStrategies(); expect(strategies[0]!.getConfig().parameters).not.toHaveProperty('dataFrequency'); expect(strategies[0]!.getCheckpointVersion()).toBe('sma-crossover-fixed/v2'); } }); } test('custom strategy extension fields survive the full API and TypeScript workflow', async () => { const f = await fixture(); const seen: Record[] = []; const registry = new StrategyRegistry().register( ['custom-fixture'], (definition, dependencies) => { seen.push(structuredClone(definition.parameters)); return new CounterStrategy(dependencies.execution, definition); } ); const services = await composedRuntime(f, { strategyRegistry: registry }); const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); await services.custom?.ModeManager?.shutdown(); }); const parameters = { vendorFeature: { window: 17, version: 'v1' }, dataFrequency: '1d', commission: 0, slippage: 0, }; const api = new BacktestServiceV2(services); const definition = await api.createBacktest( { ...config, name: 'Custom extension', strategy: 'custom-fixture', config: parameters }, { autoStart: false } ); const run = await api.createRun({ backtestId: definition.id }); await runner.runQueued(run.id); expect((await api.getRunResults(run.id))?.config.parameters).toEqual(parameters); expect(seen[0]).toMatchObject({ ...parameters, initialCapital: config.initialCapital }); expect(services.custom!.StrategyManager!.getAllStrategies()[0]!.getCheckpointVersion()).toBe( 'counter/v1' ); }); test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => { const f = await fixture(); const api = createBacktestV2Routes(f.services); for (const request of [ { ...config, symbols: ['FIXTURE'] }, { ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } }, { ...config, config: { datasetHash: 'invalid' } }, { ...config, config: { commission: -0.01 } }, { ...config, config: { slippage: 0.11 } }, { ...config, config: { commission: '0.001' } }, { ...config, initialCapital: 0 }, { ...config, strategy: '' }, ]) { const response = await api.request('/api/v2/backtests', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request), }); expect(response.status).toBe(400); } expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0); expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0); }); test('frozen inputs replay without reading mutable provider history and are recorded in results', async () => { const f = await fixture(); const first = await f.runner.runBacktest(config); expect(first.config.dataset?.barCount).toBe(70); expect(first.config.dataset?.hash).toMatch(/^[a-f0-9]{64}$/); const saved = await f.postgres.query('SELECT dataset_hash FROM runs WHERE id = $1', [ first.runId, ]); expect(saved.rows[0]?.dataset_hash).toBe(first.config.dataset!.hash); f.storage.getHistoricalBars = async () => { throw new Error('Provider unavailable or revised'); }; const replay = await f.runner.runBacktest({ ...config, datasetHash: first.config.dataset!.hash, }); expect(replay.config.dataset).toEqual(first.config.dataset); expect(replay.trades).toEqual(first.trades); expect(replay.metrics).toEqual(first.metrics); expect(replay.equity).toEqual(first.equity); expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1); await expect(f.runner.runBacktest({ ...config, datasetHash: 'f'.repeat(64) })).rejects.toThrow( 'not found' ); }); test('V1 reports shared request-validation failures as bad input without creating definitions or runs', async () => { const f = await fixture(); const response = await createV1Routes(f.services).request('/api/backtests', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...config, config: { commission: -0.01 } }), }); expect(response.status).toBe(400); expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0); expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0); }); test('REST and decorated jobs execute real data and commit the same canonical result', async () => { const f = await fixture(); const response = await f.routes.request('/api/backtest/run', { method: 'POST', body: JSON.stringify(config), headers: { 'Content-Type': 'application/json' }, }); expect(response.status).toBe(201); const rest: BacktestRunResult = await response.json(); const handler = new BacktestHandler(f.services); const job = (await handler.execute('run-backtest', config, { type: 'queue', metadata: {}, })) as { results: BacktestRunResult }; expect(rest.trades.length).toBeGreaterThan(0); expect(job.results.metrics).toEqual(rest.metrics); expect(job.results.trades).toEqual(rest.trades); expect(job.results.trades.every(trade => trade.kind === 'fill')).toBe(true); for (const result of [rest, job.results]) { const saved = await f.postgres.query( 'SELECT r.status, br.* FROM runs r JOIN backtest_results br ON br.run_id = r.id WHERE r.id = $1', [result.runId] ); expect(saved.rows[0]?.status).toBe('completed'); expect(saved.rows[0]?.metrics).toEqual(result.metrics); expect(saved.rows[0]?.configuration).toEqual(result.config); expect(saved.rows[0]?.engine).toBe('native'); } const duplicate = await f.routes.request('/api/backtest/run', { method: 'POST', body: JSON.stringify({ ...config, runId: rest.runId }), headers: { 'Content-Type': 'application/json' }, }); expect(duplicate.status).toBe(409); expect( (await f.postgres.query('SELECT * FROM backtest_results WHERE run_id = $1', [rest.runId])) .rows ).toHaveLength(1); }); test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => { const f = await fixture(); const services = await composedRuntime(f); try { const result = await services.custom!.BacktestRunner!.runBacktest(config); expect(result.engine).toBe('typescript'); expect(result.trades.length).toBeGreaterThan(0); expect(result.status).toBe('completed'); services.custom!.StorageService!.getHistoricalBars = async () => { throw new Error('Provider unavailable'); }; const repeated = await services.custom!.BacktestRunner!.runBacktest({ ...config, datasetHash: result.config.dataset!.hash, }); expect(repeated.config.dataset).toEqual(result.config.dataset); expect(repeated.trades).toEqual(result.trades); expect(repeated.metrics).toEqual(result.metrics); expect(result.ohlcData['FIXTURE.TEST']).toHaveLength(70); expect(result.trades.every(trade => trade.kind === 'closed')).toBe(true); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed'); } finally { await services.custom?.ModeManager?.shutdown(); } }); test('the maintained multi-strategy example runs through the composed runner and persists real results', async () => { const f = await fixture(); const services = await composedRuntime(f); const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); await services.custom?.ModeManager?.shutdown(); }); const result = await runMultiStrategyBacktest(runner, config); expect(result.status).toBe('completed'); expect(result.engine).toBe('typescript'); expect(result.trades.length).toBeGreaterThan(0); expect(result.config.config).toBeUndefined(); expect(config.config).toEqual({ fastPeriod: 3, slowPeriod: 7 }); expect(result.config.strategies?.map(strategy => strategy.name)).toEqual([ 'sma-crossover', 'mean-reversion', ]); const strategies = services.custom!.StrategyManager!.getAllStrategies(); expect(strategies.map(strategy => strategy.getCheckpointVersion())).toEqual([ 'sma-crossover-fixed/v2', 'mean-reversion/v2', ]); expect(result.config.dataset?.barCount).toBe(70); expect((await f.postgres.query('SELECT status FROM runs')).rows).toEqual([ { status: 'completed' }, ]); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1); }); test('undefined one-timestamp statistics survive normalization, persistence and the public result reader as null', async () => { const f = await fixture(false, {}, 1); const services = await composedRuntime(f); const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); await services.custom?.ModeManager?.shutdown(); }); const result = await runner.runBacktest(config); expect(result.metrics.sharpeRatio).toBeNull(); expect(result.metrics.profitFactor).toBeNull(); expect(result.metrics.cagr).toBeNull(); expect(result.metrics.annualizedReturn).toBeNull(); expect(result.analytics.riskMetrics?.volatility).toBeNull(); const saved = await new BacktestServiceV2(services).getRunResults(result.runId); expect(saved?.metrics).toEqual(result.metrics); expect(saved?.analytics).toEqual(result.analytics); expect(JSON.stringify(saved)).not.toMatch(/Infinity|NaN/); }); test('TypeScript cancellation is persisted without a partial success or completion event', async () => { const f = await fixture(); const services = await composedRuntime(f); const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); await services.custom?.ModeManager?.shutdown(); }); let stopped: Promise | undefined; let controlError: unknown; let completed = 0; runner.on('complete', () => { completed++; }); const manager = services.custom!.StrategyManager!; const deliver = manager.onMarketData.bind(manager); manager.onMarketData = async data => { await deliver(data); stopped = runner.stopBacktest(runner.getStatus().runId).catch(error => { controlError = error; }); }; const outcome = await runner.runBacktest(config).catch(error => error); expect(stopped).toBeDefined(); await stopped; expect(controlError).toBeUndefined(); expect(outcome).toBeInstanceOf(BacktestCancelledError); expect(completed).toBe(0); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); expect(services.custom?.BacktestEngine?.getStatus().isRunning).toBe(false); }); test('TypeScript ledger failures are persisted as failures, never fabricated equity or results', async () => { const f = await fixture(); const services = await composedRuntime(f); const runner = services.custom!.BacktestRunner!; cleanup.unshift(async () => { await runner.shutdown(); await services.custom?.ModeManager?.shutdown(); }); services.custom!.ExecutionService!.getAccount = async () => { throw new Error('Ledger unavailable'); }; await expect(runner.runBacktest(config)).rejects.toThrow('Ledger unavailable'); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); }); test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => { const f = await fixture(); 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 }); 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, 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(); const api = new BacktestService(f.services); const created = await api.createBacktest({ ...config, config: { ...config.config, commission: 0, slippage: 0 }, }); 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); }); test('empty data fails both data paths instead of producing synthetic prices or success', async () => { const f = await fixture(true); await expect( new DataManager(f.storage).loadHistoricalData( ['FIXTURE.TEST'], new Date(config.startDate), new Date(config.endDate), '1d' ) ).rejects.toThrow('No historical data'); await expect(f.runner.runBacktest(config)).rejects.toThrow('No historical data'); const runs = await f.postgres.query('SELECT status, error FROM runs'); expect(runs.rows[0]?.status).toBe('failed'); expect(runs.rows[0]?.error).toContain('No historical data'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toEqual([]); }); test('a result write failure never publishes completion and releases the runner', async () => { const f = await fixture(); let completions = 0; f.runner.on('complete', () => { completions++; }); const complete = f.repository.complete.bind(f.repository); f.repository.complete = async () => { throw new Error('Result store unavailable'); }; await expect(f.runner.runBacktest(config)).rejects.toThrow('Result store unavailable'); expect(completions).toBe(0); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed'); f.repository.complete = complete; expect((await f.runner.runBacktest(config)).status).toBe('completed'); }); test('concurrent requests cannot prepare or claim a second run', async () => { const f = await fixture(); const first = f.runner.runBacktest(config); await expect(f.runner.runBacktest(config)).rejects.toThrow('already running'); await first; expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(1); }); test('the real transaction manager rolls back when terminal result insertion fails', async () => { const f = await fixture(); const result = await f.runner.runBacktest(config); const statements: string[] = []; let released = false; const postgres = new PostgreSQLClient( { host: 'unused', database: 'fixture', user: 'fixture', password: 'fixture', port: 5432 }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ async connect() { return { async query(sql: string) { statements.push(sql.trim()); if (sql.includes('INSERT INTO backtest_results')) { throw new Error('Insert failed'); } return { rows: [{ id: result.runId, dataset_hash: result.config.dataset?.hash }], rowCount: 1, }; }, release() { released = true; }, }; }, }), }); 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'); expect(released).toBe(true); }); test('observer errors cannot change committed success into failure', async () => { const f = await fixture(); f.runner.on('complete', () => { throw new Error('Disconnected observer'); }); const result = await f.runner.runBacktest(config); expect(result.status).toBe('completed'); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed'); }); test('unsupported controls are rejected without changing persisted state', async () => { const f = await fixture(); let controlError: unknown; let control: Promise | undefined; f.runner.on('progress', (data: { runId: string }) => { control = f.runner.pauseBacktest(data.runId).catch(error => { controlError = error; }); }); const result = await f.runner.runBacktest(config); await control; expect(String(controlError)).toContain('do not support pause'); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed'); const api = new BacktestServiceV2(f.services, async (_url, init) => { expect(JSON.parse(String(init?.body)).runId).toBe(result.runId); return new Response('Unsupported', { status: 501 }); }); await expect(api.cancelRun(result.runId)).rejects.toThrow('No cancellable run'); expect((await api.getRun(result.runId))?.status).toBe('completed'); }); test('invalid input and controls cannot claim or falsify a run', async () => { const f = await fixture(); await expect(f.runner.runBacktest({ ...config, symbols: [] })).rejects.toThrow(); await expect(f.runner.runBacktest({ ...config, endDate: config.startDate })).rejects.toThrow(); await expect(f.runner.stopBacktest(randomUUID())).rejects.toThrow('No matching active'); expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0); }); test('the shared result contract fixes percentage units and preserves undefined ratios', async () => { const f = await fixture(); const raw = await f.engine.runBacktest(config); const result = normalizeBacktestResult( { ...raw, metrics: { ...raw.metrics, totalReturn: 25, winRate: 80, maxDrawdown: 0.1, profitFactor: null, }, }, 'native', config, { runId: randomUUID(), backtestId: randomUUID() }, 10, false ); expect(result.metrics.totalReturn).toBe(0.25); expect(result.metrics.winRate).toBe(0.8); expect(result.metrics.maxDrawdown).toBe(0.1); expect(result.metrics.profitFactor).toBeNull(); }); test('pre-contract history is readable with explicit legacy provenance and normalized units', async () => { const f = await fixture(); const result = await f.runner.runBacktest(config); await f.postgres.query( 'UPDATE backtest_results SET configuration = NULL, engine = NULL, metrics = $2 WHERE run_id = $1', [result.runId, JSON.stringify({ ...result.metrics, totalReturn: 25, winRate: 80 })] ); const restored = await new BacktestServiceV2(f.services).getRunResults(result.runId); expect(restored?.legacy).toBe(true); expect(restored?.engine).toBe('legacy'); expect(restored?.metrics.totalReturn).toBe(0.25); expect(restored?.metrics.winRate).toBe(0.8); }); test('SSE completion detaches listeners so later runs do not target a closed stream', async () => { const f = await fixture(); for (let attempt = 0; attempt < 2; attempt++) { const response = await f.routes.request('/api/backtest/stream'); const body = response.text(); await f.runner.runBacktest(config); expect(await body).toContain('"event":"complete"'); expect(f.runner.listenerCount('complete')).toBe(0); expect(f.runner.listenerCount('error')).toBe(0); expect(f.runner.listenerCount('progress')).toBe(0); } }); }); const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url); const blockingConfig = { ...config, name: 'fixture:block' }; function workerReady(runner: BacktestRunner) { return new Promise<{ pid: number; runId: string }>((resolve, reject) => { const onError = (error: Error) => { runner.off('progress', onProgress); reject(error); }; const onProgress = (progress: { message: string; runId: string }) => { if (!progress.message.startsWith('Fixture worker ready:')) return; runner.off('progress', onProgress); runner.off('error', onError); resolve({ pid: Number(progress.message.split(':')[1]), runId: progress.runId }); }; runner.once('error', onError); runner.on('progress', onProgress); }); } function expectWorkerExited(pid: number) { expect(pid).toBeGreaterThan(0); expect(() => process.kill(pid, 0)).toThrow(); } describe('isolated native backtest workers', () => { test('HTTP, status, and SSE stay responsive while a worker blocks; stop reaps it before acknowledgement', async () => { const f = await fixture(false, { workerUrl }); f.routes.get('/health', c => c.json({ status: 'ok' })); const stream = await f.routes.request('/api/backtest/stream'); const reader = stream.body!.getReader(); const ready = workerReady(f.runner); const request = f.routes.request('/api/backtest/run', { method: 'POST', body: JSON.stringify(blockingConfig), }); const { pid, runId } = await ready; expect((await f.routes.request('/health')).status).toBe(200); const status = await (await f.routes.request('/api/backtest/progress')).json(); expect(status).toMatchObject({ status: 'running', isRunning: true, runId }); const chunk = await reader.read(); expect(new TextDecoder().decode(chunk.value)).toContain('Fixture worker ready'); expect( ( await f.routes.request('/api/backtest/run', { method: 'POST', body: JSON.stringify(config), }) ).status ).toBe(409); await expect(f.runner.stopBacktest(randomUUID())).rejects.toThrow('No matching active'); expect(f.runner.getStatus().isRunning).toBe(true); const stop = await f.routes.request('/api/backtest/stop', { method: 'POST', body: JSON.stringify({ runId }), }); expect(stop.status).toBe(200); expectWorkerExited(pid); expect((await request).status).toBe(409); expect( (await f.postgres.query('SELECT status FROM runs WHERE id = $1', [runId])).rows[0]?.status ).toBe('cancelled'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); expect(f.runner.getStatus().isRunning).toBe(false); const terminal = await reader.read(); expect(new TextDecoder().decode(terminal.value)).toContain('"event":"cancelled"'); expect((await reader.read()).done).toBe(true); for (const event of ['complete', 'error', 'progress', 'cancelled']) { expect(f.runner.listenerCount(event)).toBe(0); } expect((await f.runner.runBacktest(config)).status).toBe('completed'); }); test('the execution deadline kills a stuck worker, records failure, and releases capacity', async () => { const f = await fixture(false, { workerUrl, timeoutMs: 750 }); const ready = workerReady(f.runner); const started = performance.now(); const failed = f.runner.runBacktest(blockingConfig).catch(error => error); const { pid } = await ready; expect(await failed).toBeInstanceOf(BacktestTimeoutError); expect(performance.now() - started).toBeLessThan(3000); expectWorkerExited(pid); expect((await f.postgres.query('SELECT status, error FROM runs')).rows[0]).toMatchObject({ status: 'failed', error: expect.stringContaining('execution deadline'), }); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); expect((await f.runner.runBacktest(config)).status).toBe('completed'); }); test.each([ ['crash', 'exited without a result'], ['no-result', 'exited without a result'], ['malformed', 'Invalid native backtest worker response'], ['invalid-result', 'Required'], ['reported-error', 'Fixture native failure'], ])('%s does not crash the parent or publish a result', async (behavior, message) => { const f = await fixture(false, { workerUrl }); let completions = 0; f.runner.on('complete', () => { completions++; }); const ready = workerReady(f.runner); const failed = f.runner .runBacktest({ ...config, name: `fixture:${behavior}` }) .catch(error => error); const { pid } = await ready; expect(String(await failed)).toContain(message); expectWorkerExited(pid); expect(completions).toBe(0); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); expect((await f.runner.runBacktest(config)).status).toBe('completed'); }); test('shutdown kills the worker and persists cancellation before rejecting new runs', async () => { const f = await fixture(false, { workerUrl }); const ready = workerReady(f.runner); const cancelled = f.runner.runBacktest(blockingConfig).catch(error => error); const { pid } = await ready; await f.runner.shutdown(); expect(await cancelled).toBeInstanceOf(BacktestCancelledError); expectWorkerExited(pid); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); await expect(f.runner.runBacktest(config)).rejects.toThrow('shutting down'); }); test('cancellation during a slow historical read cannot start a late worker', async () => { const f = await fixture(); const read = f.storage.getHistoricalBars.bind(f.storage); let release!: () => void; let reading!: () => void; const gate = new Promise(resolve => { release = resolve; }); const entered = new Promise(resolve => { reading = resolve; }); f.storage.getHistoricalBars = async (...args) => { reading(); await gate; return read(...args); }; let progress = 0; f.runner.on('progress', () => { progress++; }); const cancelled = f.runner.runBacktest(config).catch(error => error); await entered; await f.runner.stopBacktest(f.runner.getStatus().runId); expect(await cancelled).toBeInstanceOf(BacktestCancelledError); expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(0); release(); await gate; f.storage.getHistoricalBars = read; expect((await f.runner.runBacktest(config)).status).toBe('completed'); expect(progress).toBe(1); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1); }); test('a worker result is not accepted before the worker has exited', async () => { const f = await fixture(false, { workerUrl }); const ready = workerReady(f.runner); const cancelled = f.runner .runBacktest({ ...config, name: 'fixture:result-then-block' }) .catch(error => error); const { pid, runId } = await ready; await f.runner.stopBacktest(runId); expect(await cancelled).toBeInstanceOf(BacktestCancelledError); expectWorkerExited(pid); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled'); expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); }); test('a failed cancellation write is not acknowledged or published as successful', async () => { const f = await fixture(false, { workerUrl }); const ready = workerReady(f.runner); let cancellations = 0; f.runner.on('cancelled', () => { cancellations++; }); f.repository.cancel = async () => { throw new Error('Cancellation store unavailable'); }; const failed = f.runner.runBacktest(blockingConfig).catch(error => error); const { pid, runId } = await ready; await expect(f.runner.stopBacktest(runId)).rejects.toThrow('Cancellation store unavailable'); expect(String(await failed)).toContain('Cancellation store unavailable'); expectWorkerExited(pid); expect(cancellations).toBe(0); 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('late cancellation cannot relabel a completed execution while its result commits', async () => { const f = await fixture(); const complete = f.repository.complete.bind(f.repository); let entered!: () => void; let release!: () => void; const committing = new Promise(resolve => { entered = resolve; }); const gate = new Promise(resolve => { release = resolve; }); f.repository.complete = async (result, attemptId) => { entered(); await gate; await complete(result, attemptId); }; const running = f.runner.runBacktest(config); await committing; await expect(f.runner.stopBacktest()).rejects.toThrow('already finished'); const stopped = f.runner.shutdown(); release(); expect((await running).status).toBe('completed'); await stopped; expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed'); }); test('shutdown while a run claim is pending never starts native execution', async () => { const f = await fixture(); const start = f.repository.start.bind(f.repository); let entered!: () => void; let release!: () => void; const claiming = new Promise(resolve => { entered = resolve; }); const gate = new Promise(resolve => { release = resolve; }); f.repository.start = async input => { const identity = await start(input); entered(); await gate; return identity; }; let progress = 0; f.runner.on('progress', () => { progress++; }); const cancelled = f.runner.runBacktest(config).catch(error => error); await claiming; const stopped = f.runner.shutdown(); release(); await stopped; expect(await cancelled).toBeInstanceOf(BacktestCancelledError); expect(progress).toBe(0); expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled'); }); test('the built worker executes the real engine without TypeScript source imports', async () => { const f = await fixture(false, { workerUrl: new URL('../../apps/stock/orchestrator/dist/native-worker.js', import.meta.url), }); const result = await f.runner.runBacktest(config); expect(result.status).toBe('completed'); expect(result.trades.length).toBeGreaterThan(0); 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) => f.routes.request(new URL(url).pathname, init) ); const notifications: Partial[] = []; let notify!: () => void; const cancelled = new Promise(resolve => { notify = resolve; }); const handler = createWebSocketHandler(f.services); handler.broadcastRunUpdate = (_runId, update) => { notifications.push(update); if (update.type === 'run_update') { notify(); } }; Object.defineProperty(api, 'wsHandler', { value: handler }); const definition = await api.createBacktest(blockingConfig, { autoStart: false }); 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: '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'); expect(await api.getRunResults(run.id)).toBeNull(); }); });