import { createHash, randomUUID } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { asValue } from 'awilix'; import { afterEach, describe, expect, spyOn, test } from 'bun:test'; import { Pool } from 'pg'; import { ServiceContainerBuilder } from '@stock-bot/di'; import { PostgreSQLClient } from '@stock-bot/postgres'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container'; import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery'; import { BacktestConfigSchema, type OrchestratorServices, } from '../../apps/stock/orchestrator/src/types'; import { logger, quote } from '../fixtures/execution'; import { CounterStrategy } from '../fixtures/strategy-recovery'; const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); const research = BacktestConfigSchema.parse({ mode: 'backtest', strategy: 'sma-crossover', symbols: ['RESEARCH.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() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Dedicated safety database 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, 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, 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), 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', '11-simulation-execution-ledger.sql', '12-historical-datasets.sql', '13-strategy-recovery.sql', '14-backtest-submission.sql', '16-strategy-catalog.sql', '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', '24-chronological-validation.sql', ]) { 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 container = await new ServiceContainerBuilder() .withOptions({ enableCache: false, enableQueue: false, enableMongoDB: false, enablePostgres: false, enableQuestDB: false, enableBrowser: false, enableProxy: false, }) .build(); const services: OrchestratorServices = { logger, postgres }; container.register({ serviceContainer: asValue(services) }); await registerOrchestratorServices(container, { initializeMode: false, nativeExecutionTimeoutMs: 5000, }); const runtime = services.custom!; const mode = runtime.ModeManager!; const runner = runtime.BacktestRunner!; const market = runtime.MarketDataService!; const storage = runtime.StorageService!; const execution = runtime.ExecutionService!; const strategies = runtime.StrategyManager!; const feed = { connected: false }; // Only the external transport is offline; real admission, ledger, checkpoints and replay run. const feedStart = spyOn(market, 'initialize').mockImplementation(async () => { feed.connected = true; }); const originalShutdown = market.shutdown.bind(market); const feedStop = spyOn(market, 'shutdown').mockImplementation(async () => { feed.connected = false; await originalShutdown(); }); const lifecycle = [ feedStart, feedStop, spyOn(execution, 'initialize'), spyOn(execution, 'shutdown'), spyOn(storage, 'initialize'), spyOn(storage, 'shutdown'), spyOn(strategies, 'restoreStrategies'), spyOn(strategies, 'shutdown'), ]; cleanup.push(async () => { try { await runner.shutdown(); await mode.shutdown(); await strategies.shutdown(); await container.dispose(); } finally { for (const method of lifecycle) method.mockRestore(); } }); await mode.initializeMode({ mode: 'paper', accountId: 'paper-fixture', startingCapital: 10000, commission: 0.001, slippage: 0, }); const strategy = new CounterStrategy(execution); await strategies.attachStrategy(strategy); await market.subscribeToSymbol('A'); market.ingest(quote('paper-one', 100, 100, Date.now())); await market.flush(); expect(strategy.count).toBe(1); expect((await execution.getAccount()).cash).toBe(9899.9); let failedRead = false; storage.getHistoricalBars = async () => { if (failedRead) throw new Error('Injected research history failure'); return Array.from({ length: 70 }, (_, i) => { const close = 100 + Math.sin((i * Math.PI) / 6) * 8; return { symbol: research.symbols[0]!, source: 'eod' as const, timestamp: new Date(Date.parse(research.startDate) + i * 86400000), open: close, high: close + 1, low: close - 1, close, volume: 1000000, }; }); }; const stateHash = async () => { const state: unknown[] = []; for (const [table, columns] of [ ['simulation_accounts', 'id,state'], ['simulation_orders', 'id,payload'], ['simulation_fills', 'id,payload'], ['simulation_events', 'id,fingerprint'], ['simulation_market_inputs', 'id,payload'], ['simulation_strategy_journal', 'sequence,payload'], ['simulation_strategy_checkpoints', 'strategy_id,payload'], ['simulation_strategy_intents', 'client_order_id,payload'], ]) { const rows = (await pool.query(`SELECT ${columns} FROM ${table}`)).rows; state.push([table, rows.map(row => canonicalJson(row)).sort()]); } return createHash('sha256').update(canonicalJson(state)).digest('hex'); }; return { services, pool, runner, mode, execution, market, strategies, strategy, feed, stateHash, lifecycleCounts: () => lifecycle.map(method => method.mock.calls.length), failHistory: (fail: boolean) => { failedRead = fail; }, }; } describe.skipIf(!url)('research isolation from a real paper ledger', () => { test('legacy_paper_combination_rejected_before_prepare preserves an active paper graph', async () => { const f = await fixture(); const engine = f.mode.getTradingEngine(); const before = await f.stateHash(); const lifecycle = f.lifecycleCounts(); await expect(f.mode.initializeMode(research)).rejects.toThrow('only permits paper'); await expect(f.mode.transitionMode('paper', 'backtest', research)).rejects.toThrow( 'only permits paper' ); await expect(f.execution.initialize(research, engine)).rejects.toThrow('only permits paper'); expect(f.mode.getTradingEngine()).toBe(engine); expect(f.mode.isPaperMode()).toBe(true); expect(f.feed.connected).toBe(true); expect(f.lifecycleCounts()).toEqual( lifecycle.map((count, index) => count + (index === 2 ? 1 : 0)) ); expect(await f.stateHash()).toBe(before); }); test('native_paper_isolation across successful, cancelled and failed durable jobs', async () => { const f = await fixture(); const engine = f.mode.getTradingEngine(); const paperConfig = f.mode.getConfig(); const before = await f.stateHash(); const lifecycle = f.lifecycleCounts(); const unchanged = async () => { expect(await f.stateHash()).toBe(before); expect(f.mode.getTradingEngine()).toBe(engine); expect(f.mode.getConfig()).toEqual(paperConfig); expect(f.lifecycleCounts()).toEqual(lifecycle); expect(f.market.listenerCount('marketDataBatch')).toBe(1); expect(f.strategies.getActiveStrategies()).toEqual(['counter']); expect(f.feed.connected).toBe(true); }; expect((await f.runner.runBacktest(research)).status).toBe('completed'); await unchanged(); for (let i = 0; i < 2; i++) { let stopped: Promise | undefined; f.runner.once('progress', () => { stopped = f.runner.stopBacktest(); }); const outcome = await f.runner.runBacktest(research).catch(error => error); await stopped; expect(stopped).toBeDefined(); expect(outcome).toBeInstanceOf(BacktestCancelledError); await unchanged(); f.failHistory(true); await expect(f.runner.runBacktest(research)).rejects.toThrow( 'Injected research history failure' ); f.failHistory(false); await unchanged(); } expect((await f.runner.runBacktest(research)).status).toBe('completed'); await unchanged(); expect( ( await f.pool.query( 'SELECT status, count(*)::int AS count FROM runs GROUP BY status ORDER BY status::text' ) ).rows ).toEqual([ { status: 'cancelled', count: 2 }, { status: 'completed', count: 2 }, { status: 'failed', count: 2 }, ]); // The existing feed still makes exactly one new durable paper decision after research. f.market.ingest(quote('paper-two', 101, 100, Date.now())); await f.market.flush(); expect(f.strategy.count).toBe(2); expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2); }, 15000); });