import { randomUUID } from 'node:crypto'; import { EventEmitter } from 'node:events'; import { readFileSync } from 'node:fs'; import type { ServerWebSocket } from 'bun'; import { Pool } from 'pg'; import type { Browser, Page } from 'playwright'; import { createHttpSecurity } from '@stock-bot/di'; import { HandlerRegistry } from '@stock-bot/handler-registry'; import type { IServiceContainer } from '@stock-bot/handlers'; 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 type { NativeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/native-result'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { loadDataset, type DatasetResolver, } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types'; import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes'; import { createWebSocketRoute, handleWebSocketConnection, } from '../../apps/stock/web-api/src/routes/websocket.routes'; import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher'; import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service'; import { getWebSocketHandler, type RunSocketData, } from '../../apps/stock/web-api/src/websocket/run-updates'; import { seedBuiltinCatalog } from '../../scripts/seed-builtin-strategies'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('browser-fixture'); export function gate() { let resolve!: () => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve, async wait(label: string) { let timer: ReturnType | undefined; try { await Promise.race([ promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Timed out waiting for ${label}`)), 10000); }), ]); } finally { clearTimeout(timer); } }, }; } export async function until( check: () => Promise | boolean, label: string, timeout = 10000 ) { const deadline = Date.now() + timeout; while (Date.now() < deadline) { if (await check()) { return; } await Bun.sleep(25); } throw new Error(`Timed out waiting for ${label}`); } export async function visible(page: Page, text: string | RegExp) { try { await page .getByText(text, { exact: typeof text === 'string' }) .first() .waitFor({ state: 'visible' }); } catch (error) { throw new Error(`Expected visible ${text}; page: ${await page.locator('body').innerText()}`, { cause: error, }); } } const storage: Pick = { async getHistoricalBars(symbol, startDate, endDate) { const length = Math.min(70, Math.ceil((endDate.getTime() - startDate.getTime()) / 86400000)); return Array.from({ length }, (_, index) => { const close = 100 + Math.sin((index * Math.PI) / 6) * 8; return { symbol, source: 'eod' as const, timestamp: new Date(startDate.getTime() + index * 86400000), open: close, high: close + 1, low: close - 1, close, volume: 1000000, }; }); }, }; /** Retain a real hash-validated v1 fixture through the same preparation function as a run. */ export async function retainDataset(pool: Pool, overrides: Partial = {}) { const dataset = await loadDataset(storage, { mode: 'backtest', strategy: 'moving-average', symbols: ['AAPL.US'], startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-03-15T00:00:00.000Z', dataFrequency: '1d', initialCapital: 100000, speed: 'max', ...overrides, }); await pool.query('INSERT INTO backtest_datasets(hash,payload) VALUES ($1,$2)', [ dataset.manifest.hash, JSON.stringify(dataset), ]); return dataset; } /** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */ class FixtureEngine extends EventEmitter { completion = gate(); cancellation = gate(); stopped = gate(); mode: 'trades' | 'empty' | 'fail' = 'trades'; private cancelled = false; async runBacktest( config: BacktestConfig, resolver?: DatasetResolver ): Promise { if (!resolver) { throw new Error('Fixture must exercise durable dataset resolution'); } const dataset = await resolver(() => loadDataset(storage, config)); this.cancelled = false; this.emit('progress', { progress: 25, currentDate: config.startDate }); await this.completion.promise; if (this.cancelled) { throw new BacktestCancelledError(); } if (this.mode === 'fail') { throw new Error('Injected fixture worker failure'); } return { backtestId: config.backtestId!, status: 'completed', completedAt: '2024-03-15T00:00:00.000Z', config: { name: config.name!, symbols: config.symbols, startDate: config.startDate, endDate: config.endDate, initialCapital: config.initialCapital, }, metrics: { totalReturn: 0, sharpeRatio: 0, maxDrawdown: 0, winRate: 0, totalTrades: 0, profitFactor: null, avgWin: 0, avgLoss: 0, }, equity: [{ date: config.startDate, value: config.initialCapital }], trades: this.mode === 'empty' ? [] : [ { id: 'fixture-fill', symbol: config.symbols[0]!, timestamp: config.startDate, side: 'buy', price: 100, quantity: 3, commission: 0, positionAfter: 3, }, ], positions: [], analytics: { exposureTime: 0 }, executionTime: 0, ohlcData: Object.fromEntries( config.symbols.map(symbol => [symbol, dataset.bars.filter(bar => bar.symbol === symbol)]) ), }; } async stopBacktest() { this.cancelled = true; this.stopped.resolve(); await this.cancellation.promise; this.completion.resolve(); } async pauseBacktest() { throw new Error('Unsupported fixture control'); } async resumeBacktest() { throw new Error('Unsupported fixture control'); } setSpeedMultiplier() {} getStatus() { return { isRunning: true, isPaused: false, progress: 25, currentTime: 0 }; } async shutdown() { this.cancellation.resolve(); this.completion.resolve(); } } export async function fixture(browser: Browser, native = false) { const database = process.env.PIPELINE_TEST_DATABASE_URL; const redisUrl = process.env.BACKTEST_TEST_REDIS_URL; if ( !database || !new URL(database).pathname.startsWith('/stock_bot_safety') || !redisUrl || new URL(redisUrl).pathname !== '/15' ) { throw new Error('Disposable stock_bot_safety PostgreSQL and dedicated Redis DB15 are required'); } if (process.env.STOCK_BOT_E2E_BUILT !== '1') { throw new Error('Run bun run test:e2e (builds same-origin UI first)'); } const cleanup: (() => Promise)[] = []; const close = async () => { const errors = []; for (const dispose of cleanup.splice(0).reverse()) { let timer: ReturnType | undefined; try { await Promise.race([ dispose(), new Promise((_, reject) => { timer = setTimeout( () => reject( new Error( `Fixture cleanup deadline exceeded: ${dispose.toString().slice(0, 150)}` ) ), 5000 ); }), ]); } catch (error) { errors.push(error); } finally { clearTimeout(timer); } } if (errors.length) { throw new AggregateError(errors, 'Browser fixture cleanup failed'); } }; try { const schema = `stock_bot_safety_browser_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: database, connectionTimeoutMillis: 5000 }); cleanup.push(() => admin.end()); await admin.query(`CREATE SCHEMA ${schema}`); cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`)); const pool = new Pool({ connectionString: database, options: `-c search_path=${schema}`, connectionTimeoutMillis: 5000, }); cleanup.push(() => pool.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 name of [ '09-backtest-run-contract.sql', '10-durable-backtest-dispatch.sql', '12-historical-datasets.sql', '14-backtest-submission.sql', '16-strategy-catalog.sql', '17-research-retention.sql', '18-backtest-strategy-versions.sql', '19-canonical-research.sql', '20-research-workspace.sql', '21-run-reproduction.sql', '22-experiments.sql', '23-experiment-retries.sql', ]) { await pool.query( readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8') ); } const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); const redisEndpoint = new URL(redisUrl); const redis = { host: redisEndpoint.hostname, port: Number(redisEndpoint.port || 6379), db: 15, ...(redisEndpoint.password ? { password: decodeURIComponent(redisEndpoint.password) } : {}), }; const queueName = `stock-bot-safety-browser-${randomUUID()}`; const queue = new Queue(queueName, redis, {}, { workers: 0 }, logger); cleanup.push(async () => { try { await queue.getBullQueue().obliterate({ force: true }); } finally { await queue.close(); } }); const ready = gate(); const readiness = queue.getBullQueue().waitUntilReady(); // Propagate a real connection failure, or a bounded diagnostic for an unavailable fixture. try { await Promise.race([readiness, ready.wait('dedicated browser Redis readiness')]); } finally { ready.resolve(); } const dispatcher = new BacktestDispatcher(postgres, queue, logger, { intervalMs: 20, republishMs: 100, maxAttempts: 3, }); const controlled = new FixtureEngine(); const historicalDataReads: string[] = []; const runStorage: Pick = { async getHistoricalBars(...args) { historicalDataReads.push(args[0]); return storage.getHistoricalBars(...args); }, }; const engine = native ? new RustBacktestAdapter({ logger, storage: runStorage }, { timeoutMs: 15000 }) : controlled; const canonicalFailures: string[] = []; if (engine instanceof RustBacktestAdapter) { const executeCanonical = engine.runCanonical.bind(engine); engine.runCanonical = async (...args) => { const failure = canonicalFailures.shift(); if (failure) { throw new Error(failure); } return executeCanonical(...args); }; } const runner = new BacktestRunner({ engine, engineName: 'native', repository: new PostgresBacktestRunRepository(postgres, 2000), logger, heartbeatMs: 50, }); const registry = new HandlerRegistry(); registry.registerConfiguration({ name: 'orchestrator', operations: { 'run-backtest': payload => runner.runQueued((payload as { runId: string }).runId), }, }); const worker = new Queue( queueName, redis, {}, { workers: 1, concurrency: 1, handlerRegistry: registry }, logger ); cleanup.push(async () => { controlled.cancellation.resolve(); controlled.completion.resolve(); try { await runner.shutdown(); } finally { await worker.close(); } }); cleanup.push(() => dispatcher.shutdown()); const container = { postgres, logger } as IServiceContainer; const token = randomUUID() + randomUUID(); const security = createHttpSecurity({ adminToken: token, serviceToken: randomUUID() + randomUUID(), browserSessions: true, environment: 'test', origins: [], }); const routes = createRoutes(container, security); const wsRoute = createWebSocketRoute(container, security); const sockets = new Set>(); const unexpectedNetwork: string[] = []; let responseDelay: | { path: string; captured: ReturnType; release: ReturnType; delivered: ReturnType; } | undefined; const delayResponse = (path: string) => { responseDelay = { path, captured: gate(), release: gate(), delivered: gate() }; return responseDelay; }; const server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request, server) { const pathname = new URL(request.url).pathname; if (pathname === '/ws' && request.headers.get('upgrade') === 'websocket') { return wsRoute(request, server); } if (pathname.startsWith('/api/')) { if ( (!pathname.startsWith('/api/v2/backtests') && !pathname.startsWith('/api/v2/runs') && !pathname.startsWith('/api/v2/datasets') && !pathname.startsWith('/api/v2/strategies') && !pathname.startsWith('/api/v2/strategy-versions') && !pathname.startsWith('/api/v2/research-projects') && !pathname.startsWith('/api/v2/experiments') && !pathname.startsWith('/api/v2/hypotheses/') && !pathname.startsWith('/api/v2/analysis-artifacts/') && pathname !== '/api/auth/session') || /\/(pause|resume|speed)$/.test(pathname) ) { unexpectedNetwork.push(pathname); return new Response('Endpoint outside browser fixture scope', { status: 403 }); } const response = await routes.fetch(request); const delay = responseDelay; if (delay?.path === pathname) { responseDelay = undefined; // Only the selected read, not run-list metric reads. delay.captured.resolve(); await delay.release.promise; delay.delivered.resolve(); } return response; } if (pathname.startsWith('/assets/') && !pathname.includes('..')) { const file = Bun.file( new URL(`../../apps/stock/web-app/dist${pathname}`, import.meta.url) ); return (await file.exists()) ? new Response(file) : new Response('Not found', { status: 404 }); } return new Response( Bun.file(new URL('../../apps/stock/web-app/dist/index.html', import.meta.url)) ); }, websocket: { open(socket) { sockets.add(socket); handleWebSocketConnection(socket); }, message(socket, message) { getWebSocketHandler()?.handleMessage(socket, message); }, close(socket) { sockets.delete(socket); getWebSocketHandler()?.handleClose(socket); }, }, }); cleanup.push(async () => { getWebSocketHandler()?.cleanup(); const report = setTimeout( () => process.stderr.write( `browser server stop pending: requests=${server.pendingRequests} websockets=${server.pendingWebSockets} sockets=${sockets.size}\n` ), 4000 ); server.unref(); try { await server.stop(true); } finally { clearTimeout(report); } }); const origin = `http://127.0.0.1:${server.port}`; const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } }); cleanup.push(() => context.close()); await context.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin !== origin && !['data:', 'blob:'].includes(url.protocol)) { // Existing font imports remain offline; never permit external egress. if ( !( route.request().resourceType() === 'stylesheet' && url.origin === 'https://fonts.googleapis.com' && url.pathname === '/css2' && /^(Inter|JetBrains Mono):/.test(url.searchParams.get('family') ?? '') ) ) { unexpectedNetwork.push(url.origin); } return route.abort('blockedbyclient'); } return route.continue(); }); // The HTTP interception API does not intercept WebSocket handshakes. await context.addInitScript(expectedOrigin => { const Original = window.WebSocket; const connections = new Set(); Object.defineProperty(window, '__disconnectFixtureSockets', { value: () => { for (const connection of connections) { connection.close(); } }, }); window.WebSocket = class extends Original { constructor(url: string | URL, protocols?: string | string[]) { const endpoint = new URL(url, window.location.href); if (endpoint.origin !== expectedOrigin.replace(/^http/, 'ws')) { throw new Error('External fixture WebSocket blocked'); } super(url, protocols); connections.add(this); this.addEventListener('close', () => connections.delete(this)); } }; }, origin); const page = await context.newPage(); page.setDefaultTimeout(10000); const frames: { type: string; runId: string; data?: { progress?: number } }[] = []; page.on('websocket', socket => socket.on('framereceived', frame => { try { frames.push(JSON.parse(frame.payload.toString())); } catch { /* Non-JSON cannot satisfy assertions. */ } }) ); const login = async (target: Page = page) => { await target.goto(`${origin}/backtests`); await target.getByLabel('Access token').fill(token); await target.getByRole('button', { name: 'Sign in', exact: true }).click(); await visible(target, 'Create and manage backtest configurations'); }; const request = async ( path: string, method = 'GET', body?: unknown, headers: Record = {} ) => { const response = await fetch(origin + path, { method, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', ...headers, }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!response.ok) { throw new Error( `Fixture API ${method} ${path}: ${response.status} ${await response.text()}` ); } return response.json(); }; return { pool, page, context, origin, frames, delayResponse, controlled, failNextCanonical: (message: string) => { if (!native) { throw new Error('A native fixture is required for canonical failure injection'); } canonicalFailures.push(message); }, dispatcher, request, login, close, unexpectedNetwork, historicalDataReads, seedCatalog: () => seedBuiltinCatalog(new StrategyCatalogService(container)), }; } catch (error) { try { await close(); } catch (cleanupError) { throw new AggregateError([error, cleanupError], 'Browser fixture startup and cleanup failed'); } throw error; } } export async function createInBrowser(page: Page, name: string, run = false) { await page.getByRole('button', { name: 'New Backtest', exact: true }).click(); await page.getByPlaceholder('My Strategy Backtest').fill(name); await page.getByLabel('Legacy strategy', { exact: true }).selectOption('moving-average'); await page.locator('input[type="date"]').nth(0).fill('2024-01-01'); await page.locator('input[type="date"]').nth(1).fill('2024-03-15'); await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click(); await page.waitForURL(run ? /\/backtests\/[^/]+\/run\/[^/]+$/ : /\/backtests\/[^/]+$/); } export async function submitInBrowser(page: Page) { await page.getByRole('button', { name: 'New Run', exact: true }).click(); const response = page.waitForResponse( response => response.request().method() === 'POST' && /\/api\/v2\/backtests\/[^/]+\/runs$/.test(response.url()) ); await page .getByRole('button', { name: 'Run current settings', exact: true }) .filter({ hasText: 'Run current settings' }) .click(); const accepted = await response; const run = await accepted.json(); await page.waitForURL(url => url.pathname.endsWith(`/run/${run.id}`)); return accepted; }