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

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