fix(diagnostics): chain run traces to request scope

This commit is contained in:
Vincent Koc
2026-04-26 13:57:46 -07:00
parent 3ae6f01d61
commit 410783c126
3 changed files with 42 additions and 2 deletions

View File

@@ -12,8 +12,8 @@ import { filterHeartbeatPairs } from "../../../auto-reply/heartbeat-filter.js";
import { resolveChannelCapabilities } from "../../../config/channel-capabilities.js";
import { emitTrustedDiagnosticEvent } from "../../../infra/diagnostic-events.js";
import {
createDiagnosticTraceContext,
createChildDiagnosticTraceContext,
createDiagnosticTraceContextFromActiveScope,
freezeDiagnosticTraceContext,
} from "../../../infra/diagnostic-trace-context.js";
import { isEmbeddedMode } from "../../../infra/embedded-mode.js";
@@ -648,7 +648,9 @@ export async function runEmbeddedAttempt(
const sessionLabel = params.sessionKey ?? params.sessionId;
const contextInjectionMode = resolveContextInjectionMode(params.config);
const agentDir = params.agentDir ?? resolveOpenClawAgentDir();
const diagnosticTrace = freezeDiagnosticTraceContext(createDiagnosticTraceContext());
const diagnosticTrace = freezeDiagnosticTraceContext(
createDiagnosticTraceContextFromActiveScope(),
);
const runTrace = freezeDiagnosticTraceContext(
createChildDiagnosticTraceContext(diagnosticTrace),
);

View File

@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import {
createChildDiagnosticTraceContext,
createDiagnosticTraceContext,
createDiagnosticTraceContextFromActiveScope,
freezeDiagnosticTraceContext,
formatDiagnosticTraceparent,
getActiveDiagnosticTraceContext,
@@ -158,4 +159,31 @@ describe("diagnostic-trace-context", () => {
expect(getActiveDiagnosticTraceContext()).toBeUndefined();
});
it("creates child trace contexts from the active request scope", () => {
const requestTrace = createDiagnosticTraceContext({
traceId: TRACE_ID,
spanId: SPAN_ID,
traceFlags: "00",
});
runWithDiagnosticTraceContext(requestTrace, () => {
const scoped = createDiagnosticTraceContextFromActiveScope({
spanId: CHILD_SPAN_ID,
});
expect(scoped).toEqual({
traceId: TRACE_ID,
spanId: CHILD_SPAN_ID,
parentSpanId: SPAN_ID,
traceFlags: "00",
});
});
expect(createDiagnosticTraceContextFromActiveScope({ spanId: CHILD_SPAN_ID })).toEqual({
traceId: expect.stringMatching(/^[0-9a-f]{32}$/),
spanId: CHILD_SPAN_ID,
traceFlags: "01",
});
});
});

View File

@@ -198,6 +198,16 @@ export function createChildDiagnosticTraceContext(
});
}
export function createDiagnosticTraceContextFromActiveScope(
input: Omit<DiagnosticTraceContextInput, "traceId" | "traceparent"> = {},
): DiagnosticTraceContext {
const active = getActiveDiagnosticTraceContext();
if (!active) {
return createDiagnosticTraceContext(input);
}
return createChildDiagnosticTraceContext(active, input);
}
export function freezeDiagnosticTraceContext(
context: DiagnosticTraceContext,
): DiagnosticTraceContext {