Skip to content

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

fix(evals): make code-eval execution traces readable in trace detail (LFE-10884) (#15045)

Tobias Wochinger32299eff8ea4
diff --git a/packages/shared/src/server/llm/ai-sdk/telemetry.ts b/packages/shared/src/server/llm/ai-sdk/telemetry.ts
index cabf52ca23..8c1a7bc64b 100644
--- a/packages/shared/src/server/llm/ai-sdk/telemetry.ts
+++ b/packages/shared/src/server/llm/ai-sdk/telemetry.ts
@@ -11,7 +11,6 @@ import {
trace,
type Span,
} from "@opentelemetry/api";
-import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
import { resourceFromAttributes } from "@opentelemetry/resources";
import {
BasicTracerProvider,
@@ -24,7 +23,7 @@ import { stringifyValue } from "../../../utils/stringChecks";
import { traceException } from "../../instrumentation";
import { logger } from "../../logger";
import { LangfuseOtelSpanAttributes } from "../../otel/attributes";
-import { OtelIngestionProcessor } from "../../otel/OtelIngestionProcessor";
+import { publishInternalOtelSpans } from "../../otel/internalTraceOtelWriter";
import type { InternalTraceExperimentContext } from "../internalTraceEvents";
import type { TraceSinkParams } from "../types";
@@ -253,36 +252,11 @@ export function createAiSdkTelemetryCapture(params: {
}
if (matchingSpans.length === 0) return;
- const serialized = JsonTraceSerializer.serializeRequest(matchingSpans);
- if (!serialized) return;
-
- const { resourceSpans } = JSON.parse(
- new TextDecoder().decode(serialized),
- );
-
- if (!resourceSpans || resourceSpans.length === 0) return;
-
- const processor = new OtelIngestionProcessor({
+ await publishInternalOtelSpans({
+ spans: matchingSpans,
projectId: traceSinkParams.targetProjectId,
- publicKey: "", // internal ingestion has no API key; mirrors internal event writes
sdkName: INTERNAL_SDK_NAME,
- sdkVersion: "unknown",
- // Opt into the v4-native direct events write like a modern SDK batch:
- // only that path runs processToEvent -> createEventRecord, which is
- // the sole extractor of langfuse.experiment.* into experiment_*
- // columns. Without it, dual-write mode routes internal batches
- // (unknown SDK, no scope version) through legacy forwarding and
- // experiment run items lose their linkage in events_full/v4 views.
- // Legacy tables are still dual-written per v4WritesToLegacyTables.
- ingestionVersion: "4",
- // The consumer must parse these events with the internal ingestion
- // schema; the public schema strips the "langfuse-" environment prefix,
- // exposing internal traces as user environments and bypassing the
- // trace-upsert eval-loop guard.
- isLangfuseInternal: true,
});
-
- await processor.publishToOtelIngestionQueue(resourceSpans);
} catch (e) {
traceException(e);
logger.error("Failed to publish AI SDK internal telemetry", {
diff --git a/packages/shared/src/server/otel/index.ts b/packages/shared/src/server/otel/index.ts
index 745e24f072..bb5db04b40 100644
--- a/packages/shared/src/server/otel/index.ts
+++ b/packages/shared/src/server/otel/index.ts
@@ -1 +1,2 @@
export * from "./OtelIngestionProcessor";
+export * from "./internalTraceOtelWriter";
diff --git a/packages/shared/src/server/otel/internalTraceOtelWriter.test.ts b/packages/shared/src/server/otel/internalTraceOtelWriter.test.ts
new file mode 100644
index 0000000000..b2cc517090
--- /dev/null
+++ b/packages/shared/src/server/otel/internalTraceOtelWriter.test.ts
@@ -0,0 +1,153 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ writeInternalTraceViaOtelIngestion,
+ type InternalOtelSpanInput,
+} from "./internalTraceOtelWriter";
+
+const publishToOtelIngestionQueue = vi.fn().mockResolvedValue(undefined);
+
+vi.mock("./OtelIngestionProcessor", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("./OtelIngestionProcessor")>();
+ return {
+ ...actual,
+ OtelIngestionProcessor: class {
+ publishToOtelIngestionQueue = publishToOtelIngestionQueue;
+ },
+ };
+});
+
+const TRACE_ID = "0af7651916cd43dd8448eb211c80319c";
+const START_ISO = "2026-07-09T14:10:41.143Z";
+const END_ISO = "2026-07-09T14:10:42.000Z";
+
+// Mirrors the shape buildCodeEvalTraceInput (codeEvalExecution.ts) produces:
+// a single finished root span whose spanId is the 32-hex trace ID.
+const codeEvalRootInput: InternalOtelSpanInput = {
+ projectId: "project-1",
+ traceId: TRACE_ID,
+ spanId: TRACE_ID,
+ startTimeISO: START_ISO,
+ endTimeISO: END_ISO,
+ name: "Execute evaluator: helpfulness",
+ traceName: "Execute evaluator: helpfulness",
+ environment: "langfuse-code-eval",
+ level: "ERROR",
+ statusMessage: "Code eval execution failed: boom",
+ input: '{"item":{}}',
+ output: '{"error":"boom"}',
+ metadata: { dispatcher_name: "test-dispatcher" },
+};
+
+// Convert the published OTLP payload through the REAL OTel ingestion
+// processor — the same code path the OTel ingestion queue runs — so a
+// regression in attribute naming or the internal-schema contract fails here
+// instead of only in production.
+const processPublishedSpans = async () => {
+ expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);
+ const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];
+
+ const { OtelIngestionProcessor } = await vi.importActual<
+ typeof import("./OtelIngestionProcessor")
+ >("./OtelIngestionProcessor");
+ return new OtelIngestionProcessor({
+ projectId: "project-1",
+ publicKey: "",
+ sdkName: "langfuse-internal-otel-writer",
+ sdkVersion: "unknown",
+ isLangfuseInternal: true,
+ }).processToEvent(resourceSpans);
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("writeInternalTraceViaOtelIngestion", () => {
+ it("publishes a trace that converts through the real OTel ingestion processor", async () => {
+ await writeInternalTraceViaOtelIngestion({
+ rootSpanId: TRACE_ID,
+ eventInputs: [codeEvalRootInput],
+ });
+
+ const events = await processPublishedSpans();
+ expect(events).toHaveLength(1);
+
+ const root = events[0];
+ expect(root.traceId).toBe(TRACE_ID);
+ expect(root.parentSpanId).toBeNull();
+ expect(root).toMatchObject({
+ name: "Execute evaluator: helpfulness",
+ traceName: "Execute evaluator: helpfulness",
+ // The langfuse- prefix must survive conversion; stripping it would
+ // bypass the trace-upsert eval-loop guard.
+ environment: "langfuse-code-eval",
+ level: "ERROR",
+ statusMessage: "Code eval execution failed: boom",
+ input: '{"item":{}}',
+ output: '{"error":"boom"}',
+ startTimeISO: START_ISO,
+ endTimeISO: END_ISO,
+ });
+ expect(root.metadata).toMatchObject({
+ dispatcher_name: "test-dispatcher",
+ });
+ });
+
+ it("remaps child parentSpanId onto the regenerated span ids", async () => {
+ await writeInternalTraceViaOtelIngestion({
+ rootSpanId: TRACE_ID,
+ eventInputs: [
+ codeEvalRootInput,
+ {
+ ...codeEvalRootInput,
+ spanId: "original-child-id",
+ // References the root's ORIGINAL spanId (the 32-hex trace id, not a
+ // valid OTel span id) — must resolve to the root's generated id.
+ parentSpanId: codeEvalRootInput.spanId,
+ name: "child step",
+ },
+ ],
+ });
+
+ const events = await processPublishedSpans();
+ expect(events).toHaveLength(2);
+
+ const root = events.find((e: any) => !e.parentSpanId);
+ const child = events.find((e: any) => e.parentSpanId);
+ expect(child.name).toBe("child step");
+ expect(child.traceId).toBe(TRACE_ID);
+ expect(child.parentSpanId).toBe(root.spanId);
+ // Trace-level fields stay on the root only.
+ expect(child.traceName).toBeNull();
+
+ // A parent that no preceding input declared cannot be linked once span
+ // ids are regenerated — refused instead of emitting broken linkage.
+ await expect(
+ writeInternalTraceViaOtelIngestion({
+ rootSpanId: TRACE_ID,
+ eventInputs: [
+ { ...codeEvalRootInput, parentSpanId: "unknown-span-id" },
+ ],
+ }),
+ ).rejects.toThrow(/parentSpanId/);
+ });
+
+ it("skips empty, non-langfuse-environment, and invalid-trace-id inputs", async () => {
+ await writeInternalTraceViaOtelIngestion({
+ rootSpanId: TRACE_ID,
+ eventInputs: [],
+ });
+ await writeInternalTraceViaOtelIngestion({
+ rootSpanId: TRACE_ID,
+ eventInputs: [{ ...codeEvalRootInput, environment: "production" }],
+ });
+ await writeInternalTraceViaOtelIngestion({
+ rootSpanId: "not-a-trace-id",
+ eventInputs: [{ ...codeEvalRootInput, traceId: "not-a-trace-id" }],
+ });
+
+ expect(publishToOtelIngestionQueue).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/shared/src/server/otel/internalTraceOtelWriter.ts b/packages/shared/src/server/otel/internalTraceOtelWriter.ts
new file mode 100644
index 0000000000..14ae5d81a1
--- /dev/null
+++ b/packages/shared/src/server/otel/internalTraceOtelWriter.ts
@@ -0,0 +1,225 @@
+import { randomBytes } from "node:crypto";
+
+import {
+ ROOT_CONTEXT,
+ TraceFlags,
+ trace as otelTraceApi,
+ type Attributes,
+} from "@opentelemetry/api";
+import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
+import { resourceFromAttributes } from "@opentelemetry/resources";
+import {
+ BasicTracerProvider,
+ InMemorySpanExporter,
+ SimpleSpanProcessor,
+ type ReadableSpan,
+} from "@opentelemetry/sdk-trace-base";
+
+import type { InternalTraceEventInput } from "../llm/internalTraceEvents";
+import { logger } from "../logger";
+import { LangfuseOtelSpanAttributes } from "./attributes";
+import { OtelIngestionProcessor } from "./OtelIngestionProcessor";
+
+const INTERNAL_TRACE_WRITER_SDK_NAME = "langfuse-internal-otel-writer";
+const INTERNAL_TRACE_WRITER_SCOPE = "langfuse-internal-trace-writer";
+const W3C_TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
+
+/**
+ * Publishes internally captured OTel spans through the regular OTel ingestion
+ * pipeline (same S3 + queue path as the public /api/public/otel/v1/traces
+ * endpoint), so internal traces get exactly the same write treatment as user
+ * traces: legacy traces/observations tables and events tables per the V4
+ * migration flags. Shared by the AI-SDK judge capture (`createAiSdkTelemetryCapture`)
+ * and `writeInternalTraceViaOtelIngestion`.
+ */
+export async function publishInternalOtelSpans(params: {
+ spans: ReadableSpan[];
+ projectId: string;
+ sdkName: string;
+}): Promise<void> {
+ const serialized = JsonTraceSerializer.serializeRequest(params.spans);
+ if (!serialized) return;
+
+ const { resourceSpans } = JSON.parse(new TextDecoder().decode(serialized));
+
+ if (!resourceSpans || resourceSpans.length === 0) return;
+
+ const processor = new OtelIngestionProcessor({
+ projectId: params.projectId,
+ publicKey: "", // internal ingestion has no API key; mirrors internal event writes
+ sdkName: params.sdkName,
+ sdkVersion: "unknown",
+ // Opt into the v4-native direct events write like a modern SDK batch:
+ // only that path runs processToEvent -> createEventRecord, which is
+ // the sole extractor of langfuse.experiment.* into experiment_*
+ // columns. Without it, dual-write mode routes internal batches
+ // (unknown SDK, no scope version) through legacy forwarding and
+ // experiment run items lose their linkage in events_full/v4 views.
+ // Legacy tables are still dual-written per v4WritesToLegacyTables.
+ ingestionVersion: "4",
+ // The consumer must parse these events with the internal ingestion
+ // schema; the public schema strips the "langfuse-" environment prefix,
+ // exposing internal traces as user environments and bypassing the
+ // trace-upsert eval-loop guard.
+ isLangfuseInternal: true,
+ });
+
+ await processor.publishToOtelIngestionQueue(resourceSpans);
+}
+
+/**
+ * Exactly the `InternalTraceEventInput` fields this writer maps onto OTel
+ * spans. Narrowed so a caller with richer inputs (usage, prompt, experiment
+ * linkage, ...) gets a compile-time surface mismatch instead of silent drops.
+ */
+export type InternalOtelSpanInput = Pick<
+ InternalTraceEventInput,
+ | "projectId"
+ | "traceId"
+ | "spanId"
+ | "parentSpanId"
+ | "startTimeISO"
+ | "endTimeISO"
+ | "name"
+ | "traceName"
+ | "environment"
+ | "level"
+ | "statusMessage"
+ | "input"
+ | "output"
+ | "metadata"
+>;
+
+/**
+ * Writes an already-finished internal trace (e.g. a code-eval execution trace)
+ * through the OTel ingestion pipeline via `publishInternalOtelSpans`. Unlike
+ * `createInternalEventsWriter` in the worker, which only writes the v4 events
+ * tables, this reaches every store the deployment's migration flags write to —
+ * without it, trace-level auth (which reads the legacy traces table in dual
+ * mode) 404s on these traces.
+ *
+ * Span IDs are newly generated (the code-eval producer sets `spanId` to the
+ * 32-hex trace ID, which is not a valid OTel span ID), so inputs must be
+ * ordered parents-first: a `parentSpanId` must reference a preceding input's
+ * `spanId` to be remapped onto the generated ID.
+ */
+export async function writeInternalTraceViaOtelIngestion(trace: {
+ rootSpanId: string;
+ eventInputs: InternalOtelSpanInput[];
+}): Promise<void> {
+ const { eventInputs } = trace;
+ if (eventInputs.length === 0) return;
+
+ // Mirrors the createAiSdkTelemetryCapture guards: non-langfuse environments
+ // would bypass the eval-loop safeguard, and a non-W3C trace ID would emit
+ // silently malformed OTLP IDs.
+ const invalidInput = eventInputs.find(
+ (eventInput) =>
+ !eventInput.environment?.startsWith("langfuse") ||
+ !W3C_TRACE_ID_PATTERN.test(eventInput.traceId.toLowerCase()) ||
+ eventInput.traceId.toLowerCase() === "0".repeat(32),
+ );
+ if (invalidInput) {
+ logger.warn(
+ "Skipping internal trace write: environment must be langfuse-prefixed and trace id a valid W3C trace id",
+ {
+ traceId: invalidInput.traceId,
+ environment: invalidInput.environment,
+ },
+ );
+ return;
+ }
+
+ const exporter = new InMemorySpanExporter();
+ let currentTraceId = eventInputs[0].traceId.toLowerCase();
+ const tracerProvider = new BasicTracerProvider({
+ resource: resourceFromAttributes({
+ [LangfuseOtelSpanAttributes.ENVIRONMENT]: eventInputs[0].environment,
+ }),
+ spanProcessors: [new SimpleSpanProcessor(exporter)],
+ // Root spans (no parent) receive the input's Langfuse trace ID via
+ // `currentTraceId`; span creation below is synchronous, so the closure is
+ // safe.
+ idGenerator: {
+ generateTraceId: () => currentTraceId,
+ generateSpanId: () => randomBytes(8).toString("hex"),
+ },
+ });
+
+ try {
+ const tracer = tracerProvider.getTracer(INTERNAL_TRACE_WRITER_SCOPE);
+ const generatedSpanIds = new Map<string, string>();
+
+ for (const eventInput of eventInputs) {
+ currentTraceId = eventInput.traceId.toLowerCase();
+ const isRoot = !eventInput.parentSpanId;
+ const metadataJson = JSON.stringify(eventInput.metadata);
+
+ const attributes: Attributes = {
+ ...(eventInput.environment !== undefined
+ ? { [LangfuseOtelSpanAttributes.ENVIRONMENT]: eventInput.environment }
+ : {}),
+ ...(eventInput.level !== undefined
+ ? { [LangfuseOtelSpanAttributes.OBSERVATION_LEVEL]: eventInput.level }
+ : {}),
+ ...(eventInput.statusMessage !== undefined
+ ? {
+ [LangfuseOtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]:
+ eventInput.statusMessage,
+ }
+ : {}),
+ ...(eventInput.input !== undefined
+ ? { [LangfuseOtelSpanAttributes.OBSERVATION_INPUT]: eventInput.input }
+ : {}),
+ ...(eventInput.output !== undefined
+ ? {
+ [LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT]:
+ eventInput.output,
+ }
+ : {}),
+ [LangfuseOtelSpanAttributes.OBSERVATION_METADATA]: metadataJson,
+ ...(isRoot && eventInput.traceName !== undefined
+ ? { [LangfuseOtelSpanAttributes.TRACE_NAME]: eventInput.traceName }
+ : {}),
+ ...(isRoot
+ ? { [LangfuseOtelSpanAttributes.TRACE_METADATA]: metadataJson }
+ : {}),
+ };
+
+ let context = ROOT_CONTEXT;
+ if (eventInput.parentSpanId) {
+ const generatedParentSpanId = generatedSpanIds.get(
+ eventInput.parentSpanId,
+ );
+ if (!generatedParentSpanId) {
+ throw new Error(
+ "Internal trace input's parentSpanId must reference a preceding input's spanId",
+ );
+ }
+ context = otelTraceApi.setSpanContext(ROOT_CONTEXT, {
+ traceId: currentTraceId,
+ spanId: generatedParentSpanId,
+ traceFlags: TraceFlags.SAMPLED,
+ });
+ }
+
+ const span = tracer.startSpan(
+ eventInput.name ?? "",
+ { startTime: new Date(eventInput.startTimeISO), attributes },
+ context,
+ );
+ generatedSpanIds.set(eventInput.spanId, span.spanContext().spanId);
+ span.end(new Date(eventInput.endTimeISO));
+ }
+
+ await tracerProvider.forceFlush();
+
+ await publishInternalOtelSpans({
+ spans: exporter.getFinishedSpans(),
+ projectId: eventInputs[0].projectId,
+ sdkName: INTERNAL_TRACE_WRITER_SDK_NAME,
+ });
+ } finally {
+ await tracerProvider.shutdown().catch(() => undefined);
+ }
+}
diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.ts
index 2078df5db6..31cf72a0e2 100644
--- a/web/src/__tests__/server/traces-trpc.servertest.ts
+++ b/web/src/__tests__/server/traces-trpc.servertest.ts
@@ -562,6 +562,48 @@ describe("traces trpc", () => {
expect(traceRes?.timestamp).toEqual(new Date(trace.timestamp));
});
+ // In dual write mode, internally produced traces (e.g. code-eval execution
+ // traces) exist ONLY in the events tables. Trace access must fall back to
+ // the events table instead of 404ing on the legacy `traces` miss — the
+ // fast-preview list showed such traces while the detail view threw
+ // "Trace not found".
+ // Gate matches the code: events-table reads work in dual (fallback) and
+ // events_only (getTraceById routing); legacy deployments (azure /
+ // redis-cluster CI) have no events tables and skip.
+ const eventsTraceReadable =
+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy";
+ (eventsTraceReadable ? it : it.skip)(
+ "access trace that only exists in the events table",
+ async () => {
+ const traceId = randomUUID();
+
+ await createEventsCh([
+ createEvent({
+ id: traceId,
+ span_id: traceId,
+ trace_id: traceId,
+ project_id: projectId,
+ parent_span_id: null,
+ }),
+ ]);
+
+ // Precondition: legacy `traces` has no row.
+ expect(
+ await getTraceByIdFromTracesTable({ traceId, projectId }),
+ ).toBeUndefined();
+
+ // ClickHouse insert visibility can lag.
+ await waitForExpect(async () => {
+ const traceRes = await caller.traces.byId({
+ projectId,
+ traceId,
+ });
+ expect(traceRes?.id).toEqual(traceId);
+ expect(traceRes?.projectId).toEqual(projectId);
+ });
+ },
+ );
+
it("access trace without any authentication", async () => {
const unAuthedSession = createInnerTRPCContext({
session: null,
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 3c9f42407c..1ac71726f8 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -85,6 +85,7 @@ import { ZodError } from "zod";
import { setUpSuperjson } from "@/src/utils/superjson";
import {
getTraceById,
+ getTraceByIdFromEventsTable,
logger,
addUserToSpan,
contextWithLangfuseProps,
@@ -508,7 +509,7 @@ const enforceTraceAccess = t.middleware(async (opts) => {
const fromTimestamp = result.data.fromTimestamp;
const verbosity = result.data.verbosity;
- const clickhouseTrace = traceId
+ let clickhouseTrace = traceId
? // eslint-disable-next-line @typescript-eslint/no-deprecated
await getTraceById({
traceId,
@@ -522,6 +523,29 @@ const enforceTraceAccess = t.middleware(async (opts) => {
})
: null;
+ // In dual write mode the lookup above reads the legacy traces table, but
+ // internally produced traces (e.g. code-eval execution traces) were written
+ // to the events tables only — fall back so trace-level auth does not 404 on
+ // a trace the events-backed views can render (LFE-10884). Gated on "dual"
+ // because in "legacy" mode the events tables may not exist and in
+ // "events_only" mode getTraceById already read them.
+ if (
+ traceId &&
+ !clickhouseTrace &&
+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual"
+ ) {
+ clickhouseTrace = await getTraceByIdFromEventsTable({
+ traceId,
+ projectId,
+ timestamp: timestamp ?? undefined,
+ fromTimestamp: fromTimestamp ?? undefined,
+ renderingProps: {
+ truncated: verbosity === "truncated",
+ shouldJsonParse: false,
+ },
+ });
+ }
+
if (traceId && !clickhouseTrace) {
logger.error(`Trace with id ${traceId} not found for project ${projectId}`);
throw new TRPCError({
diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
index e0ca9ba7a3..4032be66ec 100644
--- a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.test.ts
@@ -39,13 +39,10 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
createW3CTraceId: mocks.createW3CTraceId,
runCodeBasedEvaluationDispatch,
resolveConfiguredCodeEvalDispatcher: vi.fn(() => mocks.dispatcher),
+ writeInternalTraceViaOtelIngestion: mocks.writeInternalTrace,
};
});
-vi.mock("../../internal-tracing/createInternalEventsWriter", () => ({
- createInternalEventsWriter: () => ({ write: mocks.writeInternalTrace }),
-}));
-
import { executeCodeBasedEvaluation } from "./executeCodeBasedEvaluation";
describe("executeCodeBasedEvaluation", () => {
diff --git a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts
index 47606169a6..c64e76097c 100644
--- a/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts
+++ b/worker/src/features/evaluation/codeBased/executeCodeBasedEvaluation.ts
@@ -6,11 +6,11 @@ import {
logger,
resolveConfiguredCodeEvalDispatcher,
runCodeBasedEvaluationDispatch,
+ writeInternalTraceViaOtelIngestion,
type ExtractedVariable,
} from "@langfuse/shared/src/server";
import { UnrecoverableError } from "../../../errors/UnrecoverableError";
import { createW3CTraceId } from "../../utils";
-import { createInternalEventsWriter } from "../../internal-tracing/createInternalEventsWriter";
import { type EvalExecutionResult } from "../evalCompletion";
import { type EvalExecutionDeps } from "../evalExecutionDeps";
@@ -68,7 +68,10 @@ export async function executeCodeBasedEvaluation(params: {
hasExperimentContext: params.hasExperimentContext ?? false,
traceName: `Execute evaluator: ${params.template.name}`,
metadata: executionMetadata,
- writeTrace: (trace) => createInternalEventsWriter().write(trace),
+ // Publish via the OTel ingestion pipeline (like LLM-as-a-judge) so the
+ // trace reaches the legacy tables too in dual write mode — a direct
+ // events-table write alone 404s in the trace detail view.
+ writeTrace: (trace) => writeInternalTraceViaOtelIngestion(trace),
});
if (!dispatchOutcome.success) {
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
index 372c244aaa..d58fb08bc5 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
@@ -44,10 +44,6 @@ vi.mock("../../evalService", () => ({
runLLMAsJudgeEvaluation: vi.fn(),
}));
-vi.mock("../../../internal-tracing/createInternalEventsWriter", () => ({
- createInternalEventsWriter: () => ({ write: mocks.writeInternalTrace }),
-}));
-
// Mock logger
vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual<
@@ -65,6 +61,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
resolveConfiguredCodeEvalDispatcher: vi.fn(
() => new actual.LocalCodeEvalDispatcher(),
),
+ writeInternalTraceViaOtelIngestion: mocks.writeInternalTrace,
};
});