import { randomUUID } from 'node:crypto'; import { EventEmitter } from 'node:events'; import { describe, expect, test } from 'bun:test'; import { canonicalRunRequestSchema, type CanonicalRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { HistoricalDatasetV2 } from '@stock-bot/types'; import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { BacktestCancelledError, type BacktestExecutionEngine, } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { BacktestLeaseLostError, type BacktestRunRepository, } from '../../apps/stock/orchestrator/src/backtest/run-repository'; import { canonicalSmaFixture } from '../fixtures/canonical-sma'; const logger = { error() {} }; function setup() { const versionId = randomUUID(), runId = randomUUID(), ownerId = `strategy:${versionId}`; const { dataset, config, selections } = canonicalSmaFixture([ownerId]); config.matching.risk.ledger.sessionId = runId; config.matching.risk.ledger.accountId = `research:${runId}`; const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!; const request = canonicalRunRequestSchema.parse({ kind: 'canonical-research/v1', runId, backtestId: randomUUID(), name: 'Runner boundary', strategy: { familyId: randomUUID(), versionId, origin: 'builtin', reviewId: randomUUID(), selection: selections[0], package: { version: 1, program: descriptor.program, parameterSchema: descriptor.parameterSchema, artifact: { format: 'esm-bundle/v1', entryExport: descriptor.entryExport, content: 'not executed by this lifecycle fixture', sha256: 'a'.repeat(64), }, dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) }, source: { revision: 'c'.repeat(40), dirty: false }, build: { tool: 'bun', version: 'fixture', target: 'browser' }, }, }, datasetHash: dataset.manifest.hash, policy: config, analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null }, modelArtifacts: [], build: { version: 1, workerSha256: 'd'.repeat(64), engineWrapperSha256: 'e'.repeat(64), engineBinarySha256: 'f'.repeat(64), dependencyLockSha256: 'b'.repeat(64), runtime: 'bun', runtimeVersion: 'fixture', platform: 'linux', arch: 'x64', }, }); const events: string[] = []; let result: CanonicalRunResult | undefined; let heartbeatFailure = false; let status = 'pending'; const repo: BacktestRunRepository = { async start() { throw new Error('legacy claim must not run'); }, async startCanonical(input) { events.push('claim'); status = 'running'; return { runId, backtestId: request.backtestId, attemptId: 'attempt', config: structuredClone(input), }; }, async load() { return { status, config: structuredClone(request) }; }, async rejectPending() { events.push('reject'); status = 'failed'; }, async heartbeat() { events.push('heartbeat'); if (heartbeatFailure) { throw new Error('lost'); } return { cancelRequested: false }; }, async loadDataset() { throw new Error('v1 data must not run'); }, async freezeDataset() { throw new Error('provider freeze must not run'); }, async loadCanonicalDataset(_id, _attempt, hash) { expect(hash).toBe(dataset.manifest.hash); events.push('dataset'); return dataset; }, async complete() { throw new Error('legacy completion must not run'); }, async completeCanonical(input) { events.push('complete'); result = input; status = 'completed'; }, async updateProgress() { events.push('progress'); }, async fail() { events.push('fail'); status = 'failed'; }, async cancel() { events.push('cancel'); status = 'cancelled'; }, async updateControl() {}, }; const engine = Object.assign(new EventEmitter(), { async runBacktest(): Promise { throw new Error('legacy simulator must not run'); }, async runCanonical( _input: typeof request, resolve: (signal: AbortSignal) => Promise ) { await resolve(new AbortController().signal); events.push('execute'); // Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only. return { financial: {} as CanonicalRunResult['financial'], analytics: {} as CanonicalRunResult['analytics'], }; }, async stopBacktest() { events.push('stop'); }, async pauseBacktest() {}, async resumeBacktest() {}, setSpeedMultiplier() {}, getStatus() { return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 }; }, async shutdown() {}, }) satisfies BacktestExecutionEngine; const runner = new BacktestRunner({ engine, repository: repo, engineName: 'native', logger, heartbeatMs: 5, heartbeatTimeoutMs: 50, async prepare() { throw new Error('legacy preparation must not run'); }, }); return { request, dataset, repo, engine, runner, events, get result() { return result; }, loseLease() { heartbeatFailure = true; }, }; } function deferred() { let resolve!: (value: T) => void; let reject!: (error: Error) => void; const promise = new Promise((a, b) => { resolve = a; reject = b; }); return { promise, resolve, reject }; } describe('canonical jobs share the durable runner lifecycle', () => { test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => { const f = setup(); expect(await f.runner.runQueued(f.request.runId)).toEqual({ runId: f.request.runId, status: 'completed', }); expect(f.events).toEqual(['claim', 'heartbeat', 'dataset', 'execute', 'complete']); expect(f.result?.request).toEqual(f.request); expect(f.result?.kind).toBe('canonical-result/v1'); expect(await f.runner.runQueued(f.request.runId)).toEqual({ runId: f.request.runId, status: 'completed', }); expect(f.events.filter(e => e === 'execute')).toHaveLength(1); await expect(f.runner.runBacktest(f.request)).rejects.toThrow(); await f.runner.shutdown(); }); test('legacy entry refuses canonical markers even when the remaining fields look legacy', async () => { const f = setup(); const legacy = { mode: 'backtest', strategy: 'sma-crossover', symbols: ['X.US'], startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-02-01T00:00:00.000Z', initialCapital: 10000, dataFrequency: '1d', }; for (const marker of [ { kind: 'canonical-research/v1' }, { kind: 'canonical-research/v999' }, { canonical: {} }, ]) { await expect(f.runner.runBacktest({ ...legacy, ...marker })).rejects.toThrow( 'Retained strategy versions' ); } expect(f.events).toEqual([]); await f.runner.shutdown(); }); test('a runner without canonical execution fails without preparation or legacy/provider fallback', async () => { const f = setup(); const engine: BacktestExecutionEngine = f.engine; delete engine.runCanonical; const fail = f.repo.fail.bind(f.repo); let savedFailure: string | undefined; f.repo.fail = async (runId, error, attemptId) => { savedFailure = error; await fail(runId, error, attemptId); }; try { await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow( 'Canonical execution capabilities are unavailable' ); expect(savedFailure).toBe('Canonical execution capabilities are unavailable'); expect(f.events).toEqual(['claim', 'heartbeat', 'fail']); expect(f.result).toBeUndefined(); expect(await f.runner.runQueued(f.request.runId)).toEqual({ runId: f.request.runId, status: 'failed', }); expect(f.events).toEqual(['claim', 'heartbeat', 'fail']); } finally { await f.runner.shutdown(); } }); test('cancel waits for execution to finish before committing cancellation', async () => { const f = setup(), entered = deferred(), reaped = deferred(), exit = deferred(); f.engine.runCanonical = async () => { entered.resolve(); return exit.promise; }; f.engine.stopBacktest = async () => { f.events.push('stop'); await reaped.promise; exit.reject(new BacktestCancelledError()); }; const run = f.runner.runQueued(f.request.runId); const failed = run.catch(error => error); await entered.promise; let stopped = false; const stop = f.runner.stopBacktest(f.request.runId).then(() => { stopped = true; }); await Promise.resolve(); expect(stopped).toBe(false); expect(f.events).not.toContain('cancel'); reaped.resolve(); await stop; expect(await failed).toBeInstanceOf(BacktestCancelledError); expect(f.events).toContain('cancel'); expect(f.events).not.toContain('complete'); await f.runner.shutdown(); }); test('lease loss stops execution without overwriting a newer owner terminal state', async () => { const f = setup(), entered = deferred(), exit = deferred(); f.engine.runCanonical = async () => { entered.resolve(); return exit.promise; }; f.engine.stopBacktest = async () => { f.events.push('stop'); exit.reject(new BacktestCancelledError()); }; const run = f.runner.runQueued(f.request.runId); const failed = run.catch(error => error); await entered.promise; f.loseLease(); expect(await failed).toBeInstanceOf(BacktestLeaseLostError); expect(f.events).toContain('stop'); expect(f.events).not.toContain('fail'); expect(f.events).not.toContain('cancel'); expect(f.events).not.toContain('complete'); await f.runner.shutdown(); }); test('invalid persisted canonical kind never becomes a legacy run', async () => { const f = setup(); f.repo.load = async () => ({ status: 'pending', config: { ...f.request, kind: 'canonical-research/v2' }, }); await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow(); expect(f.events).toEqual(['reject']); await f.runner.shutdown(); }); });