fix(monitoring): report observed research and paper readiness (O02)
This commit is contained in:
parent
70d173a908
commit
8c858b9d5c
23 changed files with 1340 additions and 319 deletions
333
test/integration/monitoring-readiness.test.ts
Normal file
333
test/integration/monitoring-readiness.test.ts
Normal 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();
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue