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

@ -48,7 +48,9 @@ export function createRoutes(
// Create routes with container
const healthRoutes = createHealthRoutes(container);
const exchangeRoutes = createExchangeRoutes(container);
const monitoringRoutes = createMonitoringRoutes(container);
const monitoringRoutes = createMonitoringRoutes(container, {
origin: integrations ? integrations.paperOrchestratorOrigin : process.env.ORCHESTRATOR_URL,
});
const pipelineRoutes = createPipelineRoutes(container);
const backtestRoutes = createBacktestRoutes(container);
const backtestV2Routes = createBacktestV2Routes(container);

View file

@ -6,9 +6,17 @@ import { Hono } from 'hono';
import type { IServiceContainer } from '@stock-bot/handlers';
import { MonitoringService } from '../services/monitoring.service';
export function createMonitoringRoutes(container: IServiceContainer) {
export function createMonitoringRoutes(
container: IServiceContainer,
options: ConstructorParameters<typeof MonitoringService>[1] = {}
) {
const monitoring = new Hono();
const monitoringService = new MonitoringService(container);
const monitoringService = new MonitoringService(container, options);
monitoring.get('/readiness', async c => {
c.header('Cache-Control', 'no-store');
return c.json(await monitoringService.getReadiness(c.req.raw));
});
/**
* Get overall system health
@ -22,12 +30,12 @@ export function createMonitoringRoutes(container: IServiceContainer) {
health.status === 'healthy' ? 200 : health.status === 'degraded' ? 503 : 500;
return c.json(health, statusCode);
} catch (error) {
} catch {
return c.json(
{
status: 'error',
message: 'Failed to retrieve system health',
error: error instanceof Error ? error.message : 'Unknown error',
error: 'Diagnostic dependency unavailable',
},
500
);
@ -41,11 +49,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const stats = await monitoringService.getCacheStats();
return c.json(stats);
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve cache statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -59,11 +67,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const stats = await monitoringService.getQueueStats();
return c.json({ queues: stats });
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve queue statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -90,11 +98,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
}
return c.json(queueStats);
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve queue statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -108,11 +116,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const stats = await monitoringService.getDatabaseStats();
return c.json({ databases: stats });
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve database statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -139,11 +147,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
}
return c.json(dbStats);
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve database statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -157,11 +165,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const metrics = await monitoringService.getServiceMetrics();
return c.json(metrics);
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve service metrics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -189,11 +197,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
parsed: stats,
raw: null, // Raw Redis commands are not part of the cache capability.
});
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve cache info',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -218,11 +226,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const services = await monitoringService.getServiceStatus();
return c.json({ services });
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve service status',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -236,11 +244,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const stats = await monitoringService.getProxyStats();
return c.json(stats || { enabled: false });
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve proxy statistics',
message: error instanceof Error ? error.message : 'Unknown error',
message: 'Diagnostic dependency unavailable',
},
500
);
@ -254,45 +262,11 @@ export function createMonitoringRoutes(container: IServiceContainer) {
try {
const overview = await monitoringService.getSystemOverview();
return c.json(overview);
} catch (error) {
} catch {
return c.json(
{
error: 'Failed to retrieve system overview',
message: error instanceof Error ? error.message : 'Unknown error',
},
500
);
}
});
/**
* Test direct BullMQ queue access
*/
monitoring.get('/test/queue/:name', async c => {
const queueName = c.req.param('name');
const { Queue } = await import('bullmq');
const connection = {
host: 'localhost',
port: 6379,
db: 0, // All queues in DB 0
};
const queue = new Queue(queueName, { connection });
try {
const counts = await queue.getJobCounts();
await queue.close();
return c.json({
queueName,
counts,
});
} catch (error) {
await queue.close();
return c.json(
{
queueName,
error: error instanceof Error ? error.message : String(error),
message: 'Diagnostic dependency unavailable',
},
500
);

View file

@ -7,6 +7,11 @@ import * as os from 'os';
import type { IServiceContainer } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { getFullQueueName } from '@stock-bot/queue';
import {
monitoringReadinessSchema,
orchestratorDiagnosticSchema,
type MonitoringReadiness,
} from '@stock-bot/stock-config/diagnostics';
import type {
CacheStats,
DatabaseStats,
@ -22,7 +27,135 @@ export class MonitoringService {
private readonly logger = getLogger('monitoring-service');
private startTime = Date.now();
constructor(private readonly container: IServiceContainer) {}
constructor(
private readonly container: IServiceContainer,
private readonly options: {
origin?: string;
request?: (url: URL, init: RequestInit) => Promise<Response>;
} = {}
) {}
/** Explicit prerequisites and unknown execution capability; never a readiness shortcut. */
async getReadiness(request: Request): Promise<MonitoringReadiness> {
const reasons: string[] = [];
const [leases, queue, orchestrator] = await Promise.all([
(async () => {
try {
if (!this.container.postgres) {
return null;
}
const result = await this.container.postgres.query<{
run_id: string;
attempt_id: string | null;
expired: boolean;
}>(
"SELECT id AS run_id, attempt_id, (lease_expires_at IS NULL OR lease_expires_at <= NOW()) AS expired FROM runs WHERE status IN ('running','paused') ORDER BY id"
);
return result.rows.map(row => ({
runId: row.run_id,
attemptId: row.attempt_id,
expired: row.expired,
}));
} catch {
return null;
}
})(),
(async () => {
try {
if (!this.container.queueManager) {
throw new Error('Unavailable');
}
const snapshot = await this.container.queueManager
.getQueue(getFullQueueName('orchestrator', 'orchestrator'), { workers: 0 })
.getStats();
return { connected: true, workers: snapshot.workers ?? null, paused: snapshot.paused };
} catch {
return { connected: false, workers: null, paused: null };
}
})(),
(async () => {
try {
if (!this.options.origin) {
return null;
}
const origin = new URL(this.options.origin);
if (
!['http:', 'https:'].includes(origin.protocol) ||
origin.username ||
origin.password ||
origin.pathname !== '/' ||
origin.search ||
origin.hash
) {
return null;
}
const headers = new Headers();
for (const name of ['authorization', 'cookie', 'origin']) {
const value = request.headers.get(name);
if (value) {
headers.set(name, value);
}
}
const response = await (this.options.request ?? fetch)(
new URL('/api/diagnostics', origin),
{ headers, redirect: 'error', signal: AbortSignal.timeout(5000) }
);
if (!response.ok) {
return null;
}
return orchestratorDiagnosticSchema.parse(await response.json());
} catch {
return null;
}
})(),
]);
if (leases === null) {
reasons.push('Research PostgreSQL unavailable');
}
if (!queue.connected) {
reasons.push('Research queue unavailable');
}
if (queue.workers === null) {
reasons.push('Research worker count unknown');
} else if (queue.workers === 0) {
reasons.push('No research queue workers');
}
if (queue.paused) {
reasons.push('Research queue paused');
}
if (!orchestrator) {
reasons.push(
this.options.origin
? 'Orchestrator diagnostics unavailable'
: 'Configure ORCHESTRATOR_URL to inspect orchestrator readiness'
);
} else {
if (!orchestrator.research) {
reasons.push('Research runtime unavailable');
} else if (!orchestrator.research.accepting) {
reasons.push('Research runtime shutting down');
}
if (!orchestrator.build) {
reasons.push('Canonical build artifacts unavailable');
}
}
if (leases?.some(lease => lease.expired)) {
reasons.push('Expired research attempts require durable recovery');
}
const unavailable = reasons.length > 0;
reasons.push(
'Native execution is verified at run start; this snapshot does not launch a worker'
);
return monitoringReadinessSchema.parse({
observedAt: new Date().toISOString(),
postgres: leases === null ? 'unavailable' : 'connected',
queue,
leases,
orchestrator,
research: { status: unavailable ? 'unavailable' : 'unknown', reasons },
live: 'disabled',
});
}
/**
* Get cache/Dragonfly statistics
@ -56,9 +189,7 @@ export class MonitoringService {
stats: {
hits: cacheStats.hits,
misses: cacheStats.misses,
keys: 0, // We can't get total keys without direct Redis access
evictedKeys: 0,
expiredKeys: 0,
keys: null, // Not measured by the public cache capability.
},
};
} catch (error) {
@ -85,26 +216,28 @@ export class MonitoringService {
webshare: 'data-ingestion',
exchanges: 'data-pipeline',
symbols: 'data-pipeline',
orchestrator: 'orchestrator',
};
return Promise.all(
Object.entries(owners).map(async ([name, service]) => {
try {
const queue = manager.getQueue(getFullQueueName(service, name));
const queue = manager.getQueue(getFullQueueName(service, name), { workers: 0 });
const snapshot = await queue.getStats();
return {
name,
service,
queue: name,
connected: true,
paused: snapshot.paused,
jobs: {
waiting: snapshot.waiting,
active: snapshot.active,
completed: snapshot.completed,
failed: snapshot.failed,
delayed: snapshot.delayed,
paused: snapshot.paused ? 1 : 0,
paused: null, // Queue pause status does not measure paused-job count.
},
workers: { count: snapshot.workers ?? queue.getWorkerCount(), concurrency: 1 },
workers: snapshot.workers === undefined ? undefined : { count: snapshot.workers },
};
} catch (error) {
this.logger.warn('Unable to inspect queue', { name, service, error });
@ -113,7 +246,7 @@ export class MonitoringService {
service,
queue: name,
connected: false,
jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 },
jobs: null,
};
}
})
@ -199,7 +332,8 @@ export class MonitoringService {
const startTime = Date.now();
// QuestDB health check
const response = await fetch(
`http://${process.env.QUESTDB_HOST || 'localhost'}:9000/exec?query=SELECT%201`
`http://${process.env.QUESTDB_HOST || 'localhost'}:9000/exec?query=SELECT%201`,
{ signal: AbortSignal.timeout(5000), redirect: 'error' }
);
const latency = Date.now() - startTime;
@ -249,6 +383,18 @@ export class MonitoringService {
errors.push(`${disconnectedQueues.length} queue(s) are disconnected`);
}
if (!databaseStats.some(db => db.type === 'postgres')) {
errors.push('Research PostgreSQL is not configured');
}
if (
!queueStats.some(
queue =>
queue.service === 'orchestrator' && queue.connected && (queue.workers?.count ?? 0) > 0
)
) {
errors.push('Research queue worker unavailable');
}
const disconnectedDbs = databaseStats.filter(db => !db.connected);
if (disconnectedDbs.length > 0) {
errors.push(`${disconnectedDbs.length} database(s) are disconnected`);
@ -288,58 +434,27 @@ export class MonitoringService {
return {
requestsPerSecond: {
timestamp: now,
value: 0,
value: null,
unit: 'req/s',
},
averageResponseTime: {
timestamp: now,
value: 0,
value: null,
unit: 'ms',
},
errorRate: {
timestamp: now,
value: 0,
value: null,
unit: '%',
},
activeConnections: {
timestamp: now,
value: 0,
value: null,
unit: 'connections',
},
};
}
/**
* Parse value from Redis INFO output
*/
private parseInfoValue(info: string, key: string): number {
const match = info.match(new RegExp(`${key}:(\\d+)`));
return match?.[1] ? parseInt(match[1], 10) : 0;
}
/**
* Parse Redis INFO into structured object
*/
private parseRedisInfo(info: string): Record<string, Record<string, string>> {
const result: Record<string, Record<string, string>> = {};
const sections = info.split('\r\n\r\n');
for (const section of sections) {
const lines = section.split('\r\n');
const sectionName = lines[0]?.replace('# ', '') || 'general';
result[sectionName] = {};
for (let i = 1; i < lines.length; i++) {
const [key, value] = (lines[i] ?? '').split(':');
if (key && value) {
result[sectionName][key] = value;
}
}
}
return result;
}
/**
* Get service status for all microservices
*/
@ -359,12 +474,12 @@ export class MonitoringService {
if (service.name === 'web-api') {
services.push({
name: 'web-api',
version: '1.0.0',
version: 'unknown',
status: 'running',
port: process.env.PORT ? parseInt(process.env.PORT) : 2003,
uptime: Date.now() - this.startTime,
lastCheck: new Date().toISOString(),
healthy: true,
healthy: null,
});
continue;
}
@ -379,12 +494,15 @@ export class MonitoringService {
const data = await response.json();
services.push({
name: service.name,
version: data.version || '1.0.0',
version: typeof data.version === 'string' ? data.version : 'unknown',
status: 'running',
port: service.port,
uptime: data.uptime || 0,
uptime:
typeof data.uptime === 'number' && Number.isFinite(data.uptime) && data.uptime >= 0
? data.uptime
: null,
lastCheck: new Date().toISOString(),
healthy: true,
healthy: null,
});
} else {
services.push({
@ -392,22 +510,22 @@ export class MonitoringService {
version: 'unknown',
status: 'error',
port: service.port,
uptime: 0,
uptime: null,
lastCheck: new Date().toISOString(),
healthy: false,
error: `HTTP ${response.status}`,
});
}
} catch (error) {
} catch {
services.push({
name: service.name,
version: 'unknown',
status: 'stopped',
port: service.port,
uptime: 0,
uptime: null,
lastCheck: new Date().toISOString(),
healthy: false,
error: error instanceof Error ? error.message : 'Connection failed',
error: 'Service health request unavailable',
});
}
}

View file

@ -14,7 +14,7 @@ export interface CacheStats {
stats?: {
hits: number;
misses: number;
keys: number;
keys: number | null;
evictedKeys?: number;
expiredKeys?: number;
};
@ -26,19 +26,20 @@ export interface QueueStats {
service: string;
queue: string;
connected: boolean;
paused?: boolean;
jobs: {
waiting: number;
active: number;
completed: number;
failed: number;
delayed: number;
paused: number;
paused: number | null;
prioritized?: number;
'waiting-children'?: number;
};
} | null;
workers?: {
count: number;
concurrency: number;
concurrency?: number;
};
throughput?: {
processed: number;
@ -86,7 +87,7 @@ export interface SystemHealth {
export interface MetricSnapshot {
timestamp: string;
value: number;
value: number | null;
unit?: string;
}
@ -102,9 +103,9 @@ export interface ServiceStatus {
version: string;
status: 'running' | 'stopped' | 'error';
port?: number;
uptime: number;
uptime: number | null;
lastCheck: string;
healthy: boolean;
healthy: boolean | null;
error?: string;
}