Skip to content

Commit f1ee2a3

Browse files
authored
fix(diagnostics-otel): agent turns split into one-span traces instead of a trace tree (#116246)
* fix(diagnostics-otel): keep parent span links across long turns Retained trusted span contexts translate a completed lifecycle span's diagnostic span id to the real OTel span context. That table was evicted 5s after run.completed, so children of a longer turn missed their parent and OTel minted a fresh trace id for each one, silently splitting a turn into single-span traces. Retention is now identity-based and lives for the service lifetime, bounded by MAX_RETAINED_TRUSTED_SPAN_CONTEXTS, which removes the timing race and the drain/timeout cleanup subsystem. Also nests openclaw.exec under its run: the exec event now carries a trusted trace context and the recorder resolves the ambient run scope. * fix(diagnostics-otel): key retained span contexts by diagnostic trace id Retained lifecycle span contexts were stored under the span's OTel trace id but looked up with the event's diagnostic trace id. Those are different id spaces, so every post-completion parent lookup missed and each straggler span started a brand-new trace. The mocked suite could not catch this: its tracer reports the same trace id the test feeds in, collapsing both id spaces into one value. Adds a boundary test that runs the real OTel SDK and OTLP/protobuf exporter against a local receiver and asserts on exported span bytes. * fix(diagnostics-otel): harden span-linking contract after review Review findings on the parent-span linking fix: - completeTrackedLifecycleSpan now takes the DiagnosticTraceContext instead of a bare trace id beside a span id. Two adjacent hex strings let a transposition compile clean and silently reinstate split traces; DiagnosticTraceContext is the only shape an OTel SpanContext cannot satisfy (traceFlags string vs number). - internalOrTrustedTraceContext composes normalizedTrustedTraceContext rather than spelling the trust predicate a third time. - Corrected comments that claimed OTel ids never equal diagnostic ids. Spans parented from an upstream traceparent do adopt the diagnostic trace id; the removed guard only ever misfired on root lifecycle spans. - Exec comment now states the real parent: the openclaw harness opens no run scope, so exec nests under openclaw.harness.run. Test gaps closed: - The core emitter switch was untested; reverting it kept every test green. The pty-fallback test now asserts the emitted metadata. - The boundary test covered only run.completed of three lifecycle owners; it now covers harness.run.completed and message.processed too, each with a straggler. - Dropped the service-context cast for the typed helper, which caught a bogus context.assembled field, and moved teardown into afterEach so a failed assertion cannot leak the real NodeSDK across files. - Scoped the one-trace assertion to this turn's spans; faked Date so a lazy Date.now expiry cannot pass. Docs: exec and tool spans now listed as staying on an upstream request trace. * fix(diagnostics-otel): keep late children on the trace on every terminator Native review found three correctness gaps in the previous commit: - Exec spans could be exported naming a parent span id nothing ever emits. The ambient lookup fell through to a remote-parent fallback built from diagnostic ids, which is a regression from the previous clean-root behavior and breaks waterfalls and parent-id-keyed backends. Exec now resolves only spans this process exported and stays a root on a miss; message spans keep the remote fallback because their context can come from an inbound traceparent. - harness.run.error never retained its span context, so an aborted turn still split. For the openclaw harness that span is the only ancestor a late child has, and aborted turns emit no run.completed. - completeTrackedLifecycleSpan no longer takes a redundant spanId. The boundary test now runs through the OPENCLAW_OTEL_PRELOADED seam with an in-memory exporter and releases the global tracer provider in teardown. A NodeSDK cannot be unregistered, so the old version would have made any later real-SDK test silently export nothing. That also deletes the hand-rolled OTLP protobuf decoder. Added guards for the aborted-turn path and for exec staying parentless; both are mutation-verified. * fix(diagnostics-otel): age retained parent contexts out after 10 minutes Retention had no time bound at all, so a command backgrounded by a turn could finish hours later and still attach to a parent that ended long before. Backends derive trace latency from the span envelope, so a 30s turn rendered as hours with a child extending past its parent. The horizon is checked lazily on lookup rather than on a timer: a timer firing mid-turn is exactly what silently split traces before. Past the horizon a straggler starts its own trace, which only loses causality for a span that would have skewed its parent's duration anyway. The two bounds now pin each other - shrinking the horizon to the old 5s window fails the original regression tests, and removing it fails the new horizon test. * fix(diagnostics-otel): retain parent contexts until capacity
1 parent dbe7140 commit f1ee2a3

12 files changed

Lines changed: 437 additions & 85 deletions

‎docs/gateway/opentelemetry.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,11 @@ each request frame:
130130
```
131131

132132
The Gateway creates a child request context that preserves the upstream trace
133-
ID and sampling flags. Agent, harness, model-call, and provider spans created
134-
inside the request remain on that trace. This allows a local experiment runner
135-
to create one Langfuse/OpenTelemetry trace per dataset item and correlate the
136-
corresponding OpenClaw execution.
133+
ID and sampling flags. Agent, harness, model-call, provider, tool-execution, and
134+
exec spans created inside the request remain on that trace, including spans
135+
recorded after their parent run has already finished. This allows a local
136+
experiment runner to create one Langfuse/OpenTelemetry trace per dataset item and
137+
correlate the corresponding OpenClaw execution.
137138

138139
Trace context is request-scoped, not connection-scoped. On a long-lived
139140
WebSocket, generate or inject the appropriate `traceparent` independently for

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,3 @@ export const CONTEXT_TOKENS_BUCKETS = [
8383
2_000_000,
8484
];
8585
export const MAX_RETAINED_TRUSTED_SPAN_CONTEXTS = 1024;
86-
export const RETAINED_TRUSTED_SPAN_CONTEXT_TIMEOUT_MS = 5_000;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ export function createDiagnosticsEventHandler(params: {
202202
recordSkillUsed(evt, metadata);
203203
return;
204204
case "exec.process.completed":
205-
recordExecProcessCompleted(evt);
205+
recordExecProcessCompleted(evt, metadata);
206206
break;
207207
case "exec.approval.followup_suppressed":
208208
break;

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ export function createHarnessRecorders(runtime: DiagnosticsRecorderRuntime) {
1818
trustedTraceContext,
1919
activeTrustedParentContext,
2020
trackTrustedSpan,
21-
takeTrackedTrustedSpan,
2221
setSpanAttrs,
2322
completeTrackedLifecycleSpan,
2423
addRunAttrs,
@@ -103,7 +102,7 @@ export function createHarnessRecorders(runtime: DiagnosticsRecorderRuntime) {
103102
});
104103
}
105104
if (trackedSpan && trustedTrace?.spanId) {
106-
completeTrackedLifecycleSpan(trustedTrace.spanId, trackedSpan, evt.ts);
105+
completeTrackedLifecycleSpan(trustedTrace, trackedSpan, evt.ts);
107106
return;
108107
}
109108
span.end(evt.ts);
@@ -132,8 +131,12 @@ export function createHarnessRecorders(runtime: DiagnosticsRecorderRuntime) {
132131
...(redactedError ? { "openclaw.error": redactedError } : {}),
133132
...(evt.cleanupFailed ? { "openclaw.harness.cleanup_failed": true } : {}),
134133
};
134+
const trustedTrace = trustedTraceContext(evt, metadata);
135+
const trackedSpan = trustedTrace?.spanId
136+
? activeTrustedSpans.get(trustedTrace.spanId)
137+
: undefined;
135138
const span =
136-
takeTrackedTrustedSpan(evt, metadata) ??
139+
trackedSpan ??
137140
spanWithDuration("openclaw.harness.run", spanAttrs, evt.durationMs, {
138141
parentContext: activeTrustedParentContext(evt, metadata),
139142
endTimeMs: evt.ts,
@@ -143,6 +146,12 @@ export function createHarnessRecorders(runtime: DiagnosticsRecorderRuntime) {
143146
code: SpanStatusCode.ERROR,
144147
message: redactedError ?? errorType,
145148
});
149+
// Retain on the error path too: for the openclaw harness this span is the only
150+
// ancestor a late child can attach to, and aborted turns emit no run.completed.
151+
if (trackedSpan && trustedTrace?.spanId) {
152+
completeTrackedLifecycleSpan(trustedTrace, trackedSpan, evt.ts);
153+
return;
154+
}
146155
span.end(evt.ts);
147156
};
148157

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ export function createOperationsRecorders(runtime: DiagnosticsRecorderRuntime) {
326326
});
327327
}
328328
if (trackedSpan && trustedTrace?.spanId) {
329-
completeTrackedLifecycleSpan(trustedTrace.spanId, trackedSpan, evt.ts);
329+
completeTrackedLifecycleSpan(trustedTrace, trackedSpan, evt.ts);
330330
return;
331331
}
332332
span.end(evt.ts);

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
2828
telemetryExporterCounter,
2929
spanWithDuration,
3030
activeTrustedParentContext,
31+
exportedInternalOrTrustedContext,
3132
trackTrustedSpan,
3233
takeTrackedTrustedSpan,
3334
setSpanAttrs,
@@ -208,6 +209,7 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
208209

209210
const recordExecProcessCompleted = (
210211
evt: Extract<DiagnosticEventPayload, { type: "exec.process.completed" }>,
212+
metadata: DiagnosticEventMetadata,
211213
) => {
212214
const attrs: Record<string, string | number> = {
213215
"openclaw.exec.target": evt.target,
@@ -236,7 +238,13 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
236238
spanAttrs["openclaw.exec.timed_out"] = evt.timedOut;
237239
}
238240

241+
// Exec events carry the innermost ambient scope rather than a child context, so
242+
// the parent is looked up by the event's own span id first. For the openclaw
243+
// harness that scope is the harness run (no run scope is opened -
244+
// shouldEmitAgentRunDiagnostics is false there), so the parent is
245+
// openclaw.harness.run; other harnesses open a run scope and parent to openclaw.run.
239246
const span = spanWithDuration("openclaw.exec", spanAttrs, evt.durationMs, {
247+
parentContext: exportedInternalOrTrustedContext(evt, metadata),
240248
endTimeMs: evt.ts,
241249
});
242250
if (evt.outcome === "failed") {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ export function createUsageRecorders(runtime: DiagnosticsRecorderRuntime) {
283283
}
284284
const traceContext = internalOrTrustedTraceContext(evt, metadata);
285285
if (trackedSpan && traceContext?.spanId) {
286-
completeTrackedLifecycleSpan(traceContext.spanId, trackedSpan, evt.ts);
286+
completeTrackedLifecycleSpan(traceContext, trackedSpan, evt.ts);
287287
return;
288288
}
289289
span.end(evt.ts);

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

Lines changed: 45 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,18 @@ import {
55
type SpanKind,
66
type Tracer,
77
} from "@opentelemetry/api";
8-
import { waitForDiagnosticEventsDrained } from "openclaw/plugin-sdk/diagnostic-runtime";
98
import type {
109
DiagnosticEventMetadata,
1110
DiagnosticEventPayload,
1211
DiagnosticTraceContext,
1312
} from "../api.js";
1413
import { redactOtelAttributes } from "./service-attributes.js";
14+
import { MAX_RETAINED_TRUSTED_SPAN_CONTEXTS } from "./service-constants.js";
1515
import {
16-
MAX_RETAINED_TRUSTED_SPAN_CONTEXTS,
17-
RETAINED_TRUSTED_SPAN_CONTEXT_TIMEOUT_MS,
18-
} from "./service-constants.js";
19-
import { contextForTraceContext, normalizeTraceContext } from "./service-trace-context.js";
16+
contextForTraceContext,
17+
normalizedTrustedTraceContext,
18+
normalizeTraceContext,
19+
} from "./service-trace-context.js";
2020
import type { TrustedSpanAliasOwner } from "./service-types.js";
2121

2222
export function createDiagnosticsTraceRuntime(tracer: Tracer) {
@@ -25,17 +25,15 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
2525
string,
2626
{ span: ReturnType<typeof tracer.startSpan>; spanId: string; owner: TrustedSpanAliasOwner }
2727
>();
28+
// Keeps a completed lifecycle span's real OTel context for late children.
29+
// Ended contexts remain valid parents without changing their span duration.
30+
// Entries live until capacity eviction or service stop.
2831
const retainedTrustedSpanContexts = new Map<
2932
string,
30-
{ spanContext: SpanContext; retentionMarker: symbol; owner?: TrustedSpanAliasOwner }
33+
{ spanContext: SpanContext; owner?: TrustedSpanAliasOwner }
3134
>();
32-
const retainedTrustedSpanContextCleanupTimers = new Set<ReturnType<typeof setTimeout>>();
3335
const stopActiveTrustedSpans = () => {
3436
const stopAt = Date.now();
35-
for (const handle of retainedTrustedSpanContextCleanupTimers) {
36-
clearTimeout(handle);
37-
}
38-
retainedTrustedSpanContextCleanupTimers.clear();
3937
retainedTrustedSpanContexts.clear();
4038
for (const span of new Set([
4139
...activeTrustedSpans.values(),
@@ -79,10 +77,16 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
7977
};
8078
const trustedTraceContext = (evt: DiagnosticEventPayload, metadata: DiagnosticEventMetadata) =>
8179
metadata.trusted ? normalizeTraceContext(evt.trace) : undefined;
80+
// Internal-dispatcher events are linkable on their own; everything else defers to
81+
// the shared trusted-trace-context rule, which also accepts an untrusted payload
82+
// whose trace context came from OpenClaw-owned scope (metadata.trustedTraceContext).
8283
const internalOrTrustedTraceContext = (
8384
evt: DiagnosticEventPayload,
8485
metadata: DiagnosticEventMetadata,
85-
) => (metadata.trusted || metadata.internal ? normalizeTraceContext(evt.trace) : undefined);
86+
) =>
87+
metadata.internal
88+
? normalizeTraceContext(evt.trace)
89+
: normalizedTrustedTraceContext(evt, metadata);
8690
const trustedSpanAliasOwner = (
8791
evt: DiagnosticEventPayload,
8892
): TrustedSpanAliasOwner | undefined => {
@@ -117,7 +121,9 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
117121
)
118122
: undefined) ??
119123
retainedTrustedSpanContexts.get(retainedTrustedSpanContextKey(traceContext.traceId, spanId));
120-
if (retained?.spanContext.traceId !== traceContext.traceId) {
124+
// Keys carry the diagnostic trace id, so a hit is already trace-correct; comparing
125+
// against the stored OTel trace id would wrongly reject root lifecycle spans.
126+
if (!retained) {
121127
return undefined;
122128
}
123129
if (retained.owner && !sameTrustedSpanAliasOwner(retained.owner, owner)) {
@@ -182,7 +188,9 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
182188
}
183189
return trace.setSpanContext(otelContextApi.active(), spanContext);
184190
};
185-
const activeInternalOrTrustedContext = (
191+
// Resolves only spans this process actually exported, so a miss leaves the caller
192+
// parentless rather than pointing at a span id no backend will ever receive.
193+
const exportedInternalOrTrustedContext = (
186194
evt: DiagnosticEventPayload,
187195
metadata: DiagnosticEventMetadata,
188196
) => {
@@ -206,11 +214,18 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
206214
const retainedSpanContext =
207215
retainedTrustedSpanContext(traceContext, traceContext.spanId, owner) ??
208216
retainedTrustedSpanContext(traceContext, traceContext.parentSpanId, owner);
209-
if (retainedSpanContext) {
210-
return trace.setSpanContext(otelContextApi.active(), retainedSpanContext);
211-
}
212-
return internalOrTrustedParentContext(evt, metadata);
217+
return retainedSpanContext
218+
? trace.setSpanContext(otelContextApi.active(), retainedSpanContext)
219+
: undefined;
213220
};
221+
// Message spans additionally accept a remote parent, because their trace context can
222+
// come from an inbound traceparent whose span really does live in another process.
223+
const activeInternalOrTrustedContext = (
224+
evt: DiagnosticEventPayload,
225+
metadata: DiagnosticEventMetadata,
226+
) =>
227+
exportedInternalOrTrustedContext(evt, metadata) ??
228+
internalOrTrustedParentContext(evt, metadata);
214229
const trackTrustedSpan = (
215230
evt: DiagnosticEventPayload,
216231
metadata: DiagnosticEventMetadata,
@@ -267,14 +282,13 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
267282
traceId: string,
268283
spanId: string,
269284
spanContext: SpanContext,
270-
retentionMarker: symbol,
271285
owner?: TrustedSpanAliasOwner,
272286
) => {
273287
retainedTrustedSpanContexts.set(retainedTrustedSpanContextKey(traceId, spanId, owner), {
274288
spanContext,
275-
retentionMarker,
276289
...(owner ? { owner } : {}),
277290
});
291+
// Map iteration is insertion-ordered, so this removes the oldest mapping first.
278292
while (retainedTrustedSpanContexts.size > MAX_RETAINED_TRUSTED_SPAN_CONTEXTS) {
279293
const oldestKey = retainedTrustedSpanContexts.keys().next().value;
280294
if (!oldestKey) {
@@ -283,44 +297,19 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
283297
retainedTrustedSpanContexts.delete(oldestKey);
284298
}
285299
};
286-
const scheduleRetainedTrustedSpanContextCleanup = (retentionMarker: symbol) => {
287-
let drainHandle: ReturnType<typeof setTimeout> | undefined;
288-
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
289-
const cleanup = () => {
290-
if (drainHandle) {
291-
clearTimeout(drainHandle);
292-
retainedTrustedSpanContextCleanupTimers.delete(drainHandle);
293-
drainHandle = undefined;
294-
}
295-
if (timeoutHandle) {
296-
clearTimeout(timeoutHandle);
297-
retainedTrustedSpanContextCleanupTimers.delete(timeoutHandle);
298-
timeoutHandle = undefined;
299-
}
300-
for (const [key, retained] of retainedTrustedSpanContexts) {
301-
if (retained.retentionMarker === retentionMarker) {
302-
retainedTrustedSpanContexts.delete(key);
303-
}
304-
}
305-
};
306-
drainHandle = setTimeout(() => {
307-
if (drainHandle) {
308-
retainedTrustedSpanContextCleanupTimers.delete(drainHandle);
309-
drainHandle = undefined;
310-
}
311-
void waitForDiagnosticEventsDrained().then(cleanup, cleanup);
312-
}, 0);
313-
(drainHandle as { unref?: () => void }).unref?.();
314-
retainedTrustedSpanContextCleanupTimers.add(drainHandle);
315-
timeoutHandle = setTimeout(cleanup, RETAINED_TRUSTED_SPAN_CONTEXT_TIMEOUT_MS);
316-
(timeoutHandle as { unref?: () => void }).unref?.();
317-
retainedTrustedSpanContextCleanupTimers.add(timeoutHandle);
318-
};
300+
// Retention keys on the diagnostic ids the event carries. Taking the whole context
301+
// (not a bare trace id) makes an OTel SpanContext a type error here; keying by OTel
302+
// ids instead would silently split every late child into its own trace.
319303
const completeTrackedLifecycleSpan = (
320-
spanId: string,
304+
traceContext: DiagnosticTraceContext,
321305
span: ReturnType<typeof tracer.startSpan>,
322306
endTimeMs: number,
323307
) => {
308+
const spanId = traceContext.spanId;
309+
if (!spanId) {
310+
span.end(endTimeMs);
311+
return;
312+
}
324313
const spanContext = span.spanContext();
325314
const retainedKeys: Array<{ spanId: string; owner?: TrustedSpanAliasOwner }> = [{ spanId }];
326315
const retainedAliasKeys: string[] = [];
@@ -339,17 +328,14 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
339328
}
340329
}
341330
span.end(endTimeMs);
342-
const retentionMarker = Symbol("retainedTrustedSpanContext");
343331
for (const retainedKey of retainedKeys) {
344332
retainTrustedSpanContext(
345-
spanContext.traceId,
333+
traceContext.traceId,
346334
retainedKey.spanId,
347335
spanContext,
348-
retentionMarker,
349336
retainedKey.owner,
350337
);
351338
}
352-
scheduleRetainedTrustedSpanContextCleanup(retentionMarker);
353339
};
354340

355341
const addRunAttrs = (
@@ -402,6 +388,7 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
402388
internalOrTrustedExplicitParentContext,
403389
activeTrustedParentContext,
404390
activeInternalOrTrustedContext,
391+
exportedInternalOrTrustedContext,
405392
trackTrustedSpan,
406393
trackInternalOrTrustedSpan,
407394
takeTrackedTrustedSpan,

0 commit comments

Comments
 (0)