Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(trpc): attach OTEL trace id to error responses (#17253)

Niklas Semmler965b0dfc00cf
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.ts
index a4fa34d43d..393847ed42 100644
--- a/packages/shared/src/server/instrumentation/index.ts
+++ b/packages/shared/src/server/instrumentation/index.ts
@@ -123,6 +123,14 @@ export function instrumentSync<T>(
export const getCurrentSpan = () => opentelemetry.trace.getActiveSpan();
+export const getActiveTraceId = () => {
+ const span = opentelemetry.trace.getActiveSpan();
+ // Only return a trace id for sampled/recording spans. An unsampled span still
+ // carries a valid traceId in its context but is never exported, so that id
+ // would resolve to nothing in the tracing backend.
+ return span?.isRecording() ? span.spanContext().traceId : undefined;
+};
+
export const addTagsToCurrentSpan = (
attributes: Parameters<opentelemetry.Span["setAttributes"]>[0],
) => {
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 8ca8a7b023..7279d9afab 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -89,6 +89,7 @@ import {
addUserToSpan,
contextWithLangfuseProps,
ClickHouseResourceError,
+ getActiveTraceId,
} from "@langfuse/shared/src/server";
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
@@ -107,6 +108,10 @@ const t = initTRPC.context<typeof createTRPCContext>().create({
...shape,
data: {
...shape.data,
+ // OTEL trace id of the failing request, for frontend/support correlation
+ // with Datadog. Absent when OTEL is not running or the trace was not
+ // sampled (an unsampled id never reaches the tracing backend).
+ traceId: getActiveTraceId(),
zodError:
error.cause instanceof ZodError ? z.flattenError(error.cause) : null,
errorName: