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

@ -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": {

View file

@ -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<typeof monitoringReadinessSchema>;

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 {

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;
}

View file

@ -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<HTMLSelectElement>) => {
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 (
<div className="flex flex-col h-full space-y-4">
<ReadinessCard />
<div className="flex items-center justify-between flex-shrink-0">
<div>
<h1 className="text-lg font-bold text-text-primary mb-2">System Monitoring</h1>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<label className="text-sm text-text-secondary">
Data source:
</label>
<button
onClick={handleDataSourceToggle}
className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
useOverview
? 'bg-primary-600 text-white'
: 'bg-surface-tertiary text-text-primary'
}`}
>
{useOverview ? 'Overview API' : 'Individual APIs'}
</button>
</div>
<div className="flex items-center space-x-2">
<label htmlFor="refresh-interval" className="text-sm text-text-secondary">
Refresh interval:
</label>
<select
id="refresh-interval"
value={refreshInterval}
onChange={handleRefreshIntervalChange}
className="text-sm bg-surface-secondary border border-border text-text-primary rounded px-2 py-1"
>
<option value={0}>Manual</option>
<option value={5000}>5 seconds</option>
<option value={10000}>10 seconds</option>
<option value={30000}>30 seconds</option>
<option value={60000}>1 minute</option>
</select>
</div>
<div className="flex items-center space-x-4">
<div className="flex items-center space-x-2">
<label className="text-sm text-text-secondary">Data source:</label>
<button
onClick={handleDataSourceToggle}
className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
useOverview ? 'bg-primary-600 text-white' : 'bg-surface-tertiary text-text-primary'
}`}
>
{useOverview ? 'Overview API' : 'Individual APIs'}
</button>
</div>
<div className="flex items-center space-x-2">
<label htmlFor="refresh-interval" className="text-sm text-text-secondary">
Refresh interval:
</label>
<select
id="refresh-interval"
value={refreshInterval}
onChange={handleRefreshIntervalChange}
className="text-sm bg-surface-secondary border border-border text-text-primary rounded px-2 py-1"
>
<option value={0}>Manual</option>
<option value={5000}>5 seconds</option>
<option value={10000}>10 seconds</option>
<option value={30000}>30 seconds</option>
<option value={60000}>1 minute</option>
</select>
</div>
</div>
</div>
{errors.length > 0 && (
@ -129,16 +162,20 @@ export function MonitoringPage() {
<h3 className="font-semibold text-primary-400 mb-2">System Environment</h3>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
<div>
<span className="text-primary-400">Node:</span> <span className="text-text-primary">{overview.environment.nodeVersion}</span>
<span className="text-primary-400">Node:</span>{' '}
<span className="text-text-primary">{overview.environment.nodeVersion}</span>
</div>
<div>
<span className="text-primary-400">Platform:</span> <span className="text-text-primary">{overview.environment.platform}</span>
<span className="text-primary-400">Platform:</span>{' '}
<span className="text-text-primary">{overview.environment.platform}</span>
</div>
<div>
<span className="text-primary-400">Architecture:</span> <span className="text-text-primary">{overview.environment.architecture}</span>
<span className="text-primary-400">Architecture:</span>{' '}
<span className="text-text-primary">{overview.environment.architecture}</span>
</div>
<div>
<span className="text-primary-400">Hostname:</span> <span className="text-text-primary">{overview.environment.hostname}</span>
<span className="text-primary-400">Hostname:</span>{' '}
<span className="text-text-primary">{overview.environment.hostname}</span>
</div>
</div>
</div>
@ -186,4 +223,4 @@ export function MonitoringPage() {
</div>
</div>
);
}
}

View file

@ -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 (
<Card className="p-4">
@ -32,11 +33,15 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
<div className="grid grid-cols-2 gap-3">
<div>
<div className="text-sm text-text-secondary">Memory Used</div>
<div className="text-lg font-semibold text-text-primary">{formatBytes(stats.memoryUsage.used)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatBytes(stats.memoryUsage.used)}
</div>
</div>
<div>
<div className="text-sm text-text-secondary">Peak Memory</div>
<div className="text-lg font-semibold text-text-primary">{formatBytes(stats.memoryUsage.peak)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatBytes(stats.memoryUsage.peak)}
</div>
</div>
</div>
)}
@ -46,29 +51,41 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
<div className="grid grid-cols-2 gap-3">
<div>
<div className="text-sm text-text-secondary">Hit Rate</div>
<div className="text-lg font-semibold text-text-primary">{formatPercentage(hitRate)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatPercentage(hitRate)}
</div>
</div>
<div>
<div className="text-sm text-text-secondary">Total Keys</div>
<div className="text-lg font-semibold text-text-primary">{formatNumber(stats.stats.keys)}</div>
<div className="text-lg font-semibold text-text-primary">
{formatNumber(stats.stats.keys)}
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<span className="text-text-secondary">Hits:</span> <span className="text-text-primary">{formatNumber(stats.stats.hits)}</span>
<span className="text-text-secondary">Hits:</span>{' '}
<span className="text-text-primary">{formatNumber(stats.stats.hits)}</span>
</div>
<div>
<span className="text-text-secondary">Misses:</span> <span className="text-text-primary">{formatNumber(stats.stats.misses)}</span>
<span className="text-text-secondary">Misses:</span>{' '}
<span className="text-text-primary">{formatNumber(stats.stats.misses)}</span>
</div>
{stats.stats.evictedKeys !== undefined && (
<div>
<span className="text-text-secondary">Evicted:</span> <span className="text-text-primary">{formatNumber(stats.stats.evictedKeys)}</span>
<span className="text-text-secondary">Evicted:</span>{' '}
<span className="text-text-primary">
{formatNumber(stats.stats.evictedKeys)}
</span>
</div>
)}
{stats.stats.expiredKeys !== undefined && (
<div>
<span className="text-text-secondary">Expired:</span> <span className="text-text-primary">{formatNumber(stats.stats.expiredKeys)}</span>
<span className="text-text-secondary">Expired:</span>{' '}
<span className="text-text-primary">
{formatNumber(stats.stats.expiredKeys)}
</span>
</div>
)}
</div>
@ -82,11 +99,9 @@ export function CacheStatsCard({ stats }: CacheStatsCardProps) {
)}
</div>
) : (
<div className="text-center py-8 text-text-secondary">
Cache service is not available
</div>
<div className="text-center py-8 text-text-secondary">Cache service is not available</div>
)}
</CardContent>
</Card>
);
}
}

View file

@ -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 (
<Card className="p-4">
<CardHeader className="p-0 pb-3">
<h3 className="text-base font-semibold text-text-primary">Queue Statistics</h3>
</CardHeader>
<CardContent className="p-0">
{queues.length > 0 ? (
<div className="overflow-x-auto">
@ -35,61 +29,94 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) {
<th className="text-center py-2 px-3 text-text-secondary font-medium">Status</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Waiting</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Active</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Completed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">
Completed
</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Failed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Delayed</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Prioritized</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">
Prioritized
</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Children</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Workers</th>
<th className="text-right py-2 px-3 text-text-secondary font-medium">Total</th>
</tr>
</thead>
<tbody>
{queues.map((queue) => (
<tr key={queue.name} className="border-b border-border hover:bg-surface-tertiary/50 transition-colors">
{queues.map(queue => (
<tr
key={queue.name}
className="border-b border-border hover:bg-surface-tertiary/50 transition-colors"
>
<td className="py-2 px-3 font-medium text-text-primary">{queue.service}</td>
<td className="py-2 px-3 font-medium text-text-primary">{queue.queue}</td>
<td className="py-2 px-3 text-center">
<span className={cn(
'inline-block w-2 h-2 rounded-full',
queue.connected ? 'bg-success' : 'bg-danger'
)} />
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.waiting)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.active > 0 ? (
<span className="text-primary-400 font-medium">{formatNumber(queue.jobs.active)}</span>
) : (
<span className="text-text-primary">{queue.jobs.active}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.completed)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.failed > 0 ? (
<span className="text-danger font-medium">{formatNumber(queue.jobs.failed)}</span>
) : (
<span className="text-text-primary">{queue.jobs.failed}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">{formatNumber(queue.jobs.delayed)}</td>
<td className="py-2 px-3 text-right">
{queue.jobs.prioritized && queue.jobs.prioritized > 0 ? (
<span className="text-primary-300 font-medium">{formatNumber(queue.jobs.prioritized)}</span>
) : (
<span className="text-text-primary">0</span>
)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? (
<span className="text-warning font-medium">{formatNumber(queue.jobs['waiting-children'])}</span>
) : (
<span className="text-text-primary">0</span>
)}
<span
className={cn(
'inline-block w-2 h-2 rounded-full',
queue.connected ? 'bg-success' : 'bg-danger'
)}
/>
</td>
{!queue.jobs ? (
<td colSpan={8} className="py-2 px-3 text-right">
Unknown — queue unavailable
</td>
) : (
<>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.waiting)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.active > 0 ? (
<span className="text-primary-400 font-medium">
{formatNumber(queue.jobs.active)}
</span>
) : (
<span className="text-text-primary">{queue.jobs.active}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.completed)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.failed > 0 ? (
<span className="text-danger font-medium">
{formatNumber(queue.jobs.failed)}
</span>
) : (
<span className="text-text-primary">{queue.jobs.failed}</span>
)}
</td>
<td className="py-2 px-3 text-right text-text-primary">
{formatNumber(queue.jobs.delayed)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs.prioritized && queue.jobs.prioritized > 0 ? (
<span className="text-primary-300 font-medium">
{formatNumber(queue.jobs.prioritized)}
</span>
) : (
<span className="text-text-primary">
{formatNumber(queue.jobs.prioritized)}
</span>
)}
</td>
<td className="py-2 px-3 text-right">
{queue.jobs['waiting-children'] && queue.jobs['waiting-children'] > 0 ? (
<span className="text-warning font-medium">
{formatNumber(queue.jobs['waiting-children'])}
</span>
) : (
<span className="text-text-primary">
{formatNumber(queue.jobs['waiting-children'])}
</span>
)}
</td>
</>
)}
<td className="py-2 px-3 text-right text-text-primary">
{queue.workers ? `${queue.workers.count}/${queue.workers.concurrency}` : '-'}
{queue.workers ? formatNumber(queue.workers.count) : 'Unknown'}
</td>
<td className="py-2 px-3 text-right font-medium text-text-primary">{formatNumber(totalJobs(queue))}</td>
</tr>
))}
</tbody>
@ -103,4 +130,4 @@ export function QueueStatsTable({ queues }: QueueStatsTableProps) {
</CardContent>
</Card>
);
}
}

View file

@ -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<MonitoringReadiness | null>(null);
const [error, setError] = useState(false);
const [loading, setLoading] = useState(true);
const active = useRef<AbortController | null>(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 (
<Card className="p-4">
<CardHeader>
<h2>Research and paper diagnostics</h2>
</CardHeader>
<CardContent>
<p>
This is a point-in-time snapshot. A responding HTTP service does not prove native
execution readiness.
</p>
<button type="button" onClick={() => void refresh()} disabled={loading}>
{loading ? 'Checking readiness…' : 'Refresh readiness'}
</button>
{error && (
<p role="alert">Readiness diagnostics unavailable. Retry to obtain a new snapshot.</p>
)}
{data && (
<>
<p>Observed: {data.observedAt}</p>
<p>
Research: {data.research.status}. PostgreSQL: {data.postgres}. Workers:{' '}
{data.queue.workers ?? 'Unknown'}.
</p>
<ul>
{data.research.reasons.map(reason => (
<li key={reason}>{reason}</li>
))}
</ul>
<p>
Native build: {data.orchestrator?.build?.engineBinarySha256 ?? 'Unknown'}. Native
execution: unverified until run start.
</p>
<p>
Paper:{' '}
{paper
? paper.ready
? 'Ready for operator review'
: 'Not ready'
: 'Unknown or not configured'}
.
</p>
{paper && (
<>
<p>
Feed connected: {String(paper.connected)}. Last received:{' '}
{paper.lastReceivedAt === null
? 'Unknown'
: new Date(paper.lastReceivedAt).toISOString()}
.
</p>
<p>
Active: {String(paper.active)}. Operator halted: {String(paper.operatorHalted)}.
Historical recovery required: {String(paper.requiresHistoricalRecovery)}.
</p>
<ul>
{paper.reasons.map(reason => (
<li key={reason}>{reason}</li>
))}
</ul>
</>
)}
<p>Live trading: disabled.</p>
{data.orchestrator?.research?.slots.map((slot, index) => (
<p key={index}>
Slot {index + 1}: {slot.phase}. Run {slot.runId ?? 'none'}; attempt{' '}
{slot.attemptId ?? 'none'}; strategy version {slot.strategyVersionId ?? 'none'}.
</p>
))}
{data.leases?.map(lease => (
<p key={lease.runId}>
SQL attempt {lease.attemptId ?? 'unknown'} for run {lease.runId}:{' '}
{lease.expired ? 'expired; recovery required' : 'lease current'}.
</p>
))}
</>
)}
<a href="/paper">Open deployment-specific paper readiness and recovery</a>
</CardContent>
</Card>
);
}

View file

@ -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 (
<Card className="p-3">
<CardHeader className="p-0 pb-2">
<div className="flex items-center justify-between">
<h3 className="font-semibold text-sm capitalize text-text-primary">
{service.name.replace(/-/g, ' ')}
</h3>
<ServiceStatusIndicator status={service.status} />
</div>
</CardHeader>
<CardContent className="p-0 space-y-1.5 text-xs">
<div className="flex justify-between">
<span className="text-text-secondary">Status:</span>
<span className="font-medium capitalize text-text-primary">{service.status}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Port:</span>
<span className="font-medium text-text-primary">{service.port || 'N/A'}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Version:</span>
<span className="font-medium text-text-primary">{service.version}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Uptime:</span>
<span className="font-medium text-text-primary">{formatUptime(service.uptime)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Health:</span>
<HealthStatus healthy={service.healthy} />
</div>
{service.error && (
<div className="mt-2 text-xs text-danger bg-danger/10 p-2 rounded">
Error: {service.error}
</div>
)}
</CardContent>
</Card>
);
}
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 (
<Card className="p-3">
<CardHeader className="p-0 pb-2">
<div className="flex items-center justify-between">
<h3 className="font-semibold text-sm capitalize text-text-primary">
{service.name.replace(/-/g, ' ')}
</h3>
<ServiceStatusIndicator status={service.status} />
</div>
</CardHeader>
<CardContent className="p-0 space-y-1.5 text-xs">
<div className="flex justify-between">
<span className="text-text-secondary">Status:</span>
<span className="font-medium capitalize text-text-primary">{service.status}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Port:</span>
<span className="font-medium text-text-primary">{service.port || 'N/A'}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Version:</span>
<span className="font-medium text-text-primary">{service.version}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary">Uptime:</span>
<span className="font-medium text-text-primary">{formatUptime(service.uptime)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Health:</span>
{service.healthy === null ? (
<span>Unknown (liveness only)</span>
) : (
<HealthStatus healthy={service.healthy} />
)}
</div>
{service.error && (
<div className="mt-2 text-xs text-danger bg-danger/10 p-2 rounded">
Error: {service.error}
</div>
)}
</CardContent>
</Card>
);
}

View file

@ -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<MonitoringReadiness> {
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<SystemHealth> {
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;
},
/**

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;
@ -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;
}

View file

@ -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)}%`;
}

View file

@ -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';

View file

@ -569,7 +569,7 @@ export class Queue {
/**
* Get count of active workers from BullMQ
*/
async getActiveWorkerCount(): Promise<number> {
async getActiveWorkerCount(): Promise<number | undefined> {
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;
}
}

View file

@ -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') &&

View file

@ -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);

View file

@ -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<Response>(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');
});

View file

@ -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<void>(),
exit = deferred<never>();
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<void>(),
exit = deferred<never>();
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();
});