Skip to content

Commit 3bc188e

Browse files
SunnyShu0925claudevincentkoc
authored
fix(diagnostics-otel): keep telemetry exporting across in-process restarts (#120131)
* [AI] fix(diagnostics-otel): keep telemetry exporting across in-process restarts Owned diagnostics-otel generations previously registered their OpenTelemetry providers globally and only shut the providers down on stop. The pinned sdk-node registers globals without override and never unregisters them, so a second in-process generation (config-watcher reload, OPENCLAW_NO_RESPAWN=1, containers) kept exporting through the first, already-shutdown providers and telemetry silently stopped. Switch owned mode to private BasicTracerProvider + MeterProvider instances whose handles are injected directly into the existing recorder runtime, and keep the preloaded (OPENCLAW_OTEL_PRELOADED=1) mode on the host's global providers without ever registering or replacing globals. Resource detection honors the pinned NodeSDK OTEL_NODE_RESOURCE_DETECTORS contract (unset defaults to env+process+host; none/subset/all are respected), and the unused @opentelemetry/sdk-node dependency is removed with a minimal lockfile update. Adds a real-SDK two-generation restart regression, real-SDK resource-detector selection coverage, migrates the unit mocks to the provider lifecycle, and updates the OpenTelemetry docs. Fixes #119997 Co-Authored-By: glm-5.2 <[email protected]> * [AI] test(diagnostics-otel): restore OpenTelemetry globals after restart test The restart regression disables global context, metrics, propagation, and trace APIs and forces OPENCLAW_OTEL_PRELOADED=0, but its cleanup only reset diagnostic events, so a later test in the same worker could inherit no-op providers. Snapshot the prior global registrations and preloaded env at module load, and re-register/restore them in afterEach, matching the existing exporter-health integration test pattern. Co-Authored-By: glm-5.2 <[email protected]> * [AI] fix(diagnostics-otel): reconcile private providers with OTEL_SDK_DISABLED Rebase onto main after #119961 (honor OTEL_SDK_DISABLED) changed the disabled admission path to return before SDK construction. Restore the removed getBooleanFromEnv import, drop the stale ownedNodeSdkDisabled guard, and update disabled-mode tests to the new semantics (all routes off, disabled runtime registered) plus the private-provider signal path for the integration suite. Related to #119997 Co-Authored-By: Claude <[email protected]> * fix(diagnostics-otel): isolate restartable provider generations * test(diagnostics-otel): prove same-pid generation routing * test(diagnostics-otel): use supported watcher reload mode * test(diagnostics-otel): satisfy ownership proof gates * test(diagnostics-otel): use managed proof cleanup * test(diagnostics-otel): verify injected trace ancestry --------- Co-authored-by: glm-5.2 <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent 4cbbfc2 commit 3bc188e

17 files changed

Lines changed: 2301 additions & 282 deletions

‎docs/gateway/opentelemetry.md‎

Lines changed: 24 additions & 11 deletions
Large diffs are not rendered by default.

‎extensions/diagnostics-otel/package.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
"@opentelemetry/resources": "2.10.0",
2121
"@opentelemetry/sdk-logs": "0.221.0",
2222
"@opentelemetry/sdk-metrics": "2.10.0",
23-
"@opentelemetry/sdk-node": "0.221.0",
2423
"@opentelemetry/sdk-trace-base": "2.10.0",
2524
"@opentelemetry/semantic-conventions": "1.43.0"
2625
},

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

Lines changed: 48 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,11 @@ import { context, metrics, propagation, ROOT_CONTEXT, trace } from "@opentelemet
44
import { logs } from "@opentelemetry/api-logs";
55
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
66
import { W3CTraceContextPropagator } from "@opentelemetry/core";
7-
import {
8-
emitTrustedDiagnosticEventWithPrivateData,
9-
resetDiagnosticEventsForTest,
10-
waitForDiagnosticEventsDrained,
11-
} from "openclaw/plugin-sdk/diagnostic-runtime";
7+
import { resetDiagnosticEventsForTest } from "openclaw/plugin-sdk/diagnostic-runtime";
128
import { afterEach, beforeEach, expect, test, vi } from "vitest";
139
import { startLocalOtlpReceiver } from "../../../test/e2e/qa-lab/runtime/otel-test-support.js";
1410
import {
11+
emitRealSdkSignals,
1512
getReportedExporterHealth,
1613
startOtelService,
1714
stopStartedOtelServices,
@@ -107,20 +104,6 @@ afterEach(async () => {
107104
resetDiagnosticEventsForTest();
108105
});
109106

110-
async function emitOpenClawSignals() {
111-
trace.getTracer("openclaw-otel-disabled-test").startSpan("disabled-test").end();
112-
metrics.getMeter("openclaw-otel-disabled-test").createCounter("disabled.test").add(1);
113-
emitTrustedDiagnosticEventWithPrivateData(
114-
{
115-
type: "log.record",
116-
level: "INFO",
117-
message: "disabled route test",
118-
},
119-
{},
120-
);
121-
await waitForDiagnosticEventsDrained();
122-
}
123-
124107
test("disables every OpenClaw route while preserving W3C propagation", async () => {
125108
const receiver = startLocalOtlpReceiver();
126109
const port = await receiver.listen();
@@ -139,7 +122,7 @@ test("disables every OpenClaw route while preserving W3C propagation", async ()
139122
});
140123

141124
try {
142-
await emitOpenClawSignals();
125+
await emitRealSdkSignals();
143126
const incoming = {
144127
baggage: "tenant=example",
145128
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
@@ -204,33 +187,40 @@ test("preserves externally owned context and propagation globals while disabled"
204187
});
205188
});
206189

207-
test("does not remove context and propagation globals installed after startup", async () => {
208-
process.env.OTEL_SDK_DISABLED = "true";
209-
const { service, ctx } = await startOtelService();
210-
const capturedContext = context.active();
190+
test.each(["true", "false"] as const)(
191+
"does not remove replacement context and propagation owners when disabled=$disabled",
192+
async (disabled) => {
193+
process.env.OTEL_SDK_DISABLED = disabled;
194+
const { service, ctx } = await startOtelService({
195+
traces: false,
196+
metrics: false,
197+
logs: false,
198+
});
199+
const capturedContext = context.active();
211200

212-
context.disable();
213-
propagation.disable();
214-
const externalContextManager = new AsyncLocalStorageContextManager().enable();
215-
expect(context.setGlobalContextManager(externalContextManager)).toBe(true);
216-
expect(propagation.setGlobalPropagator(new W3CTraceContextPropagator())).toBe(true);
217-
const incoming = {
218-
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
219-
};
220-
const extracted = propagation.extract(ROOT_CONTEXT, incoming);
201+
context.disable();
202+
propagation.disable();
203+
const externalContextManager = new AsyncLocalStorageContextManager().enable();
204+
expect(context.setGlobalContextManager(externalContextManager)).toBe(true);
205+
expect(propagation.setGlobalPropagator(new W3CTraceContextPropagator())).toBe(true);
206+
const incoming = {
207+
traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
208+
};
209+
const extracted = propagation.extract(ROOT_CONTEXT, incoming);
221210

222-
await context.with(capturedContext, () => service.stop?.(ctx));
211+
await context.with(capturedContext, () => service.stop?.(ctx));
223212

224-
expect(propagation.fields()).toEqual(["traceparent", "tracestate"]);
225-
await context.with(extracted, async () => {
226-
await new Promise<void>((resolve) => {
227-
setImmediate(resolve);
213+
expect(propagation.fields()).toEqual(["traceparent", "tracestate"]);
214+
await context.with(extracted, async () => {
215+
await new Promise<void>((resolve) => {
216+
setImmediate(resolve);
217+
});
218+
expect(trace.getSpanContext(context.active())?.traceId).toBe(
219+
"4bf92f3577b34da6a3ce929d0e0e4736",
220+
);
228221
});
229-
expect(trace.getSpanContext(context.active())?.traceId).toBe(
230-
"4bf92f3577b34da6a3ce929d0e0e4736",
231-
);
232-
});
233-
});
222+
},
223+
);
234224

235225
test.each([
236226
{
@@ -280,11 +270,11 @@ test.each([
280270
},
281271
);
282272

283-
test("cleans disabled globals before starting the enabled NodeSDK", async () => {
273+
test("cleans disabled ownership before a fresh enabled private-provider generation", async () => {
284274
const receiver = startLocalOtlpReceiver();
285275
const port = await receiver.listen();
286276
process.env.OTEL_SDK_DISABLED = "true";
287-
const { service, ctx } = await startOtelService({
277+
const disabled = await startOtelService({
288278
endpoint: `http://127.0.0.1:${port}`,
289279
traces: true,
290280
metrics: true,
@@ -294,16 +284,25 @@ test("cleans disabled globals before starting the enabled NodeSDK", async () =>
294284

295285
try {
296286
expect(propagation.fields()).toEqual(["traceparent", "tracestate", "baggage"]);
287+
await disabled.service.stop?.(disabled.ctx);
297288
process.env.OTEL_SDK_DISABLED = "false";
298-
await service.start(ctx);
299-
await emitOpenClawSignals();
300-
await service.stop?.(ctx);
289+
const enabled = await startOtelService({
290+
endpoint: `http://127.0.0.1:${port}`,
291+
traces: true,
292+
metrics: true,
293+
logs: true,
294+
logsExporter: "otlp",
295+
});
296+
expect(enabled.service).not.toBe(disabled.service);
297+
expect(propagation.fields()).toEqual(["traceparent", "tracestate", "baggage"]);
298+
await emitRealSdkSignals("enabled-generation");
299+
await enabled.service.stop?.(enabled.ctx);
301300

302301
expect(new Set(receiver.capturedRequests.map((request) => request.signal))).toEqual(
303302
new Set(["traces", "metrics", "logs"]),
304303
);
305304
} finally {
306-
await service.stop?.(ctx);
305+
await disabled.service.stop?.(disabled.ctx);
307306
await receiver.close();
308307
}
309308
}, 30_000);

‎extensions/diagnostics-otel/src/service-exporter-health.integration.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { AddressInfo } from "node:net";
33
import { context, diag, DiagLogLevel, metrics, propagation, trace } from "@opentelemetry/api";
44
import { logs } from "@opentelemetry/api-logs";
55
import {
6+
emitTrustedDiagnosticEventWithPrivateData,
67
onInternalDiagnosticEvent,
78
resetDiagnosticEventsForTest,
89
waitForDiagnosticEventsDrained,
@@ -164,6 +165,9 @@ function captureExporterEvents() {
164165
return { events, unsubscribe };
165166
}
166167

168+
const emit = (event: Parameters<typeof emitTrustedDiagnosticEventWithPrivateData>[0]) =>
169+
emitTrustedDiagnosticEventWithPrivateData(event, {});
170+
167171
async function waitForExporterStatus(
168172
events: Array<Pick<ReportedExporterHealth, "status">>,
169173
status: ReportedExporterHealth["status"],
@@ -181,7 +185,17 @@ async function waitForExporterStatus(
181185
}
182186

183187
function emitExporterHealthSpan(name: string) {
184-
trace.getTracer("openclaw-otel-exporter-health-test").startSpan(name).end();
188+
// Owned mode keeps trace providers private, so spans must be created through
189+
// the diagnostic event recorders instead of the global trace API.
190+
emit({
191+
type: "model.call.completed",
192+
runId: `run-${name}`,
193+
callId: `call-${name}`,
194+
provider: "openai",
195+
model: "gpt-5.4",
196+
durationMs: 10,
197+
usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, total: 2 },
198+
});
185199
}
186200

187201
function startTraceExporterHealthService(
@@ -238,6 +252,7 @@ test("retries a real OTLP 503 then succeeds without an intermediate failure fact
238252

239253
try {
240254
emitExporterHealthSpan("retry-then-success");
255+
await waitForDiagnosticEventsDrained();
241256
await service.stop?.(ctx);
242257
await waitForDiagnosticEventsDrained();
243258
expect(receiver.requestCount).toBe(2);
@@ -264,6 +279,7 @@ test("records a final failure after persistent real OTLP 503 responses", async (
264279

265280
try {
266281
emitExporterHealthSpan("persistent-503");
282+
await waitForDiagnosticEventsDrained();
267283
await Promise.resolve(service.stop?.(ctx)).catch(() => {});
268284
await waitForDiagnosticEventsDrained();
269285
expect(receiver.requestCount).toBe(6);
@@ -293,6 +309,7 @@ test("records a final failure for a real OTLP connection reset", async () => {
293309

294310
try {
295311
emitExporterHealthSpan("connection-reset");
312+
await waitForDiagnosticEventsDrained();
296313
await Promise.resolve(service.stop?.(ctx)).catch(() => {});
297314
await waitForDiagnosticEventsDrained();
298315
expect(receiver.requestCount).toBeGreaterThanOrEqual(1);
@@ -322,6 +339,7 @@ test("records a final failure for a real OTLP request timeout", async () => {
322339

323340
try {
324341
emitExporterHealthSpan("request-timeout");
342+
await waitForDiagnosticEventsDrained();
325343
await Promise.resolve(service.stop?.(ctx)).catch(() => {});
326344
await waitForDiagnosticEventsDrained();
327345
expect(receiver.requestCount).toBeGreaterThanOrEqual(1);
@@ -357,9 +375,11 @@ test("records recovery after a later real OTLP export succeeds", async () => {
357375

358376
try {
359377
emitExporterHealthSpan("failure-before-recovery");
378+
await waitForDiagnosticEventsDrained();
360379
await waitForExporterStatus(health, "failure");
361380
failExports = false;
362381
emitExporterHealthSpan("successful-recovery");
382+
await waitForDiagnosticEventsDrained();
363383
await waitForExporterStatus(health, "recovered");
364384
expect(
365385
health.filter((event) => event.reason === "export_failed").map((event) => event.status),

0 commit comments

Comments
 (0)