Skip to content

Commit 4db44c6

Browse files
authored
fix(diagnostics): close lifecycle spans reliably (#119791)
1 parent 2436a13 commit 4db44c6

4 files changed

Lines changed: 119 additions & 55 deletions

File tree

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

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
5757
...(evt.toolOwner ? { "openclaw.tool.owner": normalizeDiagnosticValue(evt.toolOwner) } : {}),
5858
...paramsSummaryAttrs(evt.paramsSummary),
5959
});
60+
const toolTimestampMs = (evt: { sourceTimestampMs?: number; ts: number }) =>
61+
evt.sourceTimestampMs ?? evt.ts;
6062

6163
const skillUsedAttrs = (
6264
evt: Extract<DiagnosticEventPayload, { type: "skill.used" }>,
@@ -110,7 +112,7 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
110112
metadata,
111113
spanWithDuration("openclaw.tool.execution", spanAttrs, undefined, {
112114
parentContext: activeTrustedParentContext(evt, metadata),
113-
startTimeMs: evt.ts,
115+
startTimeMs: toolTimestampMs(evt),
114116
}),
115117
).spanContext();
116118
};
@@ -133,10 +135,10 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
133135
takeTrackedTrustedSpan(evt, metadata) ??
134136
spanWithDuration("openclaw.tool.execution", spanAttrs, evt.durationMs, {
135137
parentContext: activeTrustedParentContext(evt, metadata),
136-
endTimeMs: evt.ts,
138+
endTimeMs: toolTimestampMs(evt),
137139
});
138140
setSpanAttrs(span, spanAttrs);
139-
span.end(evt.ts);
141+
span.end(toolTimestampMs(evt));
140142
};
141143

142144
const recordToolExecutionError = (
@@ -163,14 +165,14 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
163165
takeTrackedTrustedSpan(evt, metadata) ??
164166
spanWithDuration("openclaw.tool.execution", spanAttrs, evt.durationMs, {
165167
parentContext: activeTrustedParentContext(evt, metadata),
166-
endTimeMs: evt.ts,
168+
endTimeMs: toolTimestampMs(evt),
167169
});
168170
setSpanAttrs(span, spanAttrs);
169171
span.setStatus({
170172
code: SpanStatusCode.ERROR,
171173
message: redactSensitiveText(evt.errorCategory),
172174
});
173-
span.end(evt.ts);
175+
span.end(toolTimestampMs(evt));
174176
};
175177

176178
const recordToolExecutionBlocked = (
@@ -191,12 +193,14 @@ export function createToolAndSystemRecorders(runtime: DiagnosticsRecorderRuntime
191193
};
192194
addRunAttrs(spanAttrs, evt);
193195
assignOtelToolIdentityAttributes(spanAttrs, evt);
194-
const span = spanWithDuration("openclaw.tool.execution", spanAttrs, 0, {
195-
parentContext: activeTrustedParentContext(evt, metadata),
196-
endTimeMs: evt.ts,
197-
});
196+
const span =
197+
takeTrackedTrustedSpan(evt, metadata) ??
198+
spanWithDuration("openclaw.tool.execution", spanAttrs, 0, {
199+
parentContext: activeTrustedParentContext(evt, metadata),
200+
endTimeMs: toolTimestampMs(evt),
201+
});
198202
setSpanAttrs(span, spanAttrs);
199-
span.end(evt.ts);
203+
span.end(toolTimestampMs(evt));
200204
};
201205

202206
const recordPayloadLarge = (evt: Extract<DiagnosticEventPayload, { type: "payload.large" }>) => {

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3525,6 +3525,71 @@ describe("diagnostics-otel service", () => {
35253525
expect(telemetryState.tracer.setSpanContext).not.toHaveBeenCalled();
35263526
});
35273527

3528+
test("closes a tracked blocked tool span once without creating a duplicate", async () => {
3529+
await startOtelService({ traces: true, metrics: true });
3530+
3531+
emitTrustedDiagnosticEvent({
3532+
type: "tool.execution.started",
3533+
runId: "run-blocked",
3534+
toolName: "exec",
3535+
toolCallId: "call-blocked",
3536+
sourceTimestampMs: 1_000,
3537+
trace: createTestTrace(TOOL_SPAN_ID, CHILD_SPAN_ID),
3538+
});
3539+
await emitTrustedAndFlush({
3540+
type: "tool.execution.blocked",
3541+
runId: "run-blocked",
3542+
toolName: "exec",
3543+
toolCallId: "call-blocked",
3544+
deniedReason: "tools.deny",
3545+
reason: "policy denied",
3546+
sourceTimestampMs: 1_250,
3547+
trace: createTestTrace(TOOL_SPAN_ID, CHILD_SPAN_ID),
3548+
});
3549+
3550+
const toolSpans = telemetryState.spans.filter(
3551+
(span) => span.name === "openclaw.tool.execution",
3552+
);
3553+
expect(toolSpans).toHaveLength(1);
3554+
expect(startedSpanOptions("openclaw.tool.execution")?.startTime).toBe(1_000);
3555+
expect(toolSpans[0]?.end).toHaveBeenCalledTimes(1);
3556+
expect(toolSpans[0]?.end).toHaveBeenCalledWith(1_250);
3557+
});
3558+
3559+
test("uses authoritative source timestamps for terminal-only tool spans", async () => {
3560+
await startOtelService({ traces: true, metrics: true });
3561+
3562+
emitTrustedDiagnosticEvent({
3563+
type: "tool.execution.completed",
3564+
runId: "run-completed",
3565+
toolName: "read",
3566+
toolCallId: "call-completed",
3567+
durationMs: 250,
3568+
sourceTimestampMs: 5_000,
3569+
});
3570+
await emitTrustedAndFlush({
3571+
type: "tool.execution.error",
3572+
runId: "run-error",
3573+
toolName: "write",
3574+
toolCallId: "call-error",
3575+
durationMs: 500,
3576+
errorCategory: "test",
3577+
sourceTimestampMs: 7_000,
3578+
});
3579+
3580+
const toolSpanCalls = telemetryState.tracer.startSpan.mock.calls.filter(
3581+
(call) => call[0] === "openclaw.tool.execution",
3582+
);
3583+
const toolSpans = telemetryState.spans.filter(
3584+
(span) => span.name === "openclaw.tool.execution",
3585+
);
3586+
expect(toolSpanCalls).toHaveLength(2);
3587+
expect((toolSpanCalls[0]?.[1] as { startTime?: number } | undefined)?.startTime).toBe(4_750);
3588+
expect((toolSpanCalls[1]?.[1] as { startTime?: number } | undefined)?.startTime).toBe(6_500);
3589+
expect(toolSpans[0]?.end).toHaveBeenCalledWith(5_000);
3590+
expect(toolSpans[1]?.end).toHaveBeenCalledWith(7_000);
3591+
});
3592+
35283593
test("exports model failover spans", async () => {
35293594
await startOtelService({ traces: true });
35303595

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

Lines changed: 34 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -864,19 +864,34 @@ describe("diagnostic-events", () => {
864864
).toBe(true);
865865
});
866866

867-
it("preserves trusted terminal tool diagnostics when the async queue is full", async () => {
867+
it("preserves trusted lifecycle terminals when the async queue is full", async () => {
868868
const events: DiagnosticEventPayload[] = [];
869869
onInternalDiagnosticEvent((event) => {
870870
events.push(event);
871871
});
872+
const model = {
873+
runId: "run-model",
874+
callId: "call-model",
875+
provider: "openai",
876+
model: "gpt-5.4",
877+
};
878+
const harness = { runId: "run-harness", harnessId: "harness" };
879+
const terminalEvents: Array<Parameters<typeof emitTrustedDiagnosticEvent>[0]> = [
880+
{ type: "tool.execution.completed", toolName: "exec", durationMs: 1 },
881+
{ type: "tool.execution.error", toolName: "exec", durationMs: 1, errorCategory: "test" },
882+
{ type: "model.call.completed", ...model, durationMs: 1 },
883+
{ type: "model.call.error", ...model, durationMs: 1, errorCategory: "test" },
884+
{ type: "harness.run.completed", ...harness, durationMs: 1, outcome: "completed" },
885+
{
886+
type: "harness.run.error",
887+
...harness,
888+
durationMs: 1,
889+
phase: "resolve",
890+
errorCategory: "test",
891+
},
892+
];
872893

873-
emitTrustedDiagnosticEvent({
874-
type: "tool.execution.completed",
875-
runId: "run-saturation-first",
876-
toolName: "exec",
877-
toolCallId: "call-saturation-first",
878-
durationMs: 1,
879-
});
894+
emitTrustedDiagnosticEvent(terminalEvents[0]!);
880895

881896
for (let index = 0; index < 9_999; index += 1) {
882897
emitDiagnosticEvent({
@@ -887,52 +902,26 @@ describe("diagnostic-events", () => {
887902
model: "gpt-5.4",
888903
});
889904
}
890-
891-
emitTrustedDiagnosticEvent({
892-
type: "tool.execution.error",
893-
runId: "run-saturation-second",
894-
toolName: "exec",
895-
toolCallId: "call-saturation-second",
896-
durationMs: 1,
897-
errorCategory: "test",
898-
});
905+
for (const terminalEvent of terminalEvents.slice(1)) {
906+
emitTrustedDiagnosticEvent(terminalEvent);
907+
}
899908

900909
expect(
901910
hasPendingInternalDiagnosticEvent(
902-
(event, metadata) =>
903-
metadata.trusted &&
904-
event.type === "tool.execution.error" &&
905-
event.toolCallId === "call-saturation-second",
911+
(event, metadata) => metadata.trusted && event.type === "harness.run.error",
906912
),
907913
).toBe(true);
908914

909915
await waitForDiagnosticEventsDrained();
910916

917+
for (const terminalEvent of terminalEvents) {
918+
expect(events).toContainEqual(expect.objectContaining(terminalEvent));
919+
}
911920
expect(
912-
events
913-
.filter(
914-
(
915-
event,
916-
): event is Extract<
917-
DiagnosticEventPayload,
918-
{ type: "tool.execution.completed" | "tool.execution.error" }
919-
> => event.type === "tool.execution.completed" || event.type === "tool.execution.error",
920-
)
921-
.map((event) => ({
922-
type: event.type,
923-
toolCallId: event.toolCallId,
924-
})),
925-
).toEqual([
926-
{
927-
type: "tool.execution.completed",
928-
toolCallId: "call-saturation-first",
929-
},
930-
{
931-
type: "tool.execution.error",
932-
toolCallId: "call-saturation-second",
933-
},
934-
]);
935-
expect(events.filter((event) => event.type === "model.call.started")).toHaveLength(9_998);
921+
events.filter(
922+
(event) => event.type === "model.call.started" && event.runId.startsWith("saturation-run-"),
923+
),
924+
).toHaveLength(9_994);
936925
});
937926

938927
it("emits a bounded summary when async diagnostics are dropped at saturation", async () => {

‎src/infra/diagnostic-events.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -958,9 +958,15 @@ const ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set<DiagnosticEventPayload["type"]>([
958958
"log.record",
959959
]);
960960
const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set<DiagnosticEventPayload["type"]>([
961+
// Trusted lifecycle terminals must displace best-effort diagnostics; dropping one
962+
// can strand the recorder's active span after its producer already finished.
961963
"tool.execution.completed",
962964
"tool.execution.error",
963965
"tool.execution.blocked",
966+
"model.call.completed",
967+
"model.call.error",
968+
"harness.run.completed",
969+
"harness.run.error",
964970
]);
965971

966972
function createDiagnosticEventsState(): DiagnosticEventsGlobalState {

0 commit comments

Comments
 (0)