fix(monitoring): report observed research and paper readiness (O02)

This commit is contained in:
Boki 2026-10-28 12:58:38 -04:00
parent 70d173a908
commit 8c858b9d5c
23 changed files with 1340 additions and 319 deletions

View file

@ -5,6 +5,7 @@
* mutable fields never represent a shared paper account or several simultaneous runs.
*/
import { EventEmitter } from 'node:events';
import { redactLogValue } from '@stock-bot/logger';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
@ -323,6 +324,10 @@ export class BacktestRunner extends EventEmitter {
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? deadlineFailure ?? error;
const publicFailure = () =>
new Error(
`Backtest failed during ${this.phase}: ${redactLogValue(failure instanceof Error ? failure.message : String(failure))}`
);
// After lease loss, another worker may own the run. Even a failure/cancellation
// write would be an unauthorized state change, so leave recovery to the store.
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
@ -332,7 +337,7 @@ export class BacktestRunner extends EventEmitter {
} else {
await this.dependencies.repository.fail(
this.active.runId,
failure instanceof Error ? failure.message : String(failure),
publicFailure().message,
this.active.attemptId
);
}
@ -351,7 +356,7 @@ export class BacktestRunner extends EventEmitter {
status: 'cancelled',
});
} else if (this.listenerCount('error')) {
this.publish('error', failure);
this.publish('error', publicFailure());
}
throw failure;
} finally {
@ -453,6 +458,16 @@ export class BacktestRunner extends EventEmitter {
this.requireActive(runId);
throw new Error('Native backtests run at maximum speed');
}
/** A local attempt snapshot; PostgreSQL remains authoritative for leases. */
getAttemptDiagnostics() {
return {
runId: this.active?.runId ?? null,
backtestId: this.active?.backtestId ?? null,
attemptId: this.active?.attemptId ?? null,
strategyVersionId: this.active?.config.strategy.versionId ?? null,
phase: this.busy ? this.phase : ('idle' as const),
};
}
/** Local worker projection; persisted run status remains authoritative after restart. */
getStatus() {
return {

View file

@ -2,6 +2,7 @@ import { EventEmitter } from 'node:events';
import { z } from 'zod';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import type { researchRuntimeSchema } from '@stock-bot/stock-config/diagnostics';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestRunner } from './BacktestRunner';
import { BacktestCancelledError, LEGACY_EXECUTION_RETIRED } from './execution-engine';
@ -27,6 +28,7 @@ export type ResearchBacktestRuntime = Pick<
> &
Pick<EventEmitter, 'on' | 'off'> & {
getStatus(runId?: string): ReturnType<BacktestRunner['getStatus']>;
getDiagnostics?(): z.infer<typeof researchRuntimeSchema>;
};
type Reservation = {
@ -155,6 +157,14 @@ export class ResearchBacktestPool extends EventEmitter implements ResearchBackte
const [runId, { runner }] = this.resolve(input);
await runner.setSpeedMultiplier(speed, runId);
}
getDiagnostics() {
return {
accepting: !this.closing,
capacity: this.runners.length,
slots: this.runners.map(runner => runner.getAttemptDiagnostics()),
};
}
getStatus(input?: string): ReturnType<BacktestRunner['getStatus']> {
if (input === undefined && this.reservations.size === 0) {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId: undefined };

View file

@ -1,9 +1,14 @@
import { Hono } from 'hono';
import type { Server as SocketIOServer } from 'socket.io';
import {
orchestratorDiagnosticSchema,
paperDiagnosticSchema,
} from '@stock-bot/stock-config/diagnostics';
import { createAnalyticsRoutes } from '../api/rest/analytics';
import { createBacktestRoutes } from '../api/rest/backtest';
import { createPaperRoutes } from '../api/rest/paper';
import { createPaperDeploymentHostRoutes } from '../api/rest/paper-deployments';
import { readCanonicalBuildIdentity } from '../backtest/canonical-build';
import type { OrchestratorServices as IServiceContainer } from '../types';
/**
@ -35,6 +40,30 @@ export function createRoutes(
});
});
// Read-only evidence. No child is launched and no paper recovery/activation occurs.
app.get('/api/diagnostics', async c => {
const runtime = services.custom?.CanonicalPaperRuntime;
const host = services.custom?.PaperDeploymentHost;
const [build, paper] = await Promise.all([
readCanonicalBuildIdentity().catch(() => null),
(host ? host.readiness() : runtime ? runtime.status() : Promise.resolve(null))
.then(value => (value === null ? null : paperDiagnosticSchema.parse(value)))
.catch(() => null),
]);
c.header('Cache-Control', 'no-store');
return c.json(
orchestratorDiagnosticSchema.parse({
service: 'orchestrator',
observedAt: new Date().toISOString(),
research: services.custom?.BacktestRunner?.getDiagnostics?.() ?? null,
build,
nativeExecution: 'unverified-until-run',
paper,
live: 'disabled',
})
);
});
// Mount REST API routes
app.get('/api/recovery', async c => {
try {