diff --git a/apps/stock/config/package.json b/apps/stock/config/package.json index e17a21a3..02e84348 100644 --- a/apps/stock/config/package.json +++ b/apps/stock/config/package.json @@ -68,6 +68,10 @@ "./stored-source": { "types": "./dist/contracts/stored-source.d.ts", "default": "./dist/contracts/stored-source.js" + }, + "./diagnostics": { + "types": "./dist/contracts/diagnostics.d.ts", + "default": "./dist/contracts/diagnostics.js" } }, "scripts": { diff --git a/apps/stock/config/src/contracts/diagnostics.ts b/apps/stock/config/src/contracts/diagnostics.ts new file mode 100644 index 00000000..67bca70b --- /dev/null +++ b/apps/stock/config/src/contracts/diagnostics.ts @@ -0,0 +1,72 @@ +/** Read-only operational snapshots, never execution authority or resume tokens. */ +import { z } from 'zod'; +import { canonicalBuildIdentitySchema } from './canonical-research'; +import { paperReadinessSchema } from './paper-deployments'; + +export const researchSlotSchema = z + .object({ + runId: z.string().nullable(), + backtestId: z.string().nullable(), + attemptId: z.string().nullable(), + strategyVersionId: z.string().nullable(), + phase: z.enum(['idle', 'preparing', 'executing', 'persisting']), + }) + .strict(); +export const researchRuntimeSchema = z + .object({ + accepting: z.boolean(), + capacity: z.number().int().positive(), + slots: z.array(researchSlotSchema), + }) + .strict(); +export const paperDiagnosticSchema = paperReadinessSchema + .pick({ + configured: true, + ready: true, + active: true, + connected: true, + operatorHalted: true, + reasons: true, + lastReceivedAt: true, + lastAvailableAt: true, + requiresHistoricalRecovery: true, + }) + .strip(); +export const orchestratorDiagnosticSchema = z + .object({ + service: z.literal('orchestrator'), + observedAt: z.string().datetime(), + research: researchRuntimeSchema.nullable(), + build: canonicalBuildIdentitySchema.nullable(), + // A readable artifact is not proof that a fresh native child can execute it. + nativeExecution: z.literal('unverified-until-run'), + paper: paperDiagnosticSchema.nullable(), + live: z.literal('disabled'), + }) + .strict(); +export const monitoringReadinessSchema = z + .object({ + observedAt: z.string().datetime(), + postgres: z.enum(['connected', 'unavailable']), + queue: z + .object({ + connected: z.boolean(), + workers: z.number().int().nonnegative().nullable(), + paused: z.boolean().nullable(), + }) + .strict(), + leases: z + .array( + z + .object({ runId: z.string(), attemptId: z.string().nullable(), expired: z.boolean() }) + .strict() + ) + .nullable(), + orchestrator: orchestratorDiagnosticSchema.nullable(), + research: z + .object({ status: z.enum(['unavailable', 'unknown']), reasons: z.array(z.string()) }) + .strict(), + live: z.literal('disabled'), + }) + .strict(); +export type MonitoringReadiness = z.infer; diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index e02135e8..49d651eb 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -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 { diff --git a/apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts b/apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts index e7f76cf0..cf1c5d8d 100644 --- a/apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts +++ b/apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts @@ -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 & { getStatus(runId?: string): ReturnType; + getDiagnostics?(): z.infer; }; 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 { if (input === undefined && this.reservations.size === 0) { return { isRunning: false, isPaused: false, progress: 0, currentTime: 0, runId: undefined }; diff --git a/apps/stock/orchestrator/src/routes/create-routes.ts b/apps/stock/orchestrator/src/routes/create-routes.ts index dded6309..cc3a039d 100644 --- a/apps/stock/orchestrator/src/routes/create-routes.ts +++ b/apps/stock/orchestrator/src/routes/create-routes.ts @@ -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 { diff --git a/apps/stock/web-api/src/routes/create-routes.ts b/apps/stock/web-api/src/routes/create-routes.ts index 829a394b..4c6c2a02 100644 --- a/apps/stock/web-api/src/routes/create-routes.ts +++ b/apps/stock/web-api/src/routes/create-routes.ts @@ -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); diff --git a/apps/stock/web-api/src/routes/monitoring.routes.ts b/apps/stock/web-api/src/routes/monitoring.routes.ts index 5053675f..1c4e9b73 100644 --- a/apps/stock/web-api/src/routes/monitoring.routes.ts +++ b/apps/stock/web-api/src/routes/monitoring.routes.ts @@ -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[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 ); diff --git a/apps/stock/web-api/src/services/monitoring.service.ts b/apps/stock/web-api/src/services/monitoring.service.ts index 11dc8371..64a29df3 100644 --- a/apps/stock/web-api/src/services/monitoring.service.ts +++ b/apps/stock/web-api/src/services/monitoring.service.ts @@ -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; + } = {} + ) {} + + /** Explicit prerequisites and unknown execution capability; never a readiness shortcut. */ + async getReadiness(request: Request): Promise { + 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> { - const result: Record> = {}; - 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', }); } } diff --git a/apps/stock/web-api/src/types/monitoring.types.ts b/apps/stock/web-api/src/types/monitoring.types.ts index 3ccb8d21..a391160b 100644 --- a/apps/stock/web-api/src/types/monitoring.types.ts +++ b/apps/stock/web-api/src/types/monitoring.types.ts @@ -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; } diff --git a/apps/stock/web-app/src/features/monitoring/MonitoringPage.tsx b/apps/stock/web-app/src/features/monitoring/MonitoringPage.tsx index 043077e3..eaaba252 100644 --- a/apps/stock/web-app/src/features/monitoring/MonitoringPage.tsx +++ b/apps/stock/web-app/src/features/monitoring/MonitoringPage.tsx @@ -3,13 +3,14 @@ */ import React, { useState } from 'react'; +import { ReadinessCard } from './components/ReadinessCard'; import { CacheStatsCard, DatabaseStatsGrid, ProxyStatsCard, QueueStatsTable, ServiceStatusGrid, - SystemHealthCard + SystemHealthCard, } from './components'; import { useCacheStats, @@ -18,23 +19,51 @@ import { useQueueStats, useServiceStatus, useSystemHealth, - useSystemOverview + useSystemOverview, } from './hooks'; export function MonitoringPage() { const [refreshInterval, setRefreshInterval] = useState(5000); // 5 seconds default const [useOverview, setUseOverview] = useState(false); // Toggle between individual calls and overview - + // Individual API calls - const { data: health, loading: healthLoading, error: healthError } = useSystemHealth(useOverview ? 0 : refreshInterval); - const { data: cache, loading: cacheLoading, error: cacheError } = useCacheStats(useOverview ? 0 : refreshInterval); - const { data: queues, loading: queuesLoading, error: queuesError } = useQueueStats(useOverview ? 0 : refreshInterval); - const { data: databases, loading: dbLoading, error: dbError } = useDatabaseStats(useOverview ? 0 : refreshInterval); - const { data: services, loading: servicesLoading, error: servicesError } = useServiceStatus(useOverview ? 0 : refreshInterval); - const { data: proxies, loading: proxiesLoading, error: proxiesError } = useProxyStats(useOverview ? 0 : refreshInterval); - + const { + data: health, + loading: healthLoading, + error: healthError, + } = useSystemHealth(useOverview ? 0 : refreshInterval); + const { + data: cache, + loading: cacheLoading, + error: cacheError, + } = useCacheStats(useOverview ? 0 : refreshInterval); + const { + data: queues, + loading: queuesLoading, + error: queuesError, + } = useQueueStats(useOverview ? 0 : refreshInterval); + const { + data: databases, + loading: dbLoading, + error: dbError, + } = useDatabaseStats(useOverview ? 0 : refreshInterval); + const { + data: services, + loading: servicesLoading, + error: servicesError, + } = useServiceStatus(useOverview ? 0 : refreshInterval); + const { + data: proxies, + loading: proxiesLoading, + error: proxiesError, + } = useProxyStats(useOverview ? 0 : refreshInterval); + // Combined overview call - const { data: overview, loading: overviewLoading, error: overviewError } = useSystemOverview(useOverview ? refreshInterval : 0); + const { + data: overview, + loading: overviewLoading, + error: overviewError, + } = useSystemOverview(useOverview ? refreshInterval : 0); const handleRefreshIntervalChange = (e: React.ChangeEvent) => { setRefreshInterval(Number(e.target.value)); @@ -52,12 +81,19 @@ export function MonitoringPage() { const displayQueues = useOverview && overview ? overview.health.services.queues : queues; const displayDatabases = useOverview && overview ? overview.health.services.databases : databases; - const isLoading = useOverview - ? overviewLoading - : (healthLoading || cacheLoading || queuesLoading || dbLoading || servicesLoading || proxiesLoading); + const isLoading = useOverview + ? overviewLoading + : healthLoading || + cacheLoading || + queuesLoading || + dbLoading || + servicesLoading || + proxiesLoading; - const errors = useOverview - ? (overviewError ? [overviewError] : []) + const errors = useOverview + ? overviewError + ? [overviewError] + : [] : [healthError, cacheError, queuesError, dbError, servicesError, proxiesError].filter(Boolean); if (isLoading) { @@ -73,44 +109,41 @@ export function MonitoringPage() { return (
+

System Monitoring

-
-
- - -
-
- - -
+
+
+ +
+
+ + +
+
{errors.length > 0 && ( @@ -129,16 +162,20 @@ export function MonitoringPage() {

System Environment

- Node: {overview.environment.nodeVersion} + Node:{' '} + {overview.environment.nodeVersion}
- Platform: {overview.environment.platform} + Platform:{' '} + {overview.environment.platform}
- Architecture: {overview.environment.architecture} + Architecture:{' '} + {overview.environment.architecture}
- Hostname: {overview.environment.hostname} + Hostname:{' '} + {overview.environment.hostname}
@@ -186,4 +223,4 @@ export function MonitoringPage() {
); -} \ No newline at end of file +} diff --git a/apps/stock/web-app/src/features/monitoring/components/CacheStatsCard.tsx b/apps/stock/web-app/src/features/monitoring/components/CacheStatsCard.tsx index 08a64897..8c7ccc45 100644 --- a/apps/stock/web-app/src/features/monitoring/components/CacheStatsCard.tsx +++ b/apps/stock/web-app/src/features/monitoring/components/CacheStatsCard.tsx @@ -2,19 +2,20 @@ * Cache Statistics Card Component */ +import { Card, CardContent, CardHeader } from '@/components/ui/Card'; import type { CacheStats } from '../types'; -import { Card, CardHeader, CardContent } from '@/components/ui/Card'; -import { ConnectionStatus } from './StatusBadge'; import { formatBytes, formatNumber, formatPercentage } from '../utils/formatters'; +import { ConnectionStatus } from './StatusBadge'; interface CacheStatsCardProps { stats: CacheStats; } export function CacheStatsCard({ stats }: CacheStatsCardProps) { - const hitRate = stats.stats && (stats.stats.hits + stats.stats.misses) > 0 - ? (stats.stats.hits / (stats.stats.hits + stats.stats.misses) * 100) - : 0; + const hitRate = + stats.stats && stats.stats.hits + stats.stats.misses > 0 + ? (stats.stats.hits / (stats.stats.hits + stats.stats.misses)) * 100 + : null; return ( @@ -32,11 +33,15 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
Memory Used
-
{formatBytes(stats.memoryUsage.used)}
+
+ {formatBytes(stats.memoryUsage.used)} +
Peak Memory
-
{formatBytes(stats.memoryUsage.peak)}
+
+ {formatBytes(stats.memoryUsage.peak)} +
)} @@ -46,29 +51,41 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
Hit Rate
-
{formatPercentage(hitRate)}
+
+ {formatPercentage(hitRate)} +
Total Keys
-
{formatNumber(stats.stats.keys)}
+
+ {formatNumber(stats.stats.keys)} +
- Hits: {formatNumber(stats.stats.hits)} + Hits:{' '} + {formatNumber(stats.stats.hits)}
- Misses: {formatNumber(stats.stats.misses)} + Misses:{' '} + {formatNumber(stats.stats.misses)}
{stats.stats.evictedKeys !== undefined && (
- Evicted: {formatNumber(stats.stats.evictedKeys)} + Evicted:{' '} + + {formatNumber(stats.stats.evictedKeys)} +
)} {stats.stats.expiredKeys !== undefined && (
- Expired: {formatNumber(stats.stats.expiredKeys)} + Expired:{' '} + + {formatNumber(stats.stats.expiredKeys)} +
)}
@@ -82,11 +99,9 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) { )} ) : ( -
- Cache service is not available -
+
Cache service is not available
)}
); -} \ No newline at end of file +} diff --git a/apps/stock/web-app/src/features/monitoring/components/QueueStatsTable.tsx b/apps/stock/web-app/src/features/monitoring/components/QueueStatsTable.tsx index cae7638f..2cea7896 100644 --- a/apps/stock/web-app/src/features/monitoring/components/QueueStatsTable.tsx +++ b/apps/stock/web-app/src/features/monitoring/components/QueueStatsTable.tsx @@ -2,28 +2,22 @@ * Queue Statistics Table Component */ -import type { QueueStats } from '../types'; -import { Card, CardHeader, CardContent } from '@/components/ui/Card'; -import { formatNumber } from '../utils/formatters'; +import { Card, CardContent, CardHeader } from '@/components/ui/Card'; import { cn } from '@/lib/utils'; +import type { QueueStats } from '../types'; +import { formatNumber } from '../utils/formatters'; interface QueueStatsTableProps { queues: QueueStats[]; } export function QueueStatsTable({ queues }: QueueStatsTableProps) { - const totalJobs = (queue: QueueStats) => { - const { jobs } = queue; - return jobs.waiting + jobs.active + jobs.completed + jobs.failed + jobs.delayed + jobs.paused + - (jobs.prioritized || 0) + (jobs['waiting-children'] || 0); - }; - return (

Queue Statistics

- + {queues.length > 0 ? (
@@ -35,61 +29,94 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) { Status Waiting Active - Completed + + Completed + Failed Delayed - Prioritized + + Prioritized + Children Workers - Total - {queues.map((queue) => ( - + {queues.map(queue => ( + {queue.service} {queue.queue} - - - {formatNumber(queue.jobs.waiting)} - - {queue.jobs.active > 0 ? ( - {formatNumber(queue.jobs.active)} - ) : ( - {queue.jobs.active} - )} - - {formatNumber(queue.jobs.completed)} - - {queue.jobs.failed > 0 ? ( - {formatNumber(queue.jobs.failed)} - ) : ( - {queue.jobs.failed} - )} - - {formatNumber(queue.jobs.delayed)} - - {queue.jobs.prioritized && queue.jobs.prioritized > 0 ? ( - {formatNumber(queue.jobs.prioritized)} - ) : ( - 0 - )} - - - {queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? ( - {formatNumber(queue.jobs['waiting-children'])} - ) : ( - 0 - )} + + {!queue.jobs ? ( + + Unknown — queue unavailable + + ) : ( + <> + + {formatNumber(queue.jobs.waiting)} + + + {queue.jobs.active > 0 ? ( + + {formatNumber(queue.jobs.active)} + + ) : ( + {queue.jobs.active} + )} + + + {formatNumber(queue.jobs.completed)} + + + {queue.jobs.failed > 0 ? ( + + {formatNumber(queue.jobs.failed)} + + ) : ( + {queue.jobs.failed} + )} + + + {formatNumber(queue.jobs.delayed)} + + + {queue.jobs.prioritized && queue.jobs.prioritized > 0 ? ( + + {formatNumber(queue.jobs.prioritized)} + + ) : ( + + {formatNumber(queue.jobs.prioritized)} + + )} + + + {queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? ( + + {formatNumber(queue.jobs['waiting-children'])} + + ) : ( + + {formatNumber(queue.jobs['waiting-children'])} + + )} + + + )} - {queue.workers ? `${queue.workers.count}/${queue.workers.concurrency}` : '-'} + {queue.workers ? formatNumber(queue.workers.count) : 'Unknown'} - {formatNumber(totalJobs(queue))} ))} @@ -103,4 +130,4 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) { ); -} \ No newline at end of file +} diff --git a/apps/stock/web-app/src/features/monitoring/components/ReadinessCard.tsx b/apps/stock/web-app/src/features/monitoring/components/ReadinessCard.tsx new file mode 100644 index 00000000..0099b948 --- /dev/null +++ b/apps/stock/web-app/src/features/monitoring/components/ReadinessCard.tsx @@ -0,0 +1,122 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import type { MonitoringReadiness } from '@stock-bot/stock-config/diagnostics'; +import { Card, CardContent, CardHeader } from '@/components/ui/Card'; +import { monitoringApi } from '../services/monitoringApi'; + +/** Explicit refresh: never turn an older successful snapshot into current readiness. */ +export function ReadinessCard() { + const [data, setData] = useState(null); + const [error, setError] = useState(false); + const [loading, setLoading] = useState(true); + const active = useRef(null); + const refresh = useCallback(async () => { + active.current?.abort(); + const request = new AbortController(); + active.current = request; + setLoading(true); + setError(false); + setData(null); + try { + const snapshot = await monitoringApi.getReadiness(request.signal); + if (active.current === request && !request.signal.aborted) { + setData(snapshot); + } + } catch { + if (active.current === request && !request.signal.aborted) { + setError(true); + } + } finally { + if (active.current === request && !request.signal.aborted) { + setLoading(false); + } + } + }, []); + useEffect(() => { + void refresh(); + return () => { + active.current?.abort(); + active.current = null; + }; + }, [refresh]); + const paper = data?.orchestrator?.paper; + return ( + + +

Research and paper diagnostics

+
+ +

+ This is a point-in-time snapshot. A responding HTTP service does not prove native + execution readiness. +

+ + {error && ( +

Readiness diagnostics unavailable. Retry to obtain a new snapshot.

+ )} + {data && ( + <> +

Observed: {data.observedAt}

+

+ Research: {data.research.status}. PostgreSQL: {data.postgres}. Workers:{' '} + {data.queue.workers ?? 'Unknown'}. +

+
    + {data.research.reasons.map(reason => ( +
  • {reason}
  • + ))} +
+

+ Native build: {data.orchestrator?.build?.engineBinarySha256 ?? 'Unknown'}. Native + execution: unverified until run start. +

+

+ Paper:{' '} + {paper + ? paper.ready + ? 'Ready for operator review' + : 'Not ready' + : 'Unknown or not configured'} + . +

+ {paper && ( + <> +

+ Feed connected: {String(paper.connected)}. Last received:{' '} + {paper.lastReceivedAt === null + ? 'Unknown' + : new Date(paper.lastReceivedAt).toISOString()} + . +

+

+ Active: {String(paper.active)}. Operator halted: {String(paper.operatorHalted)}. + Historical recovery required: {String(paper.requiresHistoricalRecovery)}. +

+
    + {paper.reasons.map(reason => ( +
  • {reason}
  • + ))} +
+ + )} +

Live trading: disabled.

+ {data.orchestrator?.research?.slots.map((slot, index) => ( +

+ Slot {index + 1}: {slot.phase}. Run {slot.runId ?? 'none'}; attempt{' '} + {slot.attemptId ?? 'none'}; strategy version {slot.strategyVersionId ?? 'none'}. +

+ ))} + {data.leases?.map(lease => ( +

+ SQL attempt {lease.attemptId ?? 'unknown'} for run {lease.runId}:{' '} + {lease.expired ? 'expired; recovery required' : 'lease current'}. +

+ ))} + + )} + Open deployment-specific paper readiness and recovery +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/monitoring/components/ServiceCard.tsx b/apps/stock/web-app/src/features/monitoring/components/ServiceCard.tsx index 08e286b0..41f5f552 100644 --- a/apps/stock/web-app/src/features/monitoring/components/ServiceCard.tsx +++ b/apps/stock/web-app/src/features/monitoring/components/ServiceCard.tsx @@ -1,56 +1,60 @@ -import { Card, CardHeader, CardContent } from '@/components/ui/Card'; -import { ServiceStatusIndicator, HealthStatus } from './StatusBadge'; -import { formatUptime } from '../utils/formatters'; -import type { ServiceStatus } from '../types'; - -interface ServiceCardProps { - service: ServiceStatus; -} - -export function ServiceCard({ service }: ServiceCardProps) { - return ( - - -
-

- {service.name.replace(/-/g, ' ')} -

- -
-
- - -
- Status: - {service.status} -
- -
- Port: - {service.port || 'N/A'} -
- -
- Version: - {service.version} -
- -
- Uptime: - {formatUptime(service.uptime)} -
- -
- Health: - -
- - {service.error && ( -
- Error: {service.error} -
- )} -
-
- ); -} \ No newline at end of file +import { Card, CardContent, CardHeader } from '@/components/ui/Card'; +import type { ServiceStatus } from '../types'; +import { formatUptime } from '../utils/formatters'; +import { HealthStatus, ServiceStatusIndicator } from './StatusBadge'; + +interface ServiceCardProps { + service: ServiceStatus; +} + +export function ServiceCard({ service }: ServiceCardProps) { + return ( + + +
+

+ {service.name.replace(/-/g, ' ')} +

+ +
+
+ + +
+ Status: + {service.status} +
+ +
+ Port: + {service.port || 'N/A'} +
+ +
+ Version: + {service.version} +
+ +
+ Uptime: + {formatUptime(service.uptime)} +
+ +
+ Health: + {service.healthy === null ? ( + Unknown (liveness only) + ) : ( + + )} +
+ + {service.error && ( +
+ Error: {service.error} +
+ )} +
+
+ ); +} diff --git a/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts b/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts index 51bd6e38..100480f1 100644 --- a/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts +++ b/apps/stock/web-app/src/features/monitoring/services/monitoringApi.ts @@ -1,3 +1,7 @@ +import { + monitoringReadinessSchema, + type MonitoringReadiness, +} from '@stock-bot/stock-config/diagnostics'; import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; /** * Monitoring API Service @@ -16,15 +20,38 @@ import type { const MONITORING_BASE = `${API_BASE_URL}/api/system/monitoring`; export const monitoringApi = { + async getReadiness(signal?: AbortSignal): Promise { + const response = await fetch(`${MONITORING_BASE}/readiness`, { signal }); + if (!response.ok) { + throw new Error('Readiness diagnostics unavailable'); + } + return monitoringReadinessSchema.parse(await response.json()); + }, /** * Get overall system health */ async getSystemHealth(): Promise { const response = await fetch(MONITORING_BASE); - if (!response.ok) { - throw new Error(`Failed to fetch system health: ${response.statusText}`); + const body = await response.json(); + if ( + !response.ok && + !( + [500, 503].includes(response.status) && + ['degraded', 'unhealthy'].includes(body?.status) && + typeof body?.timestamp === 'string' && + typeof body?.uptime === 'number' && + typeof body?.memory?.used === 'number' && + typeof body?.memory?.total === 'number' && + typeof body?.memory?.percentage === 'number' && + body?.services?.cache && + Array.isArray(body?.services?.queues) && + Array.isArray(body?.services?.databases) && + Array.isArray(body?.errors) + ) + ) { + throw new Error('System health unavailable'); } - return response.json(); + return body; }, /** diff --git a/apps/stock/web-app/src/features/monitoring/types/index.ts b/apps/stock/web-app/src/features/monitoring/types/index.ts index 4b4e1da6..448cbfa6 100644 --- a/apps/stock/web-app/src/features/monitoring/types/index.ts +++ b/apps/stock/web-app/src/features/monitoring/types/index.ts @@ -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; @@ -98,9 +99,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; } diff --git a/apps/stock/web-app/src/features/monitoring/utils/formatters.ts b/apps/stock/web-app/src/features/monitoring/utils/formatters.ts index 631ae6c0..f1720eed 100644 --- a/apps/stock/web-app/src/features/monitoring/utils/formatters.ts +++ b/apps/stock/web-app/src/features/monitoring/utils/formatters.ts @@ -2,7 +2,10 @@ * Common formatting utilities for monitoring components */ -export function formatUptime(ms: number): string { +export function formatUptime(ms: number | null): string { + if (ms === null) { + return 'Unknown'; + } const seconds = Math.floor(ms / 1000); const minutes = Math.floor(seconds / 60); const hours = Math.floor(minutes / 60); @@ -39,10 +42,13 @@ export function formatBytes(bytes: number): string { return bytes + ' B'; } -export function formatNumber(num: number): string { - return num.toLocaleString(); +export function formatNumber(num: number | null | undefined): string { + return num === null || num === undefined ? 'Unknown' : num.toLocaleString(); } -export function formatPercentage(value: number, decimals: number = 1): string { +export function formatPercentage(value: number | null, decimals: number = 1): string { + if (value === null) { + return 'Unknown'; + } return `${value.toFixed(decimals)}%`; } diff --git a/libs/core/logger/src/index.ts b/libs/core/logger/src/index.ts index 56b421e5..b19ecb7f 100644 --- a/libs/core/logger/src/index.ts +++ b/libs/core/logger/src/index.ts @@ -9,3 +9,6 @@ export { Logger, getLogger, shutdownLoggers, setLoggerConfig } from './logger'; // Type definitions export type { LogLevel, LogContext, LogMetadata, LoggerConfig, LoggerLike } from './types'; + +// Shared redaction for durable user-visible diagnostics as well as logs. +export { redactLogValue } from './redact'; diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index a6bc7400..54465970 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -569,7 +569,7 @@ export class Queue { /** * Get count of active workers from BullMQ */ - async getActiveWorkerCount(): Promise { + async getActiveWorkerCount(): Promise { try { const workers = await this.bullQueue.getWorkers(); return workers.length; @@ -578,7 +578,9 @@ export class Queue { queueName: this.queueName, error, }); - return 0; + // The optional QueueStats.workers capability distinguishes an unavailable + // observation from a successful query that found zero workers. + return undefined; } } diff --git a/test/e2e/fixture.ts b/test/e2e/fixture.ts index c34d41a2..e1736519 100644 --- a/test/e2e/fixture.ts +++ b/test/e2e/fixture.ts @@ -437,7 +437,21 @@ export async function fixture(browser: Browser, native = false) { return (async () => { if (pathname.startsWith('/api/')) { if ( - (!pathname.startsWith('/api/v2/backtests') && + (!( + request.method === 'GET' && + [ + '/api/system/monitoring', + '/api/system/monitoring/', + '/api/system/monitoring/readiness', + '/api/system/monitoring/cache', + '/api/system/monitoring/queues', + '/api/system/monitoring/databases', + '/api/system/monitoring/services', + '/api/system/monitoring/proxies', + '/api/system/monitoring/overview', + ].includes(pathname) + ) && + !pathname.startsWith('/api/v2/backtests') && !pathname.startsWith('/api/v2/runs') && !pathname.startsWith('/api/v2/datasets') && !pathname.startsWith('/api/v2/strategies') && diff --git a/test/e2e/workbench.test.ts b/test/e2e/workbench.test.ts index 63de6aa0..b962919c 100644 --- a/test/e2e/workbench.test.ts +++ b/test/e2e/workbench.test.ts @@ -1924,11 +1924,17 @@ test('browser_cancel_failure', async () => { f.controlled.mode = 'fail'; await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click(); await createCanonicalInBrowser(f, 'Failed browser run', true); - await visible(f.page, 'Run failed: Injected fixture worker failure'); + await visible( + f.page, + 'Run failed: Backtest failed during executing: Injected fixture worker failure' + ); const failedId = f.page.url().split('/').at(-1)!; expect( (await f.pool.query('SELECT status,error FROM runs WHERE id=$1', [failedId])).rows[0] - ).toEqual({ status: 'failed', error: 'Injected fixture worker failure' }); + ).toEqual({ + status: 'failed', + error: 'Backtest failed during executing: Injected fixture worker failure', + }); expect( (await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [failedId])).rowCount ).toBe(0); @@ -4874,3 +4880,34 @@ test('isolated_candidate_publication_research_validation_and_reviewed_paper_hist await f.close(); } }, 180000); + +test('monitoring shows unavailable research evidence and retries without retaining stale readiness', async () => { + const f = await fixture(); + try { + await f.login(); + await f.page.goto(`${f.origin}/system/monitoring`); + await visible(f.page, 'Research and paper diagnostics'); + await visible(f.page, /Workers: Unknown/); + await visible(f.page, /Native execution: unverified until run start/); + await visible(f.page, 'Live trading: disabled.'); + await visible(f.page, /Open deployment-specific paper readiness and recovery/); + expect(await f.page.getByText('Observed:', { exact: false }).count()).toBe(1); + await f.page.route('**/api/system/monitoring/readiness', route => + route.fulfill({ + status: 503, + contentType: 'application/json', + body: '{"error":"fixture unavailable"}', + }) + ); + await f.page.getByRole('button', { name: 'Refresh readiness', exact: true }).click(); + await visible(f.page, 'Readiness diagnostics unavailable. Retry to obtain a new snapshot.'); + expect(await f.page.getByText('Observed:', { exact: false }).count()).toBe(0); + await f.page.unroute('**/api/system/monitoring/readiness'); + await f.page.getByRole('button', { name: 'Refresh readiness', exact: true }).click(); + await visible(f.page, /Workers: Unknown/); + expect(await f.page.getByText('Observed:', { exact: false }).count()).toBe(1); + expect(f.unexpectedNetwork).toEqual([]); + } finally { + await f.close(); + } +}, 60000); diff --git a/test/integration/monitoring-readiness-ui.test.tsx b/test/integration/monitoring-readiness-ui.test.tsx new file mode 100644 index 00000000..de94d682 --- /dev/null +++ b/test/integration/monitoring-readiness-ui.test.tsx @@ -0,0 +1,168 @@ +import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from 'bun:test'; +import { GlobalWindow } from 'happy-dom'; +import { act, createElement } from 'react'; +import type { Root } from 'react-dom/client'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { monitoringReadinessSchema } from '@stock-bot/stock-config/diagnostics'; +import { CacheStatsCard } from '../../apps/stock/web-app/src/features/monitoring/components/CacheStatsCard'; +import { QueueStatsTable } from '../../apps/stock/web-app/src/features/monitoring/components/QueueStatsTable'; + +const browser = new GlobalWindow({ url: 'http://localhost:5173' }); +const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const; +const previous = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); +let createRoot: typeof import('react-dom/client').createRoot; +let Card: typeof import('../../apps/stock/web-app/src/features/monitoring/components/ReadinessCard').ReadinessCard; +let api: typeof import('../../apps/stock/web-app/src/features/monitoring/services/monitoringApi').monitoringApi; +let root: Root | undefined, host: HTMLDivElement; +const requests: { resolve: (response: Response) => void; signal: AbortSignal | undefined }[] = []; +const snapshot = () => + monitoringReadinessSchema.parse({ + observedAt: '2026-10-28T00:00:00.000Z', + postgres: 'unavailable', + queue: { connected: false, workers: null, paused: null }, + leases: null, + orchestrator: null, + research: { status: 'unavailable', reasons: ['Research PostgreSQL unavailable'] }, + live: 'disabled', + }); +async function flush(action: () => void = () => {}) { + await act(async () => { + action(); + await Promise.resolve(); + }); +} +function refresh() { + const button = host.querySelector('button')!; + button.click(); +} +beforeAll(async () => { + Object.defineProperty(globalThis, 'window', { configurable: true, value: browser }); + Object.defineProperty(globalThis, 'document', { configurable: true, value: browser.document }); + Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { + configurable: true, + value: true, + }); + ({ createRoot } = await import('react-dom/client')); + ({ ReadinessCard: Card } = await import( + '../../apps/stock/web-app/src/features/monitoring/components/ReadinessCard' + )); + ({ monitoringApi: api } = await import( + '../../apps/stock/web-app/src/features/monitoring/services/monitoringApi' + )); +}); +beforeEach(() => { + requests.length = 0; + browser.fetch = ((_input: unknown, init?: RequestInit) => + new Promise(resolve => + requests.push({ resolve, signal: init?.signal ?? undefined }) + )) as unknown as typeof browser.fetch; + const element = browser.document.createElement('div'); + browser.document.body.append(element); + host = element as unknown as HTMLDivElement; + root = createRoot(host); +}); +afterEach(async () => { + await flush(() => root?.unmount()); + root = undefined; + host.remove(); +}); +afterAll(() => { + for (const key of keys) { + const descriptor = previous.get(key); + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + browser.happyDOM.abort(); +}); + +test('unknown cache and queue readings never render fabricated zero totals', () => { + const cache = renderToStaticMarkup( + createElement(CacheStatsCard, { + stats: { provider: 'dragonfly', connected: true, stats: { hits: 0, misses: 0, keys: null } }, + }) + ); + expect(cache).toContain('Unknown'); + expect(cache).not.toContain('0.0%'); + const queues = renderToStaticMarkup( + createElement(QueueStatsTable, { + queues: [ + { + name: 'research', + service: 'orchestrator', + queue: 'research', + connected: false, + jobs: null, + }, + ], + }) + ); + expect(queues).toContain('Unknown'); + expect(queues).toContain('queue unavailable'); + expect(queues).not.toContain('>Total<'); + const zero = renderToStaticMarkup( + createElement(QueueStatsTable, { + queues: [ + { + name: 'research', + service: 'orchestrator', + queue: 'research', + connected: true, + jobs: { waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, paused: 0 }, + workers: { count: 0 }, + }, + ], + }) + ); + expect(zero).toContain('>0<'); + expect(zero).toContain('Unknown'); +}); + +test('readiness loading, unavailable, error and retry states keep older success out of the current snapshot', async () => { + await flush(() => root!.render(createElement(Card))); + expect(host.textContent).toContain('Checking readiness'); + await flush(() => requests[0]!.resolve(Response.json(snapshot()))); + expect(host.textContent).toContain('Workers: Unknown'); + expect(host.textContent).toContain('Research PostgreSQL unavailable'); + expect(host.textContent).toContain('Live trading: disabled'); + await flush(refresh); + expect(host.textContent).not.toContain('Observed:'); + await flush(() => requests[1]!.resolve(Response.json({ error: 'offline' }, { status: 503 }))); + expect(host.textContent).toContain('Readiness diagnostics unavailable'); + await flush(refresh); + await flush(() => requests[2]!.resolve(Response.json(snapshot()))); + expect(host.textContent).toContain('Observed:'); + expect(host.textContent).not.toContain('Readiness diagnostics unavailable'); +}); + +test('unmounted requests are aborted and cannot replace a new view', async () => { + await flush(() => root!.render(createElement(Card))); + const first = requests[0]!; + await flush(() => root!.render(createElement('div', {}, 'Different view'))); + expect(first.signal?.aborted).toBe(true); + await flush(() => first.resolve(Response.json(snapshot()))); + expect(host.textContent).toBe('Different view'); +}); + +test('malformed readiness fails closed; structured degraded health remains inspectable', async () => { + const bad = api.getReadiness(); + requests[0]!.resolve(Response.json({ status: 'healthy' })); + await expect(bad).rejects.toThrow(); + const health = api.getSystemHealth(); + requests[1]!.resolve( + Response.json( + { + status: 'degraded', + timestamp: '2026-10-28T00:00:00.000Z', + uptime: 0, + memory: { used: 0, total: 1, percentage: 0 }, + services: { cache: {}, queues: [], databases: [] }, + errors: ['Database unavailable'], + }, + { status: 503 } + ) + ); + expect((await health).status).toBe('degraded'); + const unavailable = api.getSystemHealth(); + requests[2]!.resolve(Response.json({ error: 'offline' }, { status: 503 })); + await expect(unavailable).rejects.toThrow('System health unavailable'); +}); diff --git a/test/integration/monitoring-readiness.test.ts b/test/integration/monitoring-readiness.test.ts new file mode 100644 index 00000000..59b7e374 --- /dev/null +++ b/test/integration/monitoring-readiness.test.ts @@ -0,0 +1,333 @@ +import { expect, mock, test } from 'bun:test'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { orchestratorDiagnosticSchema } from '@stock-bot/stock-config/diagnostics'; +import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; +import { createRoutes } from '../../apps/stock/orchestrator/src/routes/create-routes'; +import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; +import { createMonitoringRoutes } from '../../apps/stock/web-api/src/routes/monitoring.routes'; +import { MonitoringService } from '../../apps/stock/web-api/src/services/monitoring.service'; +import { Queue } from '../../libs/core/queue/src/queue'; +import { canonicalRunnerFixture, deferred } from '../fixtures/canonical-runner'; + +const diagnostic = () => + orchestratorDiagnosticSchema.parse({ + service: 'orchestrator', + observedAt: '2026-10-28T00:00:00.000Z', + research: { + accepting: true, + capacity: 1, + slots: [ + { runId: null, backtestId: null, attemptId: null, strategyVersionId: null, phase: 'idle' }, + ], + }, + build: { + version: 1, + workerSha256: 'a'.repeat(64), + engineWrapperSha256: 'b'.repeat(64), + engineBinarySha256: 'c'.repeat(64), + dependencyLockSha256: 'd'.repeat(64), + runtime: 'bun', + runtimeVersion: 'fixture', + platform: 'linux', + arch: 'x64', + }, + nativeExecution: 'unverified-until-run', + paper: { + configured: true, + ready: false, + active: false, + connected: false, + operatorHalted: true, + reasons: ['stale-feed'], + lastReceivedAt: 1000, + lastAvailableAt: 1000, + requiresHistoricalRecovery: true, + }, + live: 'disabled', + }); +function fixture() { + const queues: { name: string; workers?: number }[] = []; + const snapshot = { + waiting: 0, + active: 0, + completed: 0, + failed: 0, + delayed: 0, + paused: false, + workers: 1, + }; + const rows: { run_id: string; attempt_id: string | null; expired: boolean }[] = []; + const db = { query: mock(async () => ({ rows })) }; + const cache = { isReady: () => true, getStats: () => ({ hits: 0, misses: 0, uptime: 0 }) }; + const manager = { + getQueue(name: string, options?: { workers?: number }) { + queues.push({ name, workers: options?.workers }); + return { getStats: async () => snapshot }; + }, + }; + const container = { postgres: db, queueManager: manager, cache } as unknown as IServiceContainer; + return { container, queues, snapshot, rows, db }; +} +const request = () => + new Request('http://web/api/system/monitoring/readiness', { + headers: { + authorization: 'Bearer fixture-auth', + cookie: 'session=fixture', + origin: 'http://web', + }, + }); + +test('dependency_unavailable_readiness never turns liveness or readable artifacts into financial readiness', async () => { + const f = fixture(); + const service = new MonitoringService(f.container, { + origin: 'http://orchestrator:2004', + request: async (url, init) => { + expect(url.pathname).toBe('/api/diagnostics'); + expect(init.redirect).toBe('error'); + expect(new Headers(init.headers).get('authorization')).toBe('Bearer fixture-auth'); + expect(new Headers(init.headers).get('cookie')).toBe('session=fixture'); + return Response.json(diagnostic()); + }, + }); + const result = await service.getReadiness(request()); + expect(result.research.status).toBe('unknown'); + expect(result.queue.workers).toBe(1); + expect(result.orchestrator?.nativeExecution).toBe('unverified-until-run'); + expect(result.live).toBe('disabled'); + expect(f.queues).toEqual([{ name: '{orchestrator_orchestrator}', workers: 0 }]); + f.snapshot.workers = 0; + expect((await service.getReadiness(request())).research.status).toBe('unavailable'); + f.snapshot.workers = 1; + f.snapshot.paused = true; + expect((await service.getReadiness(request())).research.reasons).toContain( + 'Research queue paused' + ); + const absent = await new MonitoringService({} as IServiceContainer).getReadiness(request()); + expect(absent.research.status).toBe('unavailable'); + expect(absent.queue.workers).toBeNull(); + expect(absent.leases).toBeNull(); + expect(absent.orchestrator).toBeNull(); +}); + +test('stale_feed_status and expired SQL leases remain explicit alongside local attempt diagnostics', async () => { + const f = fixture(); + f.rows.push({ run_id: 'run-1', attempt_id: 'attempt-1', expired: true }); + const upstream = diagnostic(); + upstream.research!.slots[0] = { + runId: 'run-1', + backtestId: 'backtest-1', + attemptId: 'attempt-1', + strategyVersionId: 'version-1', + phase: 'executing', + }; + const result = await new MonitoringService(f.container, { + origin: 'http://orchestrator', + request: async () => Response.json(upstream), + }).getReadiness(request()); + expect(result.orchestrator?.paper?.ready).toBe(false); + expect(result.orchestrator?.paper?.reasons).toEqual(['stale-feed']); + expect(result.orchestrator?.paper?.requiresHistoricalRecovery).toBe(true); + expect(result.leases).toEqual([{ runId: 'run-1', attemptId: 'attempt-1', expired: true }]); + expect(result.research.reasons).toContain('Expired research attempts require durable recovery'); + expect(result.orchestrator?.research?.slots[0]?.phase).toBe('executing'); +}); + +test('invalid, unavailable or shutting-down upstreams cannot become available and do not echo secrets', async () => { + const f = fixture(); + const secret = 'https://user:fixture-private-value@host/?token=fixture-private-value'; + const broken = new MonitoringService(f.container, { + origin: 'http://orchestrator', + request: async () => { + throw new Error(secret); + }, + }); + expect(JSON.stringify(await broken.getReadiness(request()))).not.toContain( + 'fixture-private-value' + ); + for (const value of [ + { status: 'healthy' }, + { ...diagnostic(), build: null }, + { ...diagnostic(), research: null }, + { ...diagnostic(), research: { ...diagnostic().research, accepting: false } }, + ]) { + const result = await new MonitoringService(f.container, { + origin: 'http://orchestrator', + request: async () => Response.json(value), + }).getReadiness(request()); + expect(result.research.status).toBe('unavailable'); + } + const fetcher = mock(async () => Response.json(diagnostic())); + for (const origin of [ + 'file:///tmp/example', + 'http://user:pass@host', + 'http://host/other', + 'http://host?token=x', + ]) { + await new MonitoringService(f.container, { origin, request: fetcher }).getReadiness(request()); + } + expect(fetcher).not.toHaveBeenCalled(); + const response = await createMonitoringRoutes(f.container, { + origin: 'http://orchestrator', + request: async () => Response.json(diagnostic()), + }).request('/readiness'); + expect(response.status).toBe(200); + expect(response.headers.get('cache-control')).toBe('no-store'); +}); + +test('unknown measurements differ from observed zero and missing required infrastructure degrades health', async () => { + const f = fixture(); + const service = new MonitoringService(f.container); + expect((await service.getCacheStats()).stats).toEqual({ hits: 0, misses: 0, keys: null }); + expect((await service.getServiceMetrics()).errorRate.value).toBeNull(); + const queues = await service.getQueueStats(); + expect(queues.some(q => q.service === 'orchestrator')).toBe(true); + expect(queues[0]?.jobs?.active).toBe(0); + expect(queues[0]?.jobs?.paused).toBeNull(); + expect(queues[0]?.paused).toBe(false); + expect(queues[0]?.workers?.concurrency).toBeUndefined(); + const broken = new MonitoringService({ + queueManager: { + getQueue() { + throw new Error('offline'); + }, + }, + } as unknown as IServiceContainer); + expect((await broken.getQueueStats())[0]?.jobs).toBeNull(); + expect((await new MonitoringService({} as IServiceContainer).getSystemHealth()).status).not.toBe( + 'healthy' + ); +}); + +test('orchestrator diagnostics read existing paper status without activating, feeding or recovering it', async () => { + const status = mock(async () => ({ + ...diagnostic().paper, + accountId: null, + sourceId: null, + pendingInput: null, + pendingBatch: null, + pendingDecisionSequence: null, + nativeStatus: null, + risk: null, + })); + const activate = mock(async () => { + throw new Error('must not activate'); + }); + const services = { + logger: { info() {}, debug() {}, error() {} }, + custom: { BacktestRunner: {}, CanonicalPaperRuntime: { status, activate } }, + } as unknown as OrchestratorServices; + const response = await createRoutes(services).request('/api/diagnostics'); + expect(response.status).toBe(200); + const body = orchestratorDiagnosticSchema.parse(await response.json()); + expect(body.paper?.ready).toBe(false); + expect(body.research).toBeNull(); + expect(body.nativeExecution).toBe('unverified-until-run'); + expect(body.live).toBe('disabled'); + expect(status).toHaveBeenCalledTimes(1); + expect(activate).not.toHaveBeenCalled(); +}); + +test('failed_attempt_diagnostics preserve actual phase and ownership while redacting durable causes', async () => { + const f = canonicalRunnerFixture(), + entered = deferred(), + exit = deferred(); + let observed: Error | undefined; + f.runner.on('error', error => { + observed = error; + }); + let failure: { runId: string; attemptId: string; message: string } | undefined; + f.repo.fail = async (runId, message, attemptId) => { + failure = { runId, message, attemptId }; + }; + f.engine.runCanonical = async () => { + entered.resolve(); + return exit.promise; + }; + const execution = f.runner.runQueued(f.request.runId).catch(error => error); + await entered.promise; + expect(f.runner.getAttemptDiagnostics()).toMatchObject({ + runId: f.request.runId, + attemptId: 'attempt', + strategyVersionId: f.request.strategy.versionId, + phase: 'executing', + }); + exit.reject( + new Error( + 'Dataset unavailable at postgres://fixture:private-password@host/?token=private-token; Bearer private-bearer' + ) + ); + await execution; + expect(failure?.runId).toBe(f.request.runId); + expect(failure?.attemptId).toBe('attempt'); + expect(failure?.message).toContain('Backtest failed during executing: Dataset unavailable'); + expect(failure?.message).not.toContain('private-password'); + expect(failure?.message).not.toContain('private-token'); + expect(failure?.message).not.toContain('private-bearer'); + expect(String(observed?.message)).toBe(String(failure?.message)); + expect(String(observed)).not.toContain('private-password'); + expect(f.runner.getAttemptDiagnostics().phase).toBe('idle'); + expect(f.runner.getAttemptDiagnostics().attemptId).toBeNull(); + await f.runner.shutdown(); +}); + +test('worker count inspection failure is unknown at the queue adapter boundary, not a measured zero', async () => { + const empty = async () => []; + let workers: unknown[] | undefined; + const bull = { + getWaiting: empty, + getActive: empty, + getCompleted: empty, + getFailed: empty, + getDelayed: empty, + isPaused: async () => false, + getWorkers: async () => { + if (workers === undefined) throw new Error('worker inspection unavailable'); + return workers; + }, + }; + // Exercise the real adapter methods without constructing external Redis connections. + const queue = Object.create(Queue.prototype) as Queue; + Object.defineProperties(queue, { + bullQueue: { value: bull }, + logger: { value: { error() {} } }, + queueName: { value: 'fixture' }, + }); + expect((await queue.getStats()).workers).toBeUndefined(); + workers = []; + expect((await queue.getStats()).workers).toBe(0); + workers = [{}, {}]; + expect((await queue.getStats()).workers).toBe(2); +}); + +test('failed cancellation persistence reports its actual cause rather than the earlier cancellation', async () => { + const f = canonicalRunnerFixture(), + entered = deferred(), + exit = deferred(); + let observed = ''; + f.runner.on('error', error => { + observed = String(error); + }); + f.engine.runCanonical = async () => { + entered.resolve(); + return exit.promise; + }; + f.engine.stopBacktest = async () => { + exit.reject(new BacktestCancelledError()); + }; + f.repo.cancel = async () => { + throw new Error( + 'Cancellation persistence unavailable postgres://fixture:private-password@host' + ); + }; + const execution = f.runner.runQueued(f.request.runId).catch(error => error); + await entered.promise; + await expect(f.runner.stopBacktest(f.request.runId)).rejects.toThrow( + 'Cancellation persistence unavailable' + ); + await execution; + expect(observed).toContain( + 'Backtest failed during executing: Cancellation persistence unavailable' + ); + expect(observed).not.toContain('private-password'); + await f.runner.shutdown(); +});