172 lines
5.1 KiB
TypeScript
172 lines
5.1 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { EventEmitter } from 'node:events';
|
|
import { expect } 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 { type BacktestExecutionEngine } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
|
import { type BacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/run-repository';
|
|
import { canonicalSmaFixture } from './canonical-sma';
|
|
|
|
const logger = { error() {} };
|
|
export function canonicalRunnerFixture() {
|
|
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 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 loadCanonicalDataset(_id, _attempt, hash) {
|
|
expect(hash).toBe(dataset.manifest.hash);
|
|
events.push('dataset');
|
|
return dataset;
|
|
},
|
|
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';
|
|
},
|
|
};
|
|
const engine = Object.assign(new EventEmitter(), {
|
|
async runCanonical(
|
|
_input: typeof request,
|
|
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
|
) {
|
|
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');
|
|
},
|
|
getStatus() {
|
|
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
|
|
},
|
|
async shutdown() {},
|
|
}) satisfies BacktestExecutionEngine;
|
|
const runner = new BacktestRunner({
|
|
engine,
|
|
repository: repo,
|
|
logger,
|
|
heartbeatMs: 5,
|
|
heartbeatTimeoutMs: 50,
|
|
});
|
|
return {
|
|
request,
|
|
dataset,
|
|
repo,
|
|
engine,
|
|
runner,
|
|
events,
|
|
get result() {
|
|
return result;
|
|
},
|
|
setStatus(next: string) {
|
|
status = next;
|
|
},
|
|
loseLease() {
|
|
heartbeatFailure = true;
|
|
},
|
|
};
|
|
}
|
|
|
|
export function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (error: Error) => void;
|
|
const promise = new Promise<T>((a, b) => {
|
|
resolve = a;
|
|
reject = b;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|