Skip to content

Commit cb9bc66

Browse files
committed
fix(health): recompute dead-letter counts for cached gateway responses
The gateway health handler can serve a cached snapshot for up to a refresh interval, so a delivery dead-lettered after the cache was filled stayed hidden from openclaw health. Recompute the delivery queue summary in mergeCachedHealthRuntimeState alongside the existing context-engine and model-pricing live merges, and cover the cached handler path with a regression test.
1 parent 5b69763 commit cb9bc66

3 files changed

Lines changed: 80 additions & 2 deletions

File tree

‎src/commands/health.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,8 @@ export function formatContextEngineHealthLine(summary: HealthSummary): string |
245245
return `Context engine: warning (${quarantined.length} quarantined; downgraded to legacy: ${engines})`;
246246
}
247247

248-
function buildDeliveryQueueHealthSummary(): DeliveryQueueHealthSummary | undefined {
248+
/** Builds dead-lettered delivery queue health; shared with cached gateway responses. */
249+
export function buildDeliveryQueueHealthSummary(): DeliveryQueueHealthSummary | undefined {
249250
// Dead-lettered deliveries are retained in SQLite for diagnostics but had no
250251
// health surface; a storage read failure must not take health down with it.
251252
try {

‎src/gateway/server-methods/health.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// detecting stale channel runtime state against live gateway snapshots.
33
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
44
import type { ChannelAccountSnapshot } from "../../channels/plugins/types.public.js";
5+
import { buildDeliveryQueueHealthSummary } from "../../commands/health.js";
56
import type { ChannelHealthSummary, HealthSummary } from "../../commands/health.types.js";
67
import { getStatusSummary } from "../../commands/status.js";
78
import { listContextEngineQuarantines } from "../../context-engine/registry.js";
@@ -92,7 +93,15 @@ function mergeCachedHealthRuntimeState(params: {
9293
cached: HealthSummary;
9394
eventLoop?: HealthSummary["eventLoop"];
9495
}): HealthSummary {
95-
const { contextEngines: _cachedContextEngines, ...cached } = params.cached;
96+
const {
97+
contextEngines: _cachedContextEngines,
98+
deliveryQueues: _cachedDeliveryQueues,
99+
...cached
100+
} = params.cached;
101+
// Dead-letter counts are cheap SQLite reads; recompute them like context
102+
// engines so a delivery that failed after the cache was filled is not hidden
103+
// for a refresh interval.
104+
const deliveryQueues = buildDeliveryQueueHealthSummary();
96105
const quarantinedContextEngines: NonNullable<HealthSummary["contextEngines"]>["quarantined"] = [];
97106
for (const entry of listContextEngineQuarantines()) {
98107
const summary: NonNullable<HealthSummary["contextEngines"]>["quarantined"][number] = {
@@ -112,6 +121,7 @@ function mergeCachedHealthRuntimeState(params: {
112121
...(quarantinedContextEngines.length > 0
113122
? { contextEngines: { quarantined: quarantinedContextEngines } }
114123
: {}),
124+
...(deliveryQueues ? { deliveryQueues } : {}),
115125
modelPricing: getGatewayModelPricingHealth({
116126
enabled: params.cached.modelPricing?.state !== "disabled",
117127
}),

‎src/gateway/server-methods/server-methods.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4734,6 +4734,73 @@ describe("gateway healthHandlers.health cache freshness", () => {
47344734
}
47354735
});
47364736

4737+
it("merges live dead-lettered delivery queue counts into cached health responses", async () => {
4738+
const tmpStateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-health-cached-dq-"));
4739+
const previousStateDir = process.env.OPENCLAW_STATE_DIR;
4740+
process.env.OPENCLAW_STATE_DIR = tmpStateDir;
4741+
try {
4742+
const { moveDeliveryQueueEntryToFailed, upsertDeliveryQueueEntry } =
4743+
await import("../../infra/delivery-queue-sqlite.js");
4744+
// The cached snapshot was built before this delivery dead-lettered.
4745+
const cached = {
4746+
ok: true,
4747+
ts: Date.now(),
4748+
durationMs: 1,
4749+
channels: {},
4750+
channelOrder: [],
4751+
channelLabels: {},
4752+
heartbeatSeconds: 0,
4753+
defaultAgentId: "main",
4754+
agents: [],
4755+
sessions: { path: "/tmp/sessions.json", count: 0, recent: [] },
4756+
};
4757+
upsertDeliveryQueueEntry({
4758+
queueName: "outbound",
4759+
entry: { id: "dead-1", enqueuedAt: 1_000, retryCount: 5 },
4760+
});
4761+
moveDeliveryQueueEntryToFailed("outbound", "dead-1");
4762+
4763+
const respond = vi.fn();
4764+
const refreshHealthSnapshot = vi.fn().mockResolvedValue(cached);
4765+
4766+
await healthHandlers.health({
4767+
req: {} as never,
4768+
params: {} as never,
4769+
respond: respond as never,
4770+
context: {
4771+
getHealthCache: () => cached,
4772+
refreshHealthSnapshot,
4773+
getRuntimeSnapshot: () => ({ channels: {}, channelAccounts: {} }),
4774+
logHealth: { error: vi.fn() },
4775+
} as never,
4776+
client: { connect: { role: "operator", scopes: ["operator.read"] } } as never,
4777+
isWebchatConnect: () => false,
4778+
});
4779+
4780+
const payload = mockCallArg(respond, 0, 1) as
4781+
| {
4782+
deliveryQueues?: {
4783+
failed?: Array<{ queueName?: string; count?: number; oldestFailedAt?: number }>;
4784+
};
4785+
}
4786+
| undefined;
4787+
expect(payload?.deliveryQueues?.failed).toHaveLength(1);
4788+
expect(payload?.deliveryQueues?.failed?.[0]).toMatchObject({
4789+
queueName: "outbound",
4790+
count: 1,
4791+
});
4792+
expect(typeof payload?.deliveryQueues?.failed?.[0]?.oldestFailedAt).toBe("number");
4793+
expect(mockCallArg(respond, 0, 3)).toEqual({ cached: true });
4794+
} finally {
4795+
if (previousStateDir === undefined) {
4796+
delete process.env.OPENCLAW_STATE_DIR;
4797+
} else {
4798+
process.env.OPENCLAW_STATE_DIR = previousStateDir;
4799+
}
4800+
fs.rmSync(tmpStateDir, { recursive: true, force: true });
4801+
}
4802+
});
4803+
47374804
it("refreshes cached health when a runtime account is missing from the cached account summary", async () => {
47384805
const cached = {
47394806
ok: true,

0 commit comments

Comments
 (0)