Skip to content

Commit 880dde9

Browse files
authored
fix(diagnostics): preserve telemetry during service shutdown (#119705)
* fix(diagnostics): preserve otel service shutdown lifecycle * test(diagnostics): type OTEL unsubscribe callback * test(diagnostics): normalize async stop assertion * fix(plugins): preserve ordinary stop handling
1 parent 66bfafa commit 880dde9

6 files changed

Lines changed: 253 additions & 24 deletions

File tree

‎extensions/diagnostics-otel/src/service.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,27 @@ describe("diagnostics-otel service", () => {
10271027
expect(telemetryState.tracer.startSpan).not.toHaveBeenCalled();
10281028
});
10291029

1030+
test("attempts every provider shutdown and reports every failure", async () => {
1031+
const logError = new Error("log provider failed");
1032+
const sdkError = new Error("SDK providers failed");
1033+
logShutdown.mockRejectedValueOnce(logError);
1034+
sdkShutdown.mockRejectedValueOnce(sdkError);
1035+
const { service, ctx } = await startOtelService({ traces: true, metrics: true, logs: true });
1036+
1037+
const stopError = await Promise.resolve(service.stop?.(ctx)).catch((error: unknown) => error);
1038+
1039+
expect(logShutdown).toHaveBeenCalledTimes(1);
1040+
expect(sdkShutdown).toHaveBeenCalledTimes(1);
1041+
expect(stopError).toBeInstanceOf(AggregateError);
1042+
expect(stopError).toMatchObject({
1043+
errors: [logError, sdkError],
1044+
message: expect.stringContaining("log provider failed"),
1045+
});
1046+
expect(stopError).toMatchObject({
1047+
message: expect.stringContaining("SDK providers failed"),
1048+
});
1049+
});
1050+
10301051
test("registers and removes an OTLP exporter unhandled rejection handler", async () => {
10311052
const { service, ctx } = await startOtelService({ traces: true, metrics: true, logs: true });
10321053

@@ -1058,6 +1079,38 @@ describe("diagnostics-otel service", () => {
10581079
expect(unhandledRejectionHandlerState.getHandlers()).toHaveLength(0);
10591080
});
10601081

1082+
test("cleans up existing providers and does not reinitialize without capability", async () => {
1083+
const service = createDiagnosticsOtelService();
1084+
const enabledCtx = createOtelContext(OTEL_TEST_ENDPOINT, {
1085+
traces: true,
1086+
metrics: true,
1087+
logs: true,
1088+
});
1089+
await service.start(enabledCtx);
1090+
1091+
sdkCtor.mockClear();
1092+
sdkStart.mockClear();
1093+
logExporterCtor.mockClear();
1094+
const deniedCtx = createOtelContext(OTEL_TEST_ENDPOINT, {
1095+
traces: true,
1096+
metrics: true,
1097+
logs: true,
1098+
});
1099+
delete deniedCtx.internalDiagnostics;
1100+
1101+
await service.start(deniedCtx);
1102+
await service.stop?.(deniedCtx);
1103+
1104+
expect(deniedCtx.logger.error).toHaveBeenCalledWith(
1105+
"diagnostics-otel: internal diagnostics capability unavailable",
1106+
);
1107+
expect(sdkCtor).not.toHaveBeenCalled();
1108+
expect(sdkStart).not.toHaveBeenCalled();
1109+
expect(logExporterCtor).not.toHaveBeenCalled();
1110+
expect(sdkShutdown).toHaveBeenCalledOnce();
1111+
expect(logShutdown).toHaveBeenCalledOnce();
1112+
});
1113+
10611114
test("does not retain an OTLP exporter handler when startup setup fails", async () => {
10621115
const startupError = new Error("trace exporter setup failed");
10631116
traceExporterCtor.mockImplementationOnce(() => {

‎extensions/diagnostics-otel/src/service.ts‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,28 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
6767
stopActiveTrustedSpans = null;
6868
unregisterUnhandledRejectionHandler = null;
6969

70-
currentUnregisterUnhandledRejectionHandler?.();
71-
currentUnsubscribe?.();
72-
currentStopActiveTrustedSpans?.();
73-
if (currentLogProvider) {
74-
await currentLogProvider.shutdown().catch(() => undefined);
70+
const settle = async (...stops: Array<(() => void | Promise<void>) | null>) =>
71+
(
72+
await Promise.allSettled(stops.map((stop) => Promise.resolve().then(() => stop?.())))
73+
).flatMap((result) => (result.status === "rejected" ? [result.reason] : []));
74+
// Preserve cleanup -> provider flush -> handler removal while attempting every step per phase.
75+
const failures = await settle(currentUnsubscribe, currentStopActiveTrustedSpans);
76+
failures.push(
77+
...(await settle(
78+
currentLogProvider ? () => currentLogProvider.shutdown() : null,
79+
currentSdk ? () => currentSdk.shutdown() : null,
80+
)),
81+
...(await settle(currentUnregisterUnhandledRejectionHandler)),
82+
);
83+
84+
if (failures.length === 1) {
85+
throw failures[0];
7586
}
76-
if (currentSdk) {
77-
await currentSdk.shutdown().catch(() => undefined);
87+
if (failures.length > 1) {
88+
throw new AggregateError(
89+
failures,
90+
`diagnostics-otel shutdown failed: ${failures.join("; ")}`,
91+
);
7892
}
7993
};
8094

@@ -128,6 +142,12 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
128142
if (enabledSignals.length === 0) {
129143
return;
130144
}
145+
// This capability is the admission gate; no exporter may outlive a denied start.
146+
const subscribe = ctx.internalDiagnostics?.onEvent;
147+
if (!subscribe) {
148+
ctx.logger.error("diagnostics-otel: internal diagnostics capability unavailable");
149+
return;
150+
}
131151

132152
const envProtocol = process.env.OTEL_EXPORTER_OTLP_PROTOCOL;
133153
const protocol = otel.protocol ?? (envProtocol?.trim() ? envProtocol : "http/protobuf");
@@ -308,11 +328,6 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
308328
...createModelRecorders(recorderRuntime),
309329
...createToolAndSystemRecorders(recorderRuntime),
310330
};
311-
const subscribe = ctx.internalDiagnostics?.onEvent;
312-
if (!subscribe) {
313-
ctx.logger.error("diagnostics-otel: internal diagnostics capability unavailable");
314-
return;
315-
}
316331

317332
unsubscribe = subscribe(
318333
createDiagnosticsEventHandler({

‎src/infra/diagnostic-events.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,46 @@ describe("diagnostic-events", () => {
630630
expect(events).toHaveLength(250);
631631
});
632632

633+
it("does not extend a drain barrier for events queued after it starts", async () => {
634+
const callIds: string[] = [];
635+
onDiagnosticEvent((event) => {
636+
if (event.type === "model.call.started") {
637+
callIds.push(event.callId);
638+
}
639+
});
640+
641+
emitDiagnosticEvent({
642+
type: "model.call.started",
643+
runId: "run-before-barrier",
644+
callId: "before-barrier",
645+
provider: "openai",
646+
model: "gpt-5.4",
647+
});
648+
const drained = waitForDiagnosticEventsDrained();
649+
for (let index = 0; index < 250; index += 1) {
650+
emitDiagnosticEvent({
651+
type: "model.call.started",
652+
runId: `run-after-${index}`,
653+
callId: `after-${index}`,
654+
provider: "openai",
655+
model: "gpt-5.4",
656+
});
657+
}
658+
659+
await drained;
660+
661+
expect(callIds).toHaveLength(100);
662+
expect(callIds[0]).toBe("before-barrier");
663+
expect(
664+
hasPendingInternalDiagnosticEvent(
665+
(event) => event.type === "model.call.started" && event.callId === "after-249",
666+
),
667+
).toBe(true);
668+
669+
await waitForDiagnosticEventsDrained();
670+
expect(callIds).toHaveLength(251);
671+
});
672+
633673
it("reports pending async diagnostic events before they drain", async () => {
634674
emitTrustedDiagnosticEvent({
635675
type: "tool.execution.error",

‎src/infra/diagnostic-events.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,10 +1216,15 @@ function dispatchAsyncDiagnosticDropSummary(state: DiagnosticEventsGlobalState):
12161216
dispatchDiagnosticEvent(state, event, createInternalDiagnosticMetadata(false));
12171217
}
12181218

1219-
/** Waits until queued async diagnostic events have been delivered to listeners. */
1219+
/** Waits until async diagnostic events queued when called are no longer pending. */
12201220
export async function waitForDiagnosticEventsDrained(): Promise<void> {
12211221
const state = getDiagnosticEventsState();
1222-
while (state.asyncDrainScheduled || state.asyncQueue.length > 0) {
1222+
const targetSeq = state.asyncQueue.at(-1)?.event.seq;
1223+
if (targetSeq === undefined) {
1224+
return;
1225+
}
1226+
// The queue is append-ordered by seq, so a newer head means this snapshot drained or dropped.
1227+
while ((state.asyncQueue[0]?.event.seq ?? Number.POSITIVE_INFINITY) <= targetSeq) {
12231228
await new Promise<void>((resolve) => {
12241229
setImmediate(resolve);
12251230
});

‎src/plugins/services.test.ts‎

Lines changed: 97 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ vi.mock("../logging/subsystem.js", () => ({
1717
}));
1818

1919
import { STATE_DIR } from "../config/paths.js";
20+
import {
21+
emitTrustedDiagnosticEvent,
22+
resetDiagnosticEventsForTest,
23+
waitForDiagnosticEventsDrained,
24+
} from "../infra/diagnostic-events.js";
2025
import { queuePluginSessionsChanged, subscribePluginSessionsChanged } from "./gateway-events.js";
2126
import { registerPluginHttpRoute } from "./http-registry.js";
2227
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "./runtime.js";
@@ -142,6 +147,7 @@ function createTrackingService(
142147
describe("startPluginServices", () => {
143148
beforeEach(() => {
144149
vi.clearAllMocks();
150+
resetDiagnosticEventsForTest();
145151
resetPluginRuntimeStateForTest();
146152
});
147153

@@ -165,6 +171,82 @@ describe("startPluginServices", () => {
165171
expectServiceLifecycleState({ starts, stops, contexts, config });
166172
});
167173

174+
it("drains producer diagnostics before exporters stop and propagates exporter failures", async () => {
175+
const order: string[] = [];
176+
const producerError = new Error("producer stop failed");
177+
const exporterError = new Error("exporter stop failed");
178+
let unsubscribe: () => void = () => undefined;
179+
const registry = createRegistry(
180+
[
181+
{
182+
id: "producer",
183+
start: () => undefined,
184+
stop: () => {
185+
order.push("producer");
186+
emitTrustedDiagnosticEvent({
187+
type: "log.record",
188+
level: "INFO",
189+
message: "queued during producer shutdown",
190+
});
191+
throw producerError;
192+
},
193+
},
194+
],
195+
"plugin:test",
196+
"workspace",
197+
);
198+
registry.services.push(
199+
...createRegistry(
200+
[
201+
{
202+
id: "diagnostics-prometheus",
203+
start: () => undefined,
204+
stop: () => {
205+
order.push("prometheus");
206+
},
207+
},
208+
],
209+
"diagnostics-prometheus",
210+
"bundled",
211+
).services,
212+
...createRegistry(
213+
[
214+
{
215+
id: "diagnostics-otel",
216+
start: (ctx) => {
217+
unsubscribe = ctx.internalDiagnostics!.onEvent((event) => {
218+
if (event.type === "log.record") {
219+
order.push("event");
220+
}
221+
});
222+
},
223+
stop: () => {
224+
order.push("otel");
225+
unsubscribe();
226+
throw exporterError;
227+
},
228+
},
229+
],
230+
"diagnostics-otel",
231+
"bundled",
232+
).services,
233+
);
234+
235+
const handle = await startPluginServices({
236+
registry,
237+
config: createServiceConfig(),
238+
});
239+
240+
await expect(handle.stop()).rejects.toBe(exporterError);
241+
await waitForDiagnosticEventsDrained();
242+
243+
expect(order).toEqual(["producer", "event", "otel", "prometheus"]);
244+
expect(mockedLogger.warn.mock.calls).toEqual([
245+
["plugin service stop failed (producer): Error: producer stop failed"],
246+
["plugin service stop failed (diagnostics-otel): Error: exporter stop failed"],
247+
]);
248+
});
249+
168250
it("rolls back partially started services before starting their siblings", async () => {
169251
const acquired = new Set<string>();
170252
const received = vi.fn();
@@ -474,10 +556,15 @@ describe("startPluginServices", () => {
474556
await handle.stop();
475557
});
476558

477-
it("logs start/stop failures and continues", async () => {
559+
it("attempts every ordinary service stop and preserves warn-and-continue failures", async () => {
478560
const stopOk = vi.fn();
479-
const stopThrows = vi.fn(() => {
480-
throw new Error("stop failed");
561+
const firstError = new Error("first stop failed");
562+
const secondError = new Error("second stop failed");
563+
const stopFirst = vi.fn(() => {
564+
throw firstError;
565+
});
566+
const stopSecond = vi.fn(() => {
567+
throw secondError;
481568
});
482569

483570
const handle = await startTrackingServices({
@@ -486,12 +573,13 @@ describe("startPluginServices", () => {
486573
failOnStart: true,
487574
stopSpy: vi.fn(),
488575
}),
576+
createTrackingService("service-stop-first", { stopSpy: stopFirst }),
489577
createTrackingService("service-ok", { stopSpy: stopOk }),
490-
createTrackingService("service-stop-fail", { stopSpy: stopThrows }),
578+
createTrackingService("service-stop-second", { stopSpy: stopSecond }),
491579
],
492580
});
493581

494-
await handle.stop();
582+
await expect(handle.stop()).resolves.toBeUndefined();
495583

496584
expect(mockedLogger.error.mock.calls).toEqual([
497585
[
@@ -500,10 +588,12 @@ describe("startPluginServices", () => {
500588
]);
501589
expect(requireLoggerErrorMessage()).not.toContain("\n");
502590
expect(mockedLogger.warn.mock.calls).toEqual([
503-
["plugin service stop failed (service-stop-fail): Error: stop failed"],
591+
["plugin service stop failed (service-stop-second): Error: second stop failed"],
592+
["plugin service stop failed (service-stop-first): Error: first stop failed"],
504593
]);
505594
expect(stopOk).toHaveBeenCalledOnce();
506-
expect(stopThrows).toHaveBeenCalledOnce();
595+
expect(stopFirst).toHaveBeenCalledOnce();
596+
expect(stopSecond).toHaveBeenCalledOnce();
507597
});
508598

509599
it("continues starting siblings when rollback also fails", async () => {

0 commit comments

Comments
 (0)