Skip to content

Commit 3c246e1

Browse files
committed
fix(diagnostics): preserve trace propagation contracts
1 parent 871d8fb commit 3c246e1

12 files changed

Lines changed: 207 additions & 65 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ c1ea9510dfda047609a99d5d2cd1f1560f5d469a36e6b695766213d695c25b0f module/convers
6161
dea96213010cbc816345b1229534f1acb8b0bcfdbd7814c62eefc77030fa9cd8 module/core
6262
4af19d59c2f18674e7d7f7dc1b358b644dc707e6bd601dc47168bd9e4a669940 module/dedupe-runtime
6363
f70c93d28053ca2e8353e45e6515ce7acef188097c6117d1545965d0699c8004 module/device-bootstrap
64-
783df660a61c0942d4b31c995a5c75ccc015f24a2af5fe22ea974b113643fb6c module/diagnostic-runtime
64+
68c726280f6585af96c071758ba383e55480b4fc913eae7c26aea1af331dedf3 module/diagnostic-runtime
6565
ea81ef06956c1bc0853fa00afbbc2b5a4019116aaf8a436e1b27d06f7a2c9e88 module/directory-runtime
6666
086bb46f97cb1f4a040b602444daf2c47ac2c24aca150a0d238933956a8100fc module/discord
6767
f65408d85477bb362ebe6ed9148c1bb6b9eb7839733e5e3119f4ff8f1cfd0567 module/error-runtime

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export function createModelRecorders(runtime: DiagnosticsRecorderRuntime) {
8484
metadata: DiagnosticEventMetadata,
8585
) => {
8686
if (!tracesEnabled || !metadata.trusted) {
87-
return;
87+
return undefined;
8888
}
8989
const trackedSpan = getTrackedInternalOrTrustedSpan(evt, metadata);
9090
if (trackedSpan) {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
9797
metadata: DiagnosticEventMetadata,
9898
) => {
9999
if (!tracesEnabled || !metadata.trusted) {
100-
return;
100+
return undefined;
101101
}
102102
const trackedSpan = getTrackedInternalOrTrustedSpan(evt, metadata);
103103
if (trackedSpan) {

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

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,15 @@ import {
2828
createChildDiagnosticTraceContext,
2929
createDiagnosticTraceContext,
3030
emitTrustedDiagnosticEventWithPrivateData,
31-
formatDiagnosticTraceparent,
3231
parseDiagnosticTraceparent,
3332
resetDiagnosticEventsForTest,
3433
waitForDiagnosticEventsDrained,
3534
} from "openclaw/plugin-sdk/diagnostic-runtime";
3635
import { afterEach, beforeEach, expect, test, vi } from "vitest";
37-
import { startLocalOtlpReceiver } from "../../../test/e2e/qa-lab/runtime/otel-test-support.js";
36+
import {
37+
runModelCallAndCaptureTraceparent,
38+
startLocalOtlpReceiver,
39+
} from "../../../test/e2e/qa-lab/runtime/otel-test-support.js";
3840
import { createDiagnosticsOtelService } from "./service.js";
3941
import {
4042
createOtelContext,
@@ -452,11 +454,9 @@ test("propagates the exported model span across two OTLP services with one roote
452454
const messageTrace = createChildDiagnosticTraceContext(inboundParent);
453455
const harnessTrace = createChildDiagnosticTraceContext(messageTrace);
454456
const runTrace = createChildDiagnosticTraceContext(harnessTrace);
455-
const modelTrace = createChildDiagnosticTraceContext(runTrace);
456457
const toolTrace = createChildDiagnosticTraceContext(runTrace);
457458
const base = { runId: "run-live-bridge", provider: "openai", model: "gpt-5.6-luna" };
458459
const harnessBase = { ...base, harnessId: "openclaw" };
459-
const modelBase = { ...base, callId: "call-live-bridge" };
460460

461461
emit({
462462
type: "message.dispatch.started",
@@ -466,9 +466,11 @@ test("propagates the exported model span across two OTLP services with one roote
466466
});
467467
emit({ type: "harness.run.started", ...harnessBase, trace: harnessTrace });
468468
emit({ type: "run.started", ...base, trace: runTrace });
469-
emit({ type: "model.call.started", ...modelBase, trace: modelTrace });
470-
471-
const outboundTraceparent = formatDiagnosticTraceparent(modelTrace);
469+
const outboundTraceparent = runModelCallAndCaptureTraceparent({
470+
...base,
471+
callId: "call-live-bridge",
472+
trace: runTrace,
473+
});
472474
const outboundContext = parseDiagnosticTraceparent(outboundTraceparent);
473475
expect(outboundContext).toBeDefined();
474476
const peerCallback = peerTracer.startSpan(
@@ -483,12 +485,6 @@ test("propagates the exported model span across two OTLP services with one roote
483485
);
484486
peerCallback.end();
485487

486-
emit({
487-
type: "model.call.completed",
488-
...modelBase,
489-
durationMs: 20,
490-
trace: modelTrace,
491-
});
492488
emit({
493489
type: "tool.execution.started",
494490
runId: base.runId,
@@ -562,22 +558,12 @@ test("propagates the exported model span across two OTLP services with one roote
562558

563559
test("uses the real preloaded model span as the mid-turn propagation root", async () => {
564560
const { service, ctx } = await startOtelService({ traces: true });
565-
const modelTrace = createDiagnosticTraceContext();
566-
const base = {
567-
type: "model.call.started" as const,
561+
const outboundTraceparent = runModelCallAndCaptureTraceparent({
562+
trace: createDiagnosticTraceContext(),
568563
runId: "run-mid-turn",
569564
callId: "call-mid-turn",
570565
provider: "openai",
571566
model: "gpt-5.6-luna",
572-
trace: modelTrace,
573-
};
574-
575-
emit(base);
576-
const outboundTraceparent = formatDiagnosticTraceparent(modelTrace);
577-
emit({
578-
...base,
579-
type: "model.call.completed",
580-
durationMs: 10,
581567
});
582568
await waitForDiagnosticEventsDrained();
583569
await service.stop?.(ctx);

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

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,11 +1013,30 @@ describe("diagnostics-otel service", () => {
10131013
});
10141014

10151015
test("restarts without retaining prior listeners or log transports", async () => {
1016-
const { service, ctx } = await startOtelService({ traces: true, metrics: true, logs: true });
1016+
const unregisterBridge = vi.fn();
1017+
const { service, ctx } = await startOtelService({
1018+
traces: true,
1019+
metrics: true,
1020+
logs: true,
1021+
configure: (context) => {
1022+
const registerBridge = context.internalDiagnostics?.registerTracePropagationBridge;
1023+
context.internalDiagnostics = {
1024+
...context.internalDiagnostics!,
1025+
registerTracePropagationBridge: (bridge) => {
1026+
const unregister = registerBridge!(bridge);
1027+
return () => {
1028+
unregisterBridge();
1029+
unregister();
1030+
};
1031+
},
1032+
};
1033+
},
1034+
});
10171035
await service.start(ctx);
10181036

10191037
expect(logShutdown).toHaveBeenCalledTimes(1);
10201038
expect(sdkShutdown).toHaveBeenCalledTimes(1);
1039+
expect(unregisterBridge).toHaveBeenCalledTimes(1);
10211040

10221041
telemetryState.tracer.startSpan.mockClear();
10231042
emitDiagnosticEvent({
@@ -1031,6 +1050,7 @@ describe("diagnostics-otel service", () => {
10311050
await service.stop?.(ctx);
10321051
expect(logShutdown).toHaveBeenCalledTimes(2);
10331052
expect(sdkShutdown).toHaveBeenCalledTimes(2);
1053+
expect(unregisterBridge).toHaveBeenCalledTimes(2);
10341054

10351055
telemetryState.tracer.startSpan.mockClear();
10361056
emitDiagnosticEvent({
@@ -1042,6 +1062,55 @@ describe("diagnostics-otel service", () => {
10421062
expect(telemetryState.tracer.startSpan).not.toHaveBeenCalled();
10431063
});
10441064

1065+
test("surfaces bridge cleanup failure after attempting every shutdown phase", async () => {
1066+
const cleanupError = new Error("bridge cleanup failed");
1067+
const unregisterBridge = vi.fn(() => {
1068+
throw cleanupError;
1069+
});
1070+
const cleanupOrder: string[] = [];
1071+
logShutdown.mockImplementationOnce(async () => {
1072+
cleanupOrder.push("log-provider");
1073+
});
1074+
sdkShutdown.mockImplementationOnce(async () => {
1075+
cleanupOrder.push("sdk-provider");
1076+
});
1077+
const service = createDiagnosticsOtelService();
1078+
const ctx = createOtelContext(OTEL_TEST_ENDPOINT, {
1079+
traces: true,
1080+
metrics: true,
1081+
logs: true,
1082+
});
1083+
const onEvent = ctx.internalDiagnostics!.onEvent;
1084+
ctx.internalDiagnostics = {
1085+
...ctx.internalDiagnostics!,
1086+
onEvent: (listener) => {
1087+
const unsubscribe = onEvent(listener);
1088+
return () => {
1089+
cleanupOrder.push("listener");
1090+
unsubscribe();
1091+
};
1092+
},
1093+
registerTracePropagationBridge: () => () => {
1094+
cleanupOrder.push("bridge");
1095+
unregisterBridge();
1096+
},
1097+
};
1098+
await service.start(ctx);
1099+
emitRunStarted();
1100+
const runSpan = spanByName("openclaw.run");
1101+
1102+
const stopError = await Promise.resolve(service.stop?.(ctx)).catch((error: unknown) => error);
1103+
1104+
expect(stopError).toBe(cleanupError);
1105+
expect(unregisterBridge).toHaveBeenCalledOnce();
1106+
expect(runSpan.end).toHaveBeenCalledOnce();
1107+
expect(logShutdown).toHaveBeenCalledOnce();
1108+
expect(sdkShutdown).toHaveBeenCalledOnce();
1109+
expect(unhandledRejectionHandlerState.getHandlers()).toEqual([]);
1110+
expect(cleanupOrder.indexOf("bridge")).toBeLessThan(cleanupOrder.indexOf("log-provider"));
1111+
expect(cleanupOrder.indexOf("listener")).toBeLessThan(cleanupOrder.indexOf("sdk-provider"));
1112+
});
1113+
10451114
test("attempts every provider shutdown and reports every failure", async () => {
10461115
const logError = new Error("log provider failed");
10471116
const sdkError = new Error("SDK providers failed");
@@ -1462,13 +1531,18 @@ describe("diagnostics-otel service", () => {
14621531
process.env.OTEL_EXPORTER_OTLP_PROTOCOL = "http/protobuf";
14631532
process.env.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL = "grpc";
14641533
process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL = "http/protobuf";
1534+
const registerBridge = vi.fn(() => vi.fn());
14651535

14661536
const { ctx } = await startOtelService({
14671537
traces: true,
14681538
metrics: true,
14691539
logs: false,
14701540
configure: (context) => {
14711541
delete context.config.diagnostics?.otel?.protocol;
1542+
context.internalDiagnostics = {
1543+
...context.internalDiagnostics!,
1544+
registerTracePropagationBridge: registerBridge,
1545+
};
14721546
},
14731547
});
14741548

@@ -1483,6 +1557,7 @@ describe("diagnostics-otel service", () => {
14831557
expect(ctx.logger.warn).toHaveBeenCalledWith(
14841558
"diagnostics-otel: unsupported traces protocol grpc; OTLP export disabled",
14851559
);
1560+
expect(registerBridge).not.toHaveBeenCalled();
14861561
});
14871562

14881563
test("keeps stdout logs active when the OTLP branch of both is unsupported", async () => {
@@ -4048,7 +4123,9 @@ describe("diagnostics-otel service", () => {
40484123
const modelTrace = createTestTrace(MODEL_CALL_SPAN_ID, CHILD_SPAN_ID);
40494124
const toolTrace = createTestTrace(TOOL_SPAN_ID, MODEL_CALL_SPAN_ID);
40504125
emitRunStarted({ trace: runTrace });
4051-
expect(formatDiagnosticTraceparent(modelTrace)).toBeUndefined();
4126+
expect(formatDiagnosticTraceparent(modelTrace)).toBe(
4127+
`00-${modelTrace.traceId}-${modelTrace.spanId}-01`,
4128+
);
40524129
emitTrustedDiagnosticEvent({
40534130
type: "model.call.started",
40544131
...MODEL_CALL_FIXTURE,
@@ -4059,7 +4136,7 @@ describe("diagnostics-otel service", () => {
40594136
const runSpanContext = spanByName("openclaw.run").spanContext();
40604137
expect(startedSpanParentContexts("openclaw.model.call")).toEqual([runSpanContext]);
40614138
expect(formatDiagnosticTraceparent(modelTrace)).toBe(
4062-
`00-${modelSpanContext.traceId}-${modelSpanContext.spanId}-01`,
4139+
`00-${modelTrace.traceId}-${modelTrace.spanId}-01`,
40634140
);
40644141

40654142
emitTrustedDiagnosticEvent({
@@ -4068,10 +4145,9 @@ describe("diagnostics-otel service", () => {
40684145
toolName: "read",
40694146
trace: toolTrace,
40704147
});
4071-
const toolSpanContext = spanByName("openclaw.tool.execution").spanContext();
40724148
expect(startedSpanParentContexts("openclaw.tool.execution")).toEqual([modelSpanContext]);
40734149
expect(formatDiagnosticTraceparent(toolTrace)).toBe(
4074-
`00-${toolSpanContext.traceId}-${toolSpanContext.spanId}-01`,
4150+
`00-${toolTrace.traceId}-${toolTrace.spanId}-01`,
40754151
);
40764152

40774153
await waitForDiagnosticEventsDrained();

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,9 @@ export function createDiagnosticsOtelService(): OpenClawPluginService {
418418
// then let the queued recorder reuse them instead of exporting duplicates.
419419
unregisterTracePropagationBridge =
420420
ctx.internalDiagnostics?.registerTracePropagationBridge?.({
421+
shouldPrepareEvent(event) {
422+
return event.type === "model.call.started" || event.type === "tool.execution.started";
423+
},
421424
prepareEvent(event, metadata) {
422425
if (event.type === "model.call.started") {
423426
recorders.recordModelCallStarted(event, metadata);

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

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
resetDiagnosticEventsForTest,
2020
setDiagnosticsEnabledForProcess,
2121
waitForDiagnosticEventsDrained,
22+
type DiagnosticEventMetadata,
2223
type DiagnosticEventPrivateData,
2324
type DiagnosticEventPayload,
2425
} from "./diagnostic-events.js";
@@ -28,6 +29,7 @@ import {
2829
runWithDiagnosticTraceContext,
2930
} from "./diagnostic-trace-context.js";
3031
import {
32+
type DiagnosticTracePropagationBridge,
3133
formatPropagatedDiagnosticTraceparent,
3234
registerDiagnosticTracePropagationBridge,
3335
} from "./diagnostic-trace-propagation.js";
@@ -275,7 +277,7 @@ describe("diagnostic-events", () => {
275277
).toBeUndefined();
276278
});
277279

278-
it("prepares trusted events synchronously and formats the resolved propagation context", async () => {
280+
it("prepares trusted events synchronously without cloning private data", async () => {
279281
const diagnosticTrace = createDiagnosticTraceContext({
280282
traceId: "4bf92f3577b34da6a3ce929d0e0e4736",
281283
spanId: "00f067aa0ba902b7",
@@ -287,22 +289,50 @@ describe("diagnostic-events", () => {
287289
traceFlags: "00",
288290
});
289291
const prepared: string[] = [];
290-
registerDiagnosticTracePropagationBridge({
292+
let privateDataReads = 0;
293+
const bridge: DiagnosticTracePropagationBridge<
294+
DiagnosticEventPayload,
295+
DiagnosticEventMetadata
296+
> = {
297+
shouldPrepareEvent(event) {
298+
return event.type === "model.call.started";
299+
},
291300
prepareEvent(event) {
292301
prepared.push(event.type);
293302
},
294303
resolveTraceContext(traceContext) {
295304
expect(traceContext).toBe(diagnosticTrace);
296305
return exportedTrace;
297306
},
298-
});
307+
};
308+
registerDiagnosticTracePropagationBridge(bridge);
299309

310+
emitTrustedDiagnosticEventWithPrivateData(
311+
{
312+
type: "model.call.started",
313+
runId: "run-1",
314+
callId: "call-1",
315+
provider: "openai",
316+
model: "gpt-5.4",
317+
trace: diagnosticTrace,
318+
},
319+
{
320+
modelContent: {
321+
get inputMessages() {
322+
privateDataReads += 1;
323+
return ["secret prompt"];
324+
},
325+
},
326+
},
327+
);
328+
expect(privateDataReads).toBe(0);
300329
emitTrustedDiagnosticEvent({
301-
type: "model.call.started",
330+
type: "model.call.completed",
302331
runId: "run-1",
303332
callId: "call-1",
304333
provider: "openai",
305334
model: "gpt-5.4",
335+
durationMs: 1,
306336
trace: diagnosticTrace,
307337
});
308338

@@ -314,6 +344,7 @@ describe("diagnostic-events", () => {
314344
`00-${exportedTrace.traceId}-${exportedTrace.spanId}-00`,
315345
);
316346
await waitForDiagnosticEventsDrained();
347+
expect(privateDataReads).toBe(0);
317348
});
318349

319350
it("does not fall back to diagnostic ids when an active propagation bridge misses", () => {
@@ -326,6 +357,9 @@ describe("diagnostic-events", () => {
326357
resolveTraceContext: () => undefined,
327358
});
328359

360+
expect(formatDiagnosticTraceparent(diagnosticTrace)).toBe(
361+
`00-${diagnosticTrace.traceId}-${diagnosticTrace.spanId}-01`,
362+
);
329363
expect(formatPropagatedDiagnosticTraceparent(diagnosticTrace)).toBeUndefined();
330364
});
331365

0 commit comments

Comments
 (0)