feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -10,15 +10,13 @@ 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 type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
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 { loadDataset } 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 {
@ -30,6 +28,7 @@ import {
handleWebSocketConnection,
} from '../../apps/stock/web-api/src/routes/websocket.routes';
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service';
import { StrategyCatalogService } from '../../apps/stock/web-api/src/services/strategy-catalog.service';
import {
getWebSocketHandler,
@ -139,23 +138,26 @@ export async function retainDataset(pool: Pool, overrides: Partial<BacktestConfi
return dataset;
}
/** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */
/** Controlled lifecycle around the real canonical engine; no fixture accounting. */
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<NativeBacktestResult> {
if (!resolver) {
throw new Error('Fixture must exercise durable dataset resolution');
}
const dataset = await resolver(() => loadDataset(storage, config));
private readonly engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 });
async runBacktest(): Promise<never> {
throw new Error('Legacy execution is retired');
}
async runCanonical(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
this.cancelled = false;
this.emit('progress', { progress: 25, currentDate: config.startDate });
this.emit('progress', {
progress: 25,
currentDate: new Date(request.policy.matching.risk.ledger.riskSession.startsAt).toISOString(),
});
await this.completion.promise;
if (this.cancelled) {
throw new BacktestCancelledError();
@ -163,53 +165,14 @@ class FixtureEngine extends EventEmitter {
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)])
),
};
// Empty outcomes use an admitted strategy with insufficient warmup; never edit the result.
return this.engine.runCanonical(request, resolveDataset);
}
async stopBacktest() {
this.cancelled = true;
if (this.engine.getStatus().isRunning) {
await this.engine.stopBacktest();
}
this.stopped.resolve();
await this.cancellation.promise;
this.completion.resolve();
@ -227,6 +190,7 @@ class FixtureEngine extends EventEmitter {
async shutdown() {
this.cancellation.resolve();
this.completion.resolve();
await this.engine.shutdown();
}
}
@ -313,6 +277,7 @@ export async function fixture(browser: Browser, native = false) {
'25-walk-forward.sql',
'26-cost-sensitivity.sql',
'27-research-evidence-sources.sql',
'28-research-agents.sql',
]) {
await pool.query(
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
@ -435,6 +400,7 @@ export async function fixture(browser: Browser, native = false) {
},
} as unknown as NonNullable<IServiceContainer['mongodb']>;
const container = { postgres, mongodb, logger } as IServiceContainer;
const researchAgents = new ResearchAgentsService(container);
const token = randomUUID() + randomUUID();
const security = createHttpSecurity({
adminToken: token,
@ -442,6 +408,7 @@ export async function fixture(browser: Browser, native = false) {
browserSessions: true,
environment: 'test',
origins: [],
resolveResearchCredential: request => researchAgents.authenticate(request),
});
const routes = createRoutes(container, security);
const wsRoute = createWebSocketRoute(container, security);
@ -476,6 +443,8 @@ export async function fixture(browser: Browser, native = false) {
!pathname.startsWith('/api/v2/strategies') &&
!pathname.startsWith('/api/v2/strategy-versions') &&
!pathname.startsWith('/api/v2/research-projects') &&
!pathname.startsWith('/api/v2/research-agents') &&
!pathname.startsWith('/api/v2/research-agent/') &&
!pathname.startsWith('/api/v2/experiments') &&
!pathname.startsWith('/api/v2/hypotheses/') &&
!pathname.startsWith('/api/v2/analysis-artifacts/') &&
@ -657,16 +626,6 @@ export async function fixture(browser: Browser, native = false) {
}
}
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(