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

@ -3,22 +3,21 @@ import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
isCanonicalRunResult,
type CanonicalRunRequest,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestCancelledError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
export { parseBacktestRequest };
@ -32,16 +31,16 @@ function parseDurableRequest(input: unknown): DurableRequest {
: parseBacktestRequest(input);
}
/** One application workflow for HTTP, jobs, and both execution backends. */
/** One canonical workflow for durably admitted research jobs. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunClaim | CanonicalRunClaim | undefined;
private active: CanonicalRunClaim | undefined;
private leaseFailure: BacktestLeaseLostError | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<ResearchRunResult> | undefined;
private execution: Promise<CanonicalRunResult> | undefined;
constructor(
private readonly dependencies: {
@ -51,20 +50,18 @@ export class BacktestRunner extends EventEmitter {
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
/** Retained only to diagnose obsolete callers; canonical work requires durable admission. */
async runBacktest(input: unknown): Promise<BacktestRunResult> {
return this.begin(parseBacktestRequest(input));
parseBacktestRequest(input);
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
private begin(config: BacktestConfig): Promise<BacktestRunResult>;
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult> {
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
@ -101,15 +98,32 @@ export class BacktestRunner extends EventEmitter {
);
throw error;
}
const result = await this.begin({ ...snapshot, runId });
if (!isCanonicalRequest(snapshot)) {
await this.dependencies.repository.rejectPending(runId, LEGACY_EXECUTION_RETIRED);
const retired = await this.dependencies.repository.load(runId);
return { runId, status: retired?.status ?? 'missing' };
}
const result = await this.begin(snapshot);
return { runId, status: result.status };
}
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
deadlineFailure ??= new Error('Research attempt exceeded its admitted execution deadline');
}
if (deadlineFailure) {
throw deadlineFailure;
}
};
const heartbeat = async () => {
const active = this.active;
if (!active) {
@ -183,19 +197,43 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
if (isCanonicalRequest(config)) {
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
} else {
this.active = await this.dependencies.repository.start(config);
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
if (
this.active.executionDeadlineAt !== undefined &&
(!Number.isSafeInteger(this.active.executionDeadlineAt) ||
this.active.executionDeadlineAt - Date.now() > 2_147_483_647)
) {
throw new Error('Invalid admitted research execution deadline');
}
checkDeadline();
if (this.active.executionDeadlineAt !== undefined) {
executionDeadline = setTimeout(
() => {
deadlineFailure = new Error(
'Research attempt exceeded its admitted execution deadline'
);
if (this.phase === 'executing') {
deadlineStop = this.dependencies.engine.stopBacktest().catch(error => {
this.dependencies.logger.error('Could not stop expired research attempt', {
error,
});
});
}
},
Math.max(0, this.active.executionDeadlineAt - Date.now())
);
executionDeadline.unref();
}
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
executionConfig.backtestId !== this.active.backtestId
) {
throw new Error('Canonical claim identity mismatch');
}
const executionConfig = parseDurableRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
});
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
@ -205,15 +243,7 @@ export class BacktestRunner extends EventEmitter {
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
checkDeadline();
if (this.leaseFailure) {
throw this.leaseFailure;
}
@ -221,8 +251,8 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestCancelledError();
}
this.phase = 'executing';
let result: ResearchRunResult;
if (isCanonicalRequest(executionConfig)) {
let result: CanonicalRunResult;
{
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const loadCanonicalDataset = repository.loadCanonicalDataset;
@ -254,89 +284,40 @@ export class BacktestRunner extends EventEmitter {
request: executionConfig,
...report,
};
} else {
let manifest: HistoricalDatasetManifest | undefined;
const claim = this.active;
const raw = await this.dependencies.engine.runBacktest(
executionConfig,
async (load, signal) => {
signal?.throwIfAborted();
const saved = await this.dependencies.repository.loadDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
);
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
signal?.throwIfAborted();
const frozen =
saved ??
(await this.dependencies.repository.freezeDataset(
claim.runId,
claim.attemptId,
dataset,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled,
manifest
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
}
checkDeadline();
this.phase = 'persisting';
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (isCanonicalRunResult(result)) {
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
} else {
await this.dependencies.repository.complete(result, this.active.attemptId);
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
checkDeadline();
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? error;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error),
failure instanceof Error ? failure.message : String(failure),
this.active.attemptId
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
if (failure instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
@ -352,6 +333,10 @@ export class BacktestRunner extends EventEmitter {
}
throw failure;
} finally {
if (executionDeadline) {
clearTimeout(executionDeadline);
}
await deadlineStop;
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}