Skip to content

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

feat(experiments): direct-write prompt experiment root events (#13044)

Hassieb Pakzadeb7ee42b8b6b
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index a8b31b5f49..7761fb7055 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -28,6 +28,7 @@ export * from "./llm/fetchLLMCompletion";
export * from "./llm/errors";
export * from "./llm/utils";
export * from "./llm/types";
+export * from "./llm/internalTraceEvents";
export * from "./llm/compileChatMessages";
export * from "./llm/testModelCall";
export * from "./llm/baseUrlValidation";
diff --git a/packages/shared/src/server/llm/getInternalTracingHandler.ts b/packages/shared/src/server/llm/getInternalTracingHandler.ts
index 9f697daf3e..04429622dd 100644
--- a/packages/shared/src/server/llm/getInternalTracingHandler.ts
+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts
@@ -1,88 +1,22 @@
import CallbackHandler from "langfuse-langchain";
-import { GenerationDetails, TraceSinkParams } from "./types";
+import { ProcessedTraceEvent, TraceSinkParams } from "./types";
+import { buildInternalTraceEventInputs } from "./internalTraceEvents";
import { processEventBatch } from "../ingestion/processEventBatch";
import { logger } from "../logger";
import { traceException } from "../instrumentation";
-type TracedEvent = {
- type: string;
- body: Record<string, unknown>;
-};
-
-/**
- * Extracts and merges generation details from a list of processed events.
- * Handles multiple generation-create and generation-update events with the same id.
- *
- * Events are merged following the "last non-null value wins" pattern:
- * - generation-create events contain: id, name, input, metadata
- * - generation-update events contain: output, usage, usageDetails
- *
- * @returns GenerationDetails or null if no generation events found
- */
-export function extractGenerationDetails(
- processedEvents: Array<{ type: string; body: Record<string, unknown> }>,
-): GenerationDetails | null {
- // 1. Filter to only generation events
- const generationEvents = processedEvents.filter(
- (event) =>
- event.type === "generation-create" || event.type === "generation-update",
- );
-
- if (generationEvents.length === 0) {
- return null;
- }
-
- // 2. Get the generation id from first event
- const generationId = generationEvents[0].body.id as string;
- if (!generationId) {
- return null;
- }
-
- // 3. Filter to events for this generation id only
- const eventsForGeneration = generationEvents.filter(
- (event) => event.body.id === generationId,
- );
-
- // 4. Merge event bodies (last non-null/non-undefined value wins)
- // Similar to IngestionService pattern but simplified for our use case
- const mergedBody = eventsForGeneration.reduce(
- (acc: Record<string, unknown>, event) => {
- for (const [key, value] of Object.entries(event.body)) {
- if (value !== undefined && value !== null) {
- // Special handling for metadata: deep merge
- if (
- key === "metadata" &&
- typeof value === "object" &&
- !Array.isArray(value)
- ) {
- acc[key] = {
- ...((acc[key] as Record<string, unknown>) || {}),
- ...(value as Record<string, unknown>),
- };
- } else {
- acc[key] = value;
- }
- }
- }
- return acc;
- },
- { id: generationId },
- );
-
- return {
- observationId: generationId,
- name: (mergedBody.name as string) || "generation",
- input: mergedBody.input,
- output: mergedBody.output,
- metadata: (mergedBody.metadata as Record<string, unknown>) || {},
- };
-}
-
-export function prepareTracedEventsForIngestion(
- events: TracedEvent[],
- { environment, prompt }: Pick<TraceSinkParams, "environment" | "prompt">,
-): TracedEvent[] {
- const blockedSpanIds = new Set<string>();
+export function prepareInternalTraceEvents(params: {
+ events: Array<{
+ type: string;
+ timestamp: string;
+ body: Record<string, unknown>;
+ }>;
+ environment: string;
+ prompt?: TraceSinkParams["prompt"];
+}): ProcessedTraceEvent[] {
+ const { events, environment, prompt } = params;
+
+ const blockedSpanIds = new Set();
const blockedSpanNames = [
"RunnableLambda",
"StructuredOutputParser",
@@ -91,29 +25,27 @@ export function prepareTracedEventsForIngestion(
];
for (const event of events) {
- const eventName = event.body.name;
+ const eventName = "name" in event.body ? event.body.name : "";
if (typeof eventName !== "string" || eventName.length === 0) {
continue;
}
- if (
- blockedSpanNames.includes(eventName) &&
- typeof event.body.id === "string"
- ) {
+ if (blockedSpanNames.includes(eventName as string) && "id" in event.body) {
blockedSpanIds.add(event.body.id);
}
}
return events
.filter((event) => {
- if (typeof event.body.id === "string") {
+ if ("id" in event.body) {
return !blockedSpanIds.has(event.body.id);
}
return true;
})
.map((event) => {
+ // Inject environment into all events
return {
...event,
body: {
@@ -142,7 +74,8 @@ export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {
handler: CallbackHandler;
processTracedEvents: () => Promise<void>;
} {
- const { prompt, targetProjectId, environment, userId } = traceSinkParams;
+ const { prompt, targetProjectId, environment, userId, eventsWriter } =
+ traceSinkParams;
const handler = new CallbackHandler({
_projectId: targetProjectId,
_isLocalEventExportEnabled: true,
@@ -155,41 +88,52 @@ export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {
const events = await handler.langfuse._exportLocalEvents(
traceSinkParams.targetProjectId,
);
+ const processedEvents = prepareInternalTraceEvents({
+ events,
+ environment,
+ prompt,
+ });
+
+ // Legacy write to traces/observations tables
+ try {
+ await processEventBatch(
+ JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call
+ {
+ validKey: true as const,
+ scope: {
+ projectId: traceSinkParams.targetProjectId, // Important: this controls into what project traces are ingested.
+ accessLevel: "project",
+ } as any,
+ },
+ {
+ isLangfuseInternal: true,
+ forwardToEventsTable: eventsWriter ? false : undefined, // Do not dual write when we already direct event write
+ },
+ );
+ } catch (processingError) {
+ traceException(processingError);
+ logger.error("Failed to process traced events via legacy ingestion", {
+ error: processingError,
+ });
+ }
- const processedEvents = prepareTracedEventsForIngestion(
- events as TracedEvent[],
- {
- environment,
- prompt,
- },
- );
-
- await processEventBatch(
- JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call
- {
- validKey: true as const,
- scope: {
- projectId: traceSinkParams.targetProjectId, // Important: this controls into what project traces are ingested.
- accessLevel: "project",
- } as any,
- },
- {
- isLangfuseInternal: true,
- },
- );
-
- // Extract generation details and invoke callback (if provided)
- if (traceSinkParams.onGenerationComplete) {
+ // Direct write to events table
+ if (eventsWriter) {
try {
- const generationDetails = extractGenerationDetails(processedEvents);
- if (generationDetails) {
- traceSinkParams.onGenerationComplete(generationDetails);
+ const { rootSpanId, eventInputs } = buildInternalTraceEventInputs({
+ processedEvents,
+ traceId: traceSinkParams.traceId,
+ projectId: targetProjectId,
+ experimentContext: eventsWriter.experimentContext,
+ });
+
+ if (eventInputs.length > 0) {
+ await eventsWriter.write({ rootSpanId, eventInputs });
}
- } catch (extractionError) {
- // Don't fail the LLM call due to generation detail extraction errors
- traceException(extractionError);
- logger.error("Failed to extract generation details from events", {
- error: extractionError,
+ } catch (writeError) {
+ traceException(writeError);
+ logger.error("Failed to direct-write internal traced events", {
+ error: writeError,
});
}
}
diff --git a/packages/shared/src/server/llm/internalTraceEvents.ts b/packages/shared/src/server/llm/internalTraceEvents.ts
new file mode 100644
index 0000000000..873b7234a4
--- /dev/null
+++ b/packages/shared/src/server/llm/internalTraceEvents.ts
@@ -0,0 +1,417 @@
+import {
+ asBoolean,
+ asNumberRecord,
+ asRecord,
+ asString,
+ asStringArray,
+} from "../../utils/objects";
+import { stringifyValue } from "../../utils/stringChecks";
+import {
+ convertCallsToArrays,
+ convertDefinitionsToMap,
+ extractToolsFromObservation,
+} from "../ingestion/extractToolsBackend";
+import { flattenJsonToPathArrays } from "../otel/utils";
+import type { ProcessedTraceEvent } from "./types";
+
+export const INTERNAL_TRACE_EVENT_SOURCE = "ingestion-api-dual-write";
+export const INTERNAL_TRACE_EXPERIMENT_EVENT_SOURCE =
+ "ingestion-api-dual-write-experiments";
+
+export type InternalTraceExperimentContext = {
+ id: string;
+ name: string;
+ metadata?: Record<string, unknown>;
+ description?: string | null;
+ datasetId: string;
+ itemId: string;
+ itemVersion: string;
+ itemExpectedOutput?: unknown;
+ itemMetadata?: Record<string, unknown> | null;
+};
+
+/**
+ * Flexible input type for writing events to the events table.
+ * This is intentionally loose to allow for iteration as the events
+ * table schema evolves. Only required fields are enforced.
+ */
+export type InternalTraceEventInput = {
+ projectId: string;
+ traceId: string;
+ spanId: string;
+ startTimeISO: string;
+ orgId?: string;
+ parentSpanId?: string;
+ name?: string;
+ type?: string;
+ environment?: string;
+ version?: string;
+ release?: string;
+ endTimeISO: string;
+ completionStartTime?: string;
+ traceName?: string;
+ tags?: string[];
+ bookmarked?: boolean;
+ public?: boolean;
+ userId?: string;
+ sessionId?: string;
+ level?: string;
+ statusMessage?: string;
+ promptId?: string;
+ promptName?: string;
+ promptVersion?: string;
+ modelId?: string;
+ modelName?: string;
+ modelParameters?: string | Record<string, unknown>;
+ providedUsageDetails?: Record<string, number>;
+ usageDetails?: Record<string, number>;
+ providedCostDetails?: Record<string, number>;
+ costDetails?: Record<string, number>;
+ toolDefinitions?: Record<string, string>;
+ toolCalls?: string[];
+ toolCallNames?: string[];
+ input?: string;
+ output?: string;
+ metadata: Record<string, unknown>;
+ source: string;
+ serviceName?: string;
+ serviceVersion?: string;
+ scopeName?: string;
+ scopeVersion?: string;
+ telemetrySdkLanguage?: string;
+ telemetrySdkName?: string;
+ telemetrySdkVersion?: string;
+ blobStorageFilePath?: string;
+ eventRaw?: string;
+ eventBytes?: number;
+ experimentId?: string;
+ experimentName?: string;
+ experimentMetadataNames?: string[];
+ experimentMetadataValues?: Array<string | null | undefined>;
+ experimentDescription?: string;
+ experimentDatasetId?: string;
+ experimentItemId?: string;
+ experimentItemVersion?: string;
+ experimentItemRootSpanId?: string;
+ experimentItemExpectedOutput?: string;
+ experimentItemMetadataNames?: string[];
+ experimentItemMetadataValues?: Array<string | null | undefined>;
+ [key: string]: any;
+};
+
+type InternalTraceSnapshot = {
+ spanId: string;
+ traceId: string;
+ parentSpanId?: string;
+ name?: string;
+ type: "SPAN" | "GENERATION";
+ environment?: string;
+ version?: string;
+ release?: string;
+ startTimeISO?: string;
+ endTimeISO?: string;
+ completionStartTime?: string;
+ level?: string;
+ statusMessage?: string;
+ promptName?: string;
+ promptVersion?: string;
+ modelName?: string;
+ modelParameters?: Record<string, unknown>;
+ providedUsageDetails?: Record<string, number>;
+ providedCostDetails?: Record<string, number>;
+ input?: unknown;
+ output?: unknown;
+ metadata: Record<string, unknown>;
+ tags?: string[];
+ public?: boolean;
+ bookmarked?: boolean;
+ userId?: string;
+ sessionId?: string;
+};
+
+export type MaterializedInternalTrace = {
+ rootSpanId: string;
+ snapshots: InternalTraceSnapshot[];
+};
+
+function isCreateEvent(type: string): boolean {
+ return type.endsWith("-create");
+}
+
+function getSnapshotType(eventType: string): "SPAN" | "GENERATION" {
+ return eventType.startsWith("generation-") ? "GENERATION" : "SPAN";
+}
+
+function getEventTime(
+ event: ProcessedTraceEvent,
+ body: Record<string, unknown>,
+): number {
+ const candidates = [body.startTime, body.timestamp, event.timestamp];
+
+ for (const candidate of candidates) {
+ if (typeof candidate === "string") {
+ const parsed = new Date(candidate).getTime();
+ if (!Number.isNaN(parsed)) {
+ return parsed;
+ }
+ }
+ }
+
+ return 0;
+}
+
+function getTimestampMs(timestamp?: string): number {
+ if (!timestamp) {
+ return 0;
+ }
+
+ const parsed = new Date(timestamp).getTime();
+ return Number.isNaN(parsed) ? 0 : parsed;
+}
+
+function sortEvents(events: ProcessedTraceEvent[]): ProcessedTraceEvent[] {
+ return [...events].sort((left, right) => {
+ const timeDelta =
+ getEventTime(left, left.body) - getEventTime(right, right.body);
+
+ if (timeDelta !== 0) {
+ return timeDelta;
+ }
+
+ if (isCreateEvent(left.type) === isCreateEvent(right.type)) {
+ return 0;
+ }
+
+ return isCreateEvent(left.type) ? -1 : 1;
+ });
+}
+
+function flattenMetadata(value: unknown): {
+ names: string[];
+ values: Array<string | null | undefined>;
+} {
+ const metadata = asRecord(value);
+ return metadata
+ ? flattenJsonToPathArrays(metadata)
+ : { names: [], values: [] };
+}
+
+function mergeSnapshotEvent(
+ snapshot: InternalTraceSnapshot,
+ event: ProcessedTraceEvent,
+): InternalTraceSnapshot {
+ const { body } = event;
+ const startTime = asString(body.startTime);
+ const timestamp = asString(body.timestamp) ?? asString(event.timestamp);
+ const metadata = asRecord(body.metadata);
+
+ return {
+ ...snapshot,
+ traceId: asString(body.traceId) ?? snapshot.traceId,
+ parentSpanId: asString(body.parentObservationId) ?? snapshot.parentSpanId,
+ type:
+ snapshot.type === "GENERATION"
+ ? snapshot.type
+ : getSnapshotType(event.type),
+ name: asString(body.name) ?? snapshot.name,
+ environment: asString(body.environment) ?? snapshot.environment,
+ version: asString(body.version) ?? snapshot.version,
+ release: asString(body.release) ?? snapshot.release,
+ startTimeISO:
+ startTime ?? snapshot.startTimeISO ?? timestamp ?? snapshot.startTimeISO,
+ endTimeISO: asString(body.endTime) ?? snapshot.endTimeISO,
+ completionStartTime:
+ asString(body.completionStartTime) ?? snapshot.completionStartTime,
+ level: asString(body.level) ?? snapshot.level,
+ statusMessage: asString(body.statusMessage) ?? snapshot.statusMessage,
+ promptName: asString(body.promptName) ?? snapshot.promptName,
+ promptVersion:
+ typeof body.promptVersion === "number"
+ ? body.promptVersion.toString()
+ : (asString(body.promptVersion) ?? snapshot.promptVersion),
+ modelName: asString(body.model) ?? snapshot.modelName,
+ modelParameters: asRecord(body.modelParameters) ?? snapshot.modelParameters,
+ providedUsageDetails:
+ asNumberRecord(body.usageDetails) ??
+ asNumberRecord(body.usage) ??
+ snapshot.providedUsageDetails,
+ providedCostDetails:
+ asNumberRecord(body.costDetails) ?? snapshot.providedCostDetails,
+ input:
+ body.input !== undefined && body.input !== null
+ ? body.input
+ : snapshot.input,
+ output:
+ body.output !== undefined && body.output !== null
+ ? body.output
+ : snapshot.output,
+ metadata: metadata
+ ? { ...snapshot.metadata, ...metadata }
+ : snapshot.metadata,
+ tags: asStringArray(body.tags) ?? snapshot.tags,
+ public: asBoolean(body.public) ?? snapshot.public,
+ bookmarked: asBoolean(body.bookmarked) ?? snapshot.bookmarked,
+ userId: asString(body.userId) ?? snapshot.userId,
+ sessionId: asString(body.sessionId) ?? snapshot.sessionId,
+ };
+}
+
+export function materializeInternalTrace(params: {
+ processedEvents: ProcessedTraceEvent[];
+ traceId: string;
+}): MaterializedInternalTrace {
+ const { processedEvents, traceId } = params;
+ const snapshots = new Map<string, InternalTraceSnapshot>();
+ const traceCreateEvent = processedEvents.find(
+ (e) => e.type === "trace-create",
+ );
+ const rootSpanId = asString(traceCreateEvent?.body.id) ?? traceId;
+
+ for (const event of sortEvents(processedEvents)) {
+ const spanId = asString(event.body.id);
+
+ if (!spanId) {
+ continue;
+ }
+
+ const existingSnapshot =
+ snapshots.get(spanId) ??
+ ({
+ spanId,
+ traceId: asString(event.body.traceId) ?? traceId,
+ type: getSnapshotType(event.type),
+ metadata: {},
+ } satisfies InternalTraceSnapshot);
+
+ snapshots.set(spanId, mergeSnapshotEvent(existingSnapshot, event));
+ }
+
+ const orderedSnapshots = [...snapshots.values()].sort((left, right) => {
+ if (left.spanId === rootSpanId) {
+ return -1;
+ }
+
+ if (right.spanId === rootSpanId) {
+ return 1;
+ }
+
+ return (
+ getTimestampMs(left.startTimeISO) - getTimestampMs(right.startTimeISO)
+ );
+ });
+
+ return { rootSpanId, snapshots: orderedSnapshots };
+}
+
+export function buildInternalTraceEventInputs(params: {
+ processedEvents: ProcessedTraceEvent[];
+ traceId: string;
+ projectId: string;
+ experimentContext?: InternalTraceExperimentContext;
+}): {
+ rootSpanId: string;
+ eventInputs: InternalTraceEventInput[];
+} {
+ const { processedEvents, traceId, projectId, experimentContext } = params;
+ // Direct write uses original IDs (observation.id === trace.id for root).
+ // The experiment backfill job skips traces already in events_core via LEFT ANTI JOIN,
+ // so there's no deduplication concern between direct write and backfill.
+ const { rootSpanId, snapshots } = materializeInternalTrace({
+ processedEvents,
+ traceId,
+ });
+ const rootSnapshot = snapshots.find((s) => s.spanId === rootSpanId);
+
+ if (!rootSnapshot) {
+ return { rootSpanId, eventInputs: [] };
+ }
+
+ const experimentMetadata = flattenMetadata(experimentContext?.metadata);
+ const experimentItemMetadata = flattenMetadata(
+ experimentContext?.itemMetadata,
+ );
+ const source = experimentContext
+ ? INTERNAL_TRACE_EXPERIMENT_EVENT_SOURCE
+ : INTERNAL_TRACE_EVENT_SOURCE;
+
+ const eventInputs = snapshots.map((snapshot) => {
+ const { toolDefinitions, toolArguments } = extractToolsFromObservation(
+ snapshot.input,
+ snapshot.output,
+ );
+ const toolCalls = convertCallsToArrays(toolArguments);
+ const isRoot = snapshot.spanId === rootSpanId;
+
+ return {
+ projectId,
+ traceId,
+ spanId: snapshot.spanId,
+ parentSpanId: isRoot ? undefined : (snapshot.parentSpanId ?? rootSpanId),
+ name:
+ snapshot.name ??
+ (snapshot.type === "GENERATION"
+ ? "generation"
+ : (rootSnapshot.name ?? "span")),
+ type: snapshot.type,
+ environment: snapshot.environment ?? rootSnapshot.environment,
+ version: snapshot.version ?? rootSnapshot.version,
+ release: rootSnapshot.release,
+ startTimeISO:
+ snapshot.startTimeISO ??
+ rootSnapshot.startTimeISO ??
+ new Date().toISOString(),
+ endTimeISO:
+ snapshot.endTimeISO ??
+ snapshot.startTimeISO ??
+ rootSnapshot.endTimeISO ??
+ rootSnapshot.startTimeISO ??
+ new Date().toISOString(),
+ completionStartTime: snapshot.completionStartTime,
+ traceName: rootSnapshot.name,
+ tags: rootSnapshot.tags ?? [],
+ bookmarked: rootSnapshot.bookmarked,
+ public: rootSnapshot.public,
+ userId: rootSnapshot.userId,
+ sessionId: rootSnapshot.sessionId,
+ level: snapshot.level ?? "DEFAULT",
+ statusMessage: snapshot.statusMessage,
+ promptName: snapshot.promptName,
+ promptVersion: snapshot.promptVersion,
+ modelName: snapshot.modelName,
+ modelParameters: snapshot.modelParameters,
+ providedUsageDetails: snapshot.providedUsageDetails,
+ providedCostDetails: snapshot.providedCostDetails,
+ toolDefinitions: convertDefinitionsToMap(toolDefinitions),
+ toolCalls: toolCalls.tool_calls,
+ toolCallNames: toolCalls.tool_call_names,
+ input:
+ snapshot.input !== undefined
+ ? stringifyValue(snapshot.input)
+ : undefined,
+ output:
+ snapshot.output !== undefined
+ ? stringifyValue(snapshot.output)
+ : undefined,
+ metadata: snapshot.metadata,
+ source,
+ experimentId: experimentContext?.id,
+ experimentName: experimentContext?.name,
+ experimentMetadataNames: experimentMetadata.names,
+ experimentMetadataValues: experimentMetadata.values,
+ experimentDescription: experimentContext?.description ?? undefined,
+ experimentDatasetId: experimentContext?.datasetId,
+ experimentItemId: experimentContext?.itemId,
+ experimentItemVersion: experimentContext?.itemVersion,
+ experimentItemRootSpanId: experimentContext ? rootSpanId : undefined,
+ experimentItemExpectedOutput:
+ experimentContext?.itemExpectedOutput !== undefined &&
+ experimentContext?.itemExpectedOutput !== null
+ ? stringifyValue(experimentContext.itemExpectedOutput)
+ : undefined,
+ experimentItemMetadataNames: experimentItemMetadata.names,
+ experimentItemMetadataValues: experimentItemMetadata.values,
+ } satisfies InternalTraceEventInput;
+ });
+
+ return { rootSpanId, eventInputs };
+}
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 9e1f1b3d68..7c7a223590 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -5,6 +5,10 @@ import {
VertexAIConfigSchema,
} from "../../interfaces/customLLMProviderConfigSchemas";
import { JSONObjectSchema } from "../../utils/zod";
+import type {
+ InternalTraceEventInput,
+ InternalTraceExperimentContext,
+} from "./internalTraceEvents";
// disable lint as this is exported and used in web/worker
@@ -533,16 +537,22 @@ export enum LangfuseInternalTraceEnvironment {
LLMJudge = "langfuse-llm-as-a-judge",
}
+export type ProcessedTraceEvent = {
+ type: string;
+ timestamp: string;
+ body: Record<string, unknown>;
+};
+
/**
- * Details of a generation extracted from traced events.
- * Used to pass generation information from internal tracing to callbacks.
+ * Configuration for direct writing of trace events to the events table.
+ * Used by internal tracing (prompt experiments, evaluations).
*/
-export type GenerationDetails = {
- observationId: string;
- name: string;
- input: unknown;
- output: unknown;
- metadata: Record<string, unknown>;
+export type InternalEventsWriter = {
+ experimentContext?: InternalTraceExperimentContext;
+ write: (params: {
+ rootSpanId: string;
+ eventInputs: InternalTraceEventInput[];
+ }) => Promise<void>;
};
export type TraceSinkParams = {
@@ -561,8 +571,10 @@ export type TraceSinkParams = {
version: number;
};
/**
- * Optional callback invoked after the generation events have been processed.
- * Called with merged generation details (from create + update events).
+ * When provided, traced events are written directly to the events table,
+ * bypassing the legacy traces/observations ingestion pipeline for the events write.
+ * Used for internal tracing (prompt experiments, LLM-as-a-judge evaluations). Traced
+ * events are still written to the legacy traces/observations tables.
*/
- onGenerationComplete?: (details: GenerationDetails) => void;
+ eventsWriter?: InternalEventsWriter;
};
diff --git a/packages/shared/src/utils/objects.ts b/packages/shared/src/utils/objects.ts
index 60f9d3b060..aebfb6baed 100644
--- a/packages/shared/src/utils/objects.ts
+++ b/packages/shared/src/utils/objects.ts
@@ -3,7 +3,6 @@ type OmitKeys<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
/**
* Removes specified keys from an object and returns a new object without those keys.
*/
-
export function removeObjectKeys<T, K extends keyof T>(
obj: T,
keys: K[],
@@ -14,3 +13,62 @@ export function removeObjectKeys<T, K extends keyof T>(
}
return result;
}
+
+/**
+ * Safely coerces a value to a Record if it's a plain object.
+ * Returns undefined for null, undefined, arrays, and non-objects.
+ */
+export function asRecord(value: unknown): Record<string, unknown> | undefined {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : undefined;
+}
+
+/**
+ * Safely coerces a value to a string if it's a non-empty string.
+ * Returns undefined for empty strings and non-strings.
+ */
+export function asString(value: unknown): string | undefined {
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}
+
+/**
+ * Safely coerces a value to a boolean if it's a boolean.
+ * Returns undefined for non-booleans.
+ */
+export function asBoolean(value: unknown): boolean | undefined {
+ return typeof value === "boolean" ? value : undefined;
+}
+
+/**
+ * Safely coerces a value to a string array if it's an array of strings.
+ * Returns undefined for non-arrays or arrays with non-string elements.
+ */
+export function asStringArray(value: unknown): string[] | undefined {
+ return Array.isArray(value) &&
+ value.every((entry) => typeof entry === "string")
+ ? value
+ : undefined;
+}
+
+/**
+ * Safely coerces a value to a Record<string, number> if it's an object with numeric values.
+ * Filters out non-finite numbers. Returns undefined if result is empty or input is not an object.
+ */
+export function asNumberRecord(
+ value: unknown,
+): Record<string, number> | undefined {
+ const record = asRecord(value);
+
+ if (!record) {
+ return undefined;
+ }
+
+ const normalized = Object.fromEntries(
+ Object.entries(record).filter(
+ ([, entry]) => typeof entry === "number" && Number.isFinite(entry),
+ ),
+ ) as Record<string, number>;
+
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
+}
diff --git a/worker/src/__tests__/getInternalTracingHandler.test.ts b/worker/src/__tests__/getInternalTracingHandler.test.ts
index 3fd26b6089..e894658b02 100644
--- a/worker/src/__tests__/getInternalTracingHandler.test.ts
+++ b/worker/src/__tests__/getInternalTracingHandler.test.ts
@@ -2,15 +2,16 @@ import { describe, expect, it } from "vitest";
import {
LangfuseInternalTraceEnvironment,
- prepareTracedEventsForIngestion,
+ prepareInternalTraceEvents,
} from "@langfuse/shared/src/server";
-describe("prepareTracedEventsForIngestion", () => {
+describe("prepareInternalTraceEvents", () => {
it("sets the configured environment on every forwarded event", () => {
- const preparedEvents = prepareTracedEventsForIngestion(
- [
+ const preparedEvents = prepareInternalTraceEvents({
+ events: [
{
type: "trace-create",
+ timestamp: new Date().toISOString(),
body: {
id: "trace-123",
name: "internal-trace",
@@ -19,6 +20,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "span-create",
+ timestamp: new Date().toISOString(),
body: {
id: "blocked-span",
traceId: "trace-123",
@@ -28,6 +30,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "span-update",
+ timestamp: new Date().toISOString(),
body: {
id: "blocked-span",
traceId: "trace-123",
@@ -35,6 +38,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "generation-create",
+ timestamp: new Date().toISOString(),
body: {
id: "generation-123",
traceId: "trace-123",
@@ -43,6 +47,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "generation-update",
+ timestamp: new Date().toISOString(),
body: {
id: "generation-123",
traceId: "trace-123",
@@ -54,6 +59,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "span-create",
+ timestamp: new Date().toISOString(),
body: {
id: "allowed-span",
traceId: "trace-123",
@@ -63,16 +69,15 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "span-update",
+ timestamp: new Date().toISOString(),
body: {
id: "allowed-span",
traceId: "trace-123",
},
},
],
- {
- environment: LangfuseInternalTraceEnvironment.PromptExperiments,
- },
- );
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ });
expect(preparedEvents.map((event) => event.body.id)).not.toContain(
"blocked-span",
@@ -88,10 +93,11 @@ describe("prepareTracedEventsForIngestion", () => {
});
it("adds prompt metadata only to generation-create events", () => {
- const preparedEvents = prepareTracedEventsForIngestion(
- [
+ const preparedEvents = prepareInternalTraceEvents({
+ events: [
{
type: "trace-create",
+ timestamp: new Date().toISOString(),
body: {
id: "trace-123",
name: "internal-trace",
@@ -99,6 +105,7 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "generation-create",
+ timestamp: new Date().toISOString(),
body: {
id: "generation-123",
traceId: "trace-123",
@@ -107,20 +114,19 @@ describe("prepareTracedEventsForIngestion", () => {
},
{
type: "generation-update",
+ timestamp: new Date().toISOString(),
body: {
id: "generation-123",
traceId: "trace-123",
},
},
],
- {
- environment: LangfuseInternalTraceEnvironment.PromptExperiments,
- prompt: {
- name: "internal-prompt",
- version: 3,
- },
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ prompt: {
+ name: "internal-prompt",
+ version: 3,
},
- );
+ });
expect(preparedEvents).toEqual(
expect.arrayContaining([
diff --git a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
new file mode 100644
index 0000000000..a90656f23a
--- /dev/null
+++ b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { createProductionEvalExecutionDeps } from "../evalExecutionDeps";
+
+const { mockFetchLLMCompletion } = vi.hoisted(() => ({
+ mockFetchLLMCompletion: vi.fn(),
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const original =
+ await importOriginal<typeof import("@langfuse/shared/src/server")>();
+ return {
+ ...original,
+ fetchLLMCompletion: mockFetchLLMCompletion,
+ };
+});
+
+vi.mock("../../../env", async (importOriginal) => {
+ const original = (await importOriginal()) as { env: Record<string, unknown> };
+ return {
+ ...original,
+ env: {
+ ...original.env,
+ LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE: "true",
+ },
+ };
+});
+
+describe("createProductionEvalExecutionDeps", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockFetchLLMCompletion.mockResolvedValue({ completion: "ok" });
+ });
+
+ it("enables internal direct event write for llm-as-a-judge traces", async () => {
+ const deps = createProductionEvalExecutionDeps();
+
+ await deps.callLLM({
+ messages: [
+ {
+ role: "user",
+ type: "user",
+ content: "Judge this answer",
+ },
+ ],
+ modelConfig: {
+ provider: "openai",
+ model: "gpt-4.1",
+ apiKey: {
+ adapter: "openai",
+ secretKey: "secret",
+ },
+ adapter: "openai" as any,
+ modelParams: {},
+ },
+ structuredOutputSchema: {} as any,
+ traceSinkParams: {
+ targetProjectId: "project-123",
+ traceId: "trace-123",
+ traceName: "Judge trace",
+ environment: "langfuse-llm-as-a-judge",
+ metadata: {
+ score_id: "score-123",
+ },
+ },
+ });
+
+ expect(mockFetchLLMCompletion).toHaveBeenCalledWith(
+ expect.objectContaining({
+ traceSinkParams: expect.objectContaining({
+ traceId: "trace-123",
+ environment: "langfuse-llm-as-a-judge",
+ eventsWriter: expect.objectContaining({
+ write: expect.any(Function),
+ }),
+ }),
+ }),
+ );
+ });
+});
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
index 080c190fec..55db56ef26 100644
--- a/worker/src/features/evaluation/evalExecutionDeps.ts
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -12,6 +12,7 @@ import {
import { env } from "../../env";
import { buildEvalMessages } from "./evalRuntime";
import { getEvalS3StorageClient } from "./s3StorageClient";
+import { createInternalEventsWriter } from "../internal-tracing/createInternalEventsWriter";
type StructuredOutputSchema = NonNullable<
Parameters<typeof fetchLLMCompletion>[0]["structuredOutputSchema"]
@@ -207,6 +208,7 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
traceName: params.traceSinkParams.traceName,
environment: params.traceSinkParams.environment,
metadata: params.traceSinkParams.metadata,
+ eventsWriter: createInternalEventsWriter(),
},
});
},
diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
index da8357f550..3605c7032e 100644
--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts
+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts
@@ -231,6 +231,7 @@ export async function getRelevantObservations(
AND o.trace_id IN {traceIds: Array(String)}
AND o.start_time >= {minTime: DateTime64(3)} - interval 4 hour
AND o.start_time <= {maxTime: DateTime64(3)} + interval 7 day
+ AND coalesce(o.environment, '') != 'langfuse-prompt-experiment'
ORDER BY o.event_ts DESC
LIMIT 1 BY o.project_id, o.id
`;
@@ -311,6 +312,7 @@ export async function getRelevantTraces(
AND t.id IN {traceIds: Array(String)}
AND t.timestamp >= {minTime: DateTime64(3)} - interval 4 hour
AND t.timestamp <= {maxTime: DateTime64(3)} + interval 7 day
+ AND coalesce(t.environment, '') != 'langfuse-prompt-experiment'
ORDER BY t.event_ts DESC
LIMIT 1 BY t.project_id, t.id
`;
diff --git a/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts b/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
index a003255ef6..db16c553c3 100644
--- a/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
+++ b/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
@@ -1,20 +1,113 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
- extractGenerationDetails,
+ convertEventRecordToObservationForEval,
LangfuseInternalTraceEnvironment,
- type GenerationDetails,
+} from "@langfuse/shared";
+import {
+ buildInternalTraceEventInputs,
+ materializeInternalTrace,
+ prepareInternalTraceEvents,
} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
import type { ObservationForEval } from "../../evaluation/observationEval";
+import { IngestionService } from "../../../services/IngestionService";
+import * as clickhouseWriterExports from "../../../services/ClickhouseWriter";
+import { scheduleExperimentObservationEvals } from "../scheduleExperimentEvals";
+
+const {
+ mockAddToClickhouseWriter,
+ mockFetchObservationEvalConfigs,
+ mockCreateObservationEvalSchedulerDeps,
+ mockScheduleObservationEvals,
+} = vi.hoisted(() => ({
+ mockAddToClickhouseWriter: vi.fn(),
+ mockFetchObservationEvalConfigs: vi.fn(),
+ mockCreateObservationEvalSchedulerDeps: vi.fn(),
+ mockScheduleObservationEvals: vi.fn(),
+}));
+
+vi.mock("../../../services/ClickhouseWriter", async (importOriginal) => {
+ const original = (await importOriginal()) as object;
+ return {
+ ...original,
+ ClickhouseWriter: {
+ getInstance: () => ({
+ addToQueue: mockAddToClickhouseWriter,
+ }),
+ },
+ };
+});
+
+vi.mock("../../evaluation/observationEval", async (importOriginal) => {
+ const original = (await importOriginal()) as object;
+ return {
+ ...original,
+ fetchObservationEvalConfigs: mockFetchObservationEvalConfigs,
+ createObservationEvalSchedulerDeps: mockCreateObservationEvalSchedulerDeps,
+ scheduleObservationEvals: mockScheduleObservationEvals,
+ };
+});
+
+const mockClickhouseClient = {
+ query: async () => ({
+ json: async () => [],
+ query_id: "test-query-id",
+ response_headers: { "x-clickhouse-summary": "[]" },
+ }),
+};
+
+const ingestionService = new IngestionService(
+ null as any,
+ prisma,
+ clickhouseWriterExports.ClickhouseWriter.getInstance() as any,
+ mockClickhouseClient as any,
+);
+
+const traceId = "4a56b6d74bbdffd08b9a2485f3315eeb";
+const generationId = "d6f103ed-6ef6-4f83-a520-ab746e717360";
+const blockedParserSpanId = "8bd2ff9f-1d45-4240-9581-45a7190c77fd";
+
+const prompt = { name: "Capital guesser", version: 1 };
+
+const datasetItem = {
+ id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
+ datasetId: "cml1yj2ag0001xsej1fcv6vz8",
+ validFrom: new Date("2026-01-31T06:57:38.646Z"),
+ expectedOutput: { capital: "Berlin" },
+ metadata: {
+ region: "EU",
+ difficulty: "easy",
+ },
+ input: {
+ country: "Germany",
+ },
+} as any;
+
+const config = {
+ runId: "run-456",
+ datasetRun: {
+ name: "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
+ description: "Prompt experiment run",
+ metadata: {
+ prompt_id: "prompt-123",
+ provider: "openai",
+ model: "gpt-4.1",
+ model_params: {},
+ experiment_name: "Prompt Capital guesser-v1 on dataset countries",
+ experiment_run_name:
+ "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
+ },
+ },
+} as any;
-// Real events captured from an experiment run
-// These events show the pattern: multiple generation-create and generation-update events with the same id
+// Real events captured from an experiment run.
const realExperimentEvents = [
{
id: "669353e4-e6a5-451e-9eab-1b33c9e396d5",
type: "trace-create",
timestamp: "2026-01-31T06:58:02.221Z",
body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ id: traceId,
timestamp: "2026-01-31T06:58:02.218Z",
environment: "langfuse-prompt-experiment",
name: "dataset-run-item-008e4",
@@ -42,10 +135,10 @@ const realExperimentEvents = [
type: "span-create",
timestamp: "2026-01-31T06:58:02.221Z",
body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ id: traceId,
startTime: "2026-01-31T06:58:02.218Z",
environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
name: "dataset-run-item-008e4",
metadata: {
dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
@@ -71,10 +164,10 @@ const realExperimentEvents = [
type: "generation-create",
timestamp: "2026-01-31T06:58:02.222Z",
body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
+ id: generationId,
startTime: "2026-01-31T06:58:02.220Z",
environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
name: "ChatOpenAI",
metadata: {
tags: ["seq:step:1"],
@@ -87,7 +180,7 @@ const realExperimentEvents = [
ls_model_name: "gpt-4.1",
ls_model_type: "chat",
},
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ parentObservationId: traceId,
input: [
{
content: "You are a euro capital guesser.",
@@ -107,10 +200,10 @@ const realExperimentEvents = [
type: "generation-create",
timestamp: "2026-01-31T06:58:02.230Z",
body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
+ id: generationId,
startTime: "2026-01-31T06:58:02.220Z",
environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
name: "ChatOpenAI",
metadata: {
tags: ["seq:step:1"],
@@ -123,7 +216,7 @@ const realExperimentEvents = [
ls_model_name: "gpt-4.1",
ls_model_type: "chat",
},
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ parentObservationId: traceId,
input: [
{
content: "You are a euro capital guesser.",
@@ -143,9 +236,9 @@ const realExperimentEvents = [
type: "generation-update",
timestamp: "2026-01-31T06:58:03.708Z",
body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
+ id: generationId,
model: "gpt-4.1-2025-04-14",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
output: {
content: "The capital of Germany is Berlin.",
role: "assistant",
@@ -176,9 +269,9 @@ const realExperimentEvents = [
type: "generation-update",
timestamp: "2026-01-31T06:58:03.708Z",
body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
+ id: generationId,
model: "gpt-4.1-2025-04-14",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
output: {
content: "The capital of Germany is Berlin.",
role: "assistant",
@@ -209,11 +302,11 @@ const realExperimentEvents = [
type: "span-create",
timestamp: "2026-01-31T06:58:03.709Z",
body: {
- id: "8bd2ff9f-1d45-4240-9581-45a7190c77fd",
+ id: blockedParserSpanId,
startTime: "2026-01-31T06:58:03.708Z",
environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ traceId,
+ parentObservationId: traceId,
name: "StrOutputParser",
metadata: {
tags: ["seq:step:2"],
@@ -231,8 +324,8 @@ const realExperimentEvents = [
type: "span-update",
timestamp: "2026-01-31T06:58:03.709Z",
body: {
- id: "8bd2ff9f-1d45-4240-9581-45a7190c77fd",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ id: blockedParserSpanId,
+ traceId,
output: "The capital of Germany is Berlin.",
endTime: "2026-01-31T06:58:03.709Z",
},
@@ -242,8 +335,8 @@ const realExperimentEvents = [
type: "span-update",
timestamp: "2026-01-31T06:58:03.710Z",
body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ id: traceId,
+ traceId,
output: "The capital of Germany is Berlin.",
endTime: "2026-01-31T06:58:03.709Z",
},
@@ -253,7 +346,7 @@ const realExperimentEvents = [
type: "trace-create",
timestamp: "2026-01-31T06:58:03.710Z",
body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
+ id: traceId,
timestamp: "2026-01-31T06:58:03.709Z",
environment: "langfuse-prompt-experiment",
output: "The capital of Germany is Berlin.",
@@ -262,165 +355,229 @@ const realExperimentEvents = [
},
];
-describe("extractGenerationDetails", () => {
- it("should extract and merge generation details from real experiment events", () => {
- const result = extractGenerationDetails(realExperimentEvents);
+function getProcessedExperimentEvents() {
+ return prepareInternalTraceEvents({
+ events: realExperimentEvents as any,
+ environment: "langfuse-prompt-experiment",
+ prompt,
+ });
+}
+
+function getExperimentContext() {
+ return {
+ id: config.runId,
+ name: config.datasetRun.name,
+ metadata: config.datasetRun.metadata,
+ description: config.datasetRun.description,
+ datasetId: datasetItem.datasetId,
+ itemId: datasetItem.id,
+ itemVersion: datasetItem.validFrom
+ .toISOString()
+ .replace("T", " ")
+ .replace("Z", ""),
+ itemExpectedOutput: datasetItem.expectedOutput,
+ itemMetadata: datasetItem.metadata,
+ };
+}
+
+describe("prompt experiment direct-write materialization", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
- expect(result).not.toBeNull();
- expect(result!.observationId).toBe("d6f103ed-6ef6-4f83-a520-ab746e717360");
- expect(result!.name).toBe("ChatOpenAI");
+ it("should filter parser spans and use the trace root as the experiment root", () => {
+ const processedEvents = getProcessedExperimentEvents();
+ const { rootSpanId, snapshots } = materializeInternalTrace({
+ processedEvents,
+ traceId,
+ });
+
+ expect(processedEvents.map((event) => event.body.id)).not.toContain(
+ blockedParserSpanId,
+ );
+ expect(rootSpanId).toBe(traceId);
+ expect(snapshots).toHaveLength(2);
- // Input should come from generation-create events
- expect(result!.input).toEqual([
- { content: "You are a euro capital guesser.", role: "system" },
- { content: "What is the capital of Germany?", role: "user" },
- ]);
+ const rootSnapshot = snapshots.find(
+ (snapshot) => snapshot.spanId === traceId,
+ );
+ const generationSnapshot = snapshots.find(
+ (snapshot) => snapshot.spanId === generationId,
+ );
- // Output should come from generation-update events
- expect(result!.output).toEqual({
- content: "The capital of Germany is Berlin.",
- role: "assistant",
+ expect(rootSnapshot).toMatchObject({
+ spanId: traceId,
+ traceId,
+ type: "SPAN",
+ name: "dataset-run-item-008e4",
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ input: [
+ { content: "You are a euro capital guesser.", role: "system" },
+ { content: "What is the capital of Germany?", role: "user" },
+ ],
+ output: "The capital of Germany is Berlin.",
+ metadata: {
+ dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
+ dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
+ experiment_name: "Prompt Capital guesser-v1 on dataset countries",
+ experiment_run_name:
+ "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
+ },
+ endTimeISO: "2026-01-31T06:58:03.709Z",
});
- // Metadata should be merged from all generation events
- expect(result!.metadata).toEqual({
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
+ expect(generationSnapshot).toMatchObject({
+ spanId: generationId,
+ traceId,
+ parentSpanId: traceId,
+ type: "GENERATION",
+ name: "ChatOpenAI",
+ promptName: "Capital guesser",
+ promptVersion: "1",
+ modelName: "gpt-4.1-2025-04-14",
});
});
- it("should return null when no generation events are present", () => {
- const nonGenerationEvents = realExperimentEvents.filter(
- (e) => !e.type.startsWith("generation"),
- );
+ it("should build trace-rooted event inputs with experiment metadata", async () => {
+ const { rootSpanId, eventInputs } = buildInternalTraceEventInputs({
+ processedEvents: getProcessedExperimentEvents(),
+ traceId,
+ projectId: "project-123",
+ experimentContext: getExperimentContext(),
+ });
- const result = extractGenerationDetails(nonGenerationEvents);
+ // Direct write uses original IDs (no t- prefix remapping).
+ // The experiment backfill job skips traces already in events_core via LEFT ANTI JOIN.
+ expect(rootSpanId).toBe(traceId);
+ expect(eventInputs).toHaveLength(2);
- expect(result).toBeNull();
- });
+ const rootEventInput = eventInputs.find(
+ (eventInput) => eventInput.spanId === traceId,
+ );
+ const generationEventInput = eventInputs.find(
+ (eventInput) => eventInput.spanId === generationId,
+ );
+
+ expect(rootEventInput).toMatchObject({
+ projectId: "project-123",
+ traceId,
+ spanId: traceId,
+ parentSpanId: undefined,
+ type: "SPAN",
+ experimentId: "run-456",
+ experimentName:
+ "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
+ experimentItemRootSpanId: traceId,
+ input: JSON.stringify([
+ { content: "You are a euro capital guesser.", role: "system" },
+ { content: "What is the capital of Germany?", role: "user" },
+ ]),
+ output: "The capital of Germany is Berlin.",
+ source: "ingestion-api-dual-write-experiments",
+ });
- it("should return null for empty events array", () => {
- const result = extractGenerationDetails([]);
+ expect(generationEventInput).toMatchObject({
+ traceId,
+ spanId: generationId,
+ parentSpanId: traceId,
+ type: "GENERATION",
+ promptName: "Capital guesser",
+ promptVersion: "1",
+ modelName: "gpt-4.1-2025-04-14",
+ });
- expect(result).toBeNull();
+ const rootEventRecord = await ingestionService.createEventRecord(
+ rootEventInput!,
+ "",
+ );
+ const rootObservation =
+ convertEventRecordToObservationForEval(rootEventRecord);
+
+ expect(rootObservation.span_id).toBe(traceId);
+ expect(rootObservation.experiment_item_root_span_id).toBe(traceId);
+ expect(rootObservation.type).toBe("SPAN");
+ expect(rootObservation.name).toBe("dataset-run-item-008e4");
+ expect(rootObservation.experiment_id).toBe("run-456");
+ expect(rootObservation.experiment_name).toBe(
+ "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
+ );
+ expect(rootObservation.experiment_item_expected_output).toBe(
+ JSON.stringify({ capital: "Berlin" }),
+ );
});
- it("should handle events without generation id", () => {
- const eventsWithoutId = [
- {
- type: "generation-create",
- body: { name: "test" }, // No id field
- },
- ];
+ it("should build non-experiment internal traces without experiment columns", () => {
+ const { eventInputs } = buildInternalTraceEventInputs({
+ processedEvents: getProcessedExperimentEvents(),
+ traceId,
+ projectId: "project-123",
+ });
- const result = extractGenerationDetails(eventsWithoutId);
+ const rootEventInput = eventInputs.find(
+ (eventInput) => eventInput.spanId === traceId,
+ );
- expect(result).toBeNull();
+ expect(rootEventInput).toMatchObject({
+ spanId: traceId,
+ source: "ingestion-api-dual-write",
+ experimentId: undefined,
+ experimentItemRootSpanId: undefined,
+ });
});
+});
- it("should merge metadata from multiple generation events", () => {
- const eventsWithDifferentMetadata = [
- {
- type: "generation-create",
- body: {
- id: "gen-1",
- name: "test",
- metadata: { key1: "value1" },
- },
- },
- {
- type: "generation-update",
- body: {
- id: "gen-1",
- metadata: { key2: "value2" },
- },
- },
- ];
-
- const result = extractGenerationDetails(eventsWithDifferentMetadata);
-
- expect(result!.metadata).toEqual({
- key1: "value1",
- key2: "value2",
+describe("scheduleExperimentObservationEvals", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockFetchObservationEvalConfigs.mockResolvedValue([{ id: "config-1" }]);
+ mockCreateObservationEvalSchedulerDeps.mockReturnValue({
+ uploadObservationToS3: vi.fn(),
+ upsertJobExecution: vi.fn(),
+ enqueueEvalJob: vi.fn(),
});
+ mockScheduleObservationEvals.mockResolvedValue(undefined);
});
- it("should use default name when name is not provided", () => {
- const eventsWithoutName = [
- {
- type: "generation-create",
- body: {
- id: "gen-1",
- // No name field
- },
- },
- ];
+ it("should schedule evals against the trace-root observation", async () => {
+ const { eventInputs } = buildInternalTraceEventInputs({
+ processedEvents: getProcessedExperimentEvents(),
+ traceId,
+ projectId: "project-123",
+ experimentContext: getExperimentContext(),
+ });
+ const rootEventInput = eventInputs.find(
+ (eventInput) => eventInput.spanId === traceId,
+ );
+ const rootEventRecord = await ingestionService.createEventRecord(
+ rootEventInput!,
+ "",
+ );
+ const observation = convertEventRecordToObservationForEval(rootEventRecord);
- const result = extractGenerationDetails(eventsWithoutName);
+ await scheduleExperimentObservationEvals({ observation });
- expect(result!.name).toBe("generation");
+ expect(mockFetchObservationEvalConfigs).toHaveBeenCalledWith("project-123");
+ expect(mockScheduleObservationEvals).toHaveBeenCalledWith({
+ observation,
+ configs: [{ id: "config-1" }],
+ schedulerDeps: expect.any(Object),
+ });
+ expect(observation.span_id).toBe(traceId);
+ expect(observation.experiment_item_root_span_id).toBe(traceId);
});
-});
-describe("buildObservationForEval", () => {
- // Helper function that mirrors the logic in scheduleExperimentObservationEvals
- function buildObservationForEval(params: {
- projectId: string;
- traceId: string;
- generationDetails: GenerationDetails;
- config: {
- runId: string;
- experimentName?: string;
- prompt?: { name: string; version: number };
- };
- datasetItem: {
- id: string;
- datasetId: string;
- expectedOutput?: unknown;
- };
- }): ObservationForEval {
- const { projectId, traceId, generationDetails, config, datasetItem } =
- params;
-
- return {
- // Identifiers
- span_id: generationDetails.observationId,
- trace_id: traceId,
- project_id: projectId,
+ it("should skip scheduling when no configs exist", async () => {
+ mockFetchObservationEvalConfigs.mockResolvedValue([]);
- // Core properties
- type: "GENERATION",
- name: generationDetails.name || "generation",
+ const observation = {
+ span_id: traceId,
+ trace_id: traceId,
+ project_id: "project-123",
+ type: "SPAN",
+ name: "dataset-run-item-008e4",
environment: LangfuseInternalTraceEnvironment.PromptExperiments,
level: "DEFAULT",
-
- // Prompt info
- prompt_name: config.prompt?.name,
- prompt_version: config.prompt?.version,
-
- // Experiment fields - critical for matching
- experiment_id: config.runId,
- experiment_name: config.experimentName,
- experiment_dataset_id: datasetItem.datasetId,
- experiment_item_id: datasetItem.id,
- experiment_item_expected_output: datasetItem.expectedOutput
- ? JSON.stringify(datasetItem.expectedOutput)
- : null,
- experiment_item_root_span_id: generationDetails.observationId, // Same as span_id for root
-
- // Data fields
- input: generationDetails.input,
- output: generationDetails.output,
- metadata: generationDetails.metadata,
-
- // Empty defaults
+ experiment_item_root_span_id: traceId,
tags: [],
provided_usage_details: {},
provided_cost_details: {},
@@ -429,142 +586,10 @@ describe("buildObservationForEval", () => {
tool_definitions: {},
tool_calls: [],
tool_call_names: [],
- tool_call_count: 0,
- };
- }
-
- it("should build correct ObservationForEval from real experiment events", () => {
- // Extract generation details from real events
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- // Build ObservationForEval
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- generationDetails,
- config: {
- runId: "run-456",
- experimentName: "Prompt Capital guesser-v1 on dataset countries",
- prompt: { name: "Capital guesser", version: 1 },
- },
- datasetItem: {
- id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- datasetId: "cml1yj2ag0001xsej1fcv6vz8",
- expectedOutput: { capital: "Berlin" },
- },
- });
-
- // Verify identifiers
- expect(observation.span_id).toBe("d6f103ed-6ef6-4f83-a520-ab746e717360");
- expect(observation.trace_id).toBe("4a56b6d74bbdffd08b9a2485f3315eeb");
- expect(observation.project_id).toBe("project-123");
-
- // Verify core properties
- expect(observation.type).toBe("GENERATION");
- expect(observation.name).toBe("ChatOpenAI");
- expect(observation.environment).toBe(
- LangfuseInternalTraceEnvironment.PromptExperiments,
- );
- expect(observation.level).toBe("DEFAULT");
-
- // Verify prompt info
- expect(observation.prompt_name).toBe("Capital guesser");
- expect(observation.prompt_version).toBe(1);
-
- // Verify experiment fields (critical for filter matching)
- expect(observation.experiment_id).toBe("run-456");
- expect(observation.experiment_name).toBe(
- "Prompt Capital guesser-v1 on dataset countries",
- );
- expect(observation.experiment_dataset_id).toBe("cml1yj2ag0001xsej1fcv6vz8");
- expect(observation.experiment_item_id).toBe(
- "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- );
- expect(observation.experiment_item_expected_output).toBe(
- JSON.stringify({ capital: "Berlin" }),
- );
- // Root span ID should equal span_id for experiment evals
- expect(observation.experiment_item_root_span_id).toBe(observation.span_id);
-
- // Verify data fields
- expect(observation.input).toEqual([
- { content: "You are a euro capital guesser.", role: "system" },
- { content: "What is the capital of Germany?", role: "user" },
- ]);
- expect(observation.output).toEqual({
- content: "The capital of Germany is Berlin.",
- role: "assistant",
- });
-
- // Verify metadata includes experiment context
- expect(observation.metadata).toEqual({
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
- });
- });
-
- it("should set experiment_item_root_span_id equal to span_id for root observations", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: { runId: "run-789" },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- },
- });
-
- // This is critical for experiment eval filter matching
- // The filter checks: span_id === experiment_item_root_span_id
- expect(observation.experiment_item_root_span_id).toBe(observation.span_id);
- });
-
- it("should handle missing expectedOutput gracefully", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: { runId: "run-789" },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- expectedOutput: undefined, // No expected output
- },
- });
+ } as ObservationForEval;
- expect(observation.experiment_item_expected_output).toBeNull();
- });
-
- it("should handle missing prompt info gracefully", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: {
- runId: "run-789",
- // No prompt provided
- },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- },
- });
+ await scheduleExperimentObservationEvals({ observation });
- expect(observation.prompt_name).toBeUndefined();
- expect(observation.prompt_version).toBeUndefined();
+ expect(mockScheduleObservationEvals).not.toHaveBeenCalled();
});
});
diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.ts
index 925cae7685..c5853327e3 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -1,12 +1,17 @@
-import { DatasetItemDomain, Prisma } from "@langfuse/shared";
+import {
+ asRecord,
+ convertEventRecordToObservationForEval,
+ DatasetItemDomain,
+ Prisma,
+} from "@langfuse/shared";
import {
ChatMessage,
+ convertDateToClickhouseDateTime,
createDatasetItemFilterState,
DatasetRunItemUpsertQueue,
eventTypes,
ExperimentCreateEventSchema,
fetchLLMCompletion,
- GenerationDetails,
getDatasetItems,
IngestionEventType,
LangfuseInternalTraceEnvironment,
@@ -32,6 +37,7 @@ import {
import { randomUUID } from "crypto";
import { createW3CTraceId } from "../utils";
import { scheduleExperimentObservationEvals } from "./scheduleExperimentEvals";
+import { createInternalEventsWriter } from "../internal-tracing/createInternalEventsWriter";
async function getExistingRunItemDatasetItemIds(
projectId: string,
@@ -126,20 +132,6 @@ async function processItem(
if (!llmResult.success) return { success: false };
- /********************
- * SCHEDULE EXPERIMENT OBSERVATION EVALS *
- ********************/
-
- if (llmResult.generationDetails) {
- await scheduleExperimentObservationEvals({
- projectId,
- traceId: newTraceId,
- datasetItem,
- config,
- generationDetails: llmResult.generationDetails,
- });
- }
-
/********************
* ASYNC RUN ITEM EVAL *
********************/
@@ -169,7 +161,7 @@ async function processLLMCall(
traceId: string,
datasetItem: DatasetItemDomain & { input: Prisma.JsonObject },
config: PromptExperimentConfig,
-): Promise<{ success: boolean; generationDetails?: GenerationDetails }> {
+): Promise<{ success: boolean }> {
let messages: ChatMessage[] = [];
// Extract and replace variables in prompt
try {
@@ -186,9 +178,6 @@ async function processLLMCall(
);
return { success: false };
}
-
- let generationDetails: GenerationDetails | null = null;
-
const traceSinkParams: TraceSinkParams = {
environment: LangfuseInternalTraceEnvironment.PromptExperiments,
traceName: `dataset-run-item-${runItemId.slice(0, 5)}`,
@@ -202,9 +191,24 @@ async function processLLMCall(
experiment_run_name: config.experimentRunName,
},
prompt: config.prompt,
- onGenerationComplete: (details) => {
- generationDetails = details;
- },
+ eventsWriter: createInternalEventsWriter({
+ experimentContext: {
+ id: config.runId,
+ name: config.datasetRun.name,
+ metadata: asRecord(config.datasetRun.metadata),
+ description: config.datasetRun.description,
+ datasetId: datasetItem.datasetId,
+ itemId: datasetItem.id,
+ itemVersion: convertDateToClickhouseDateTime(datasetItem.validFrom),
+ itemExpectedOutput: datasetItem.expectedOutput,
+ itemMetadata: asRecord(datasetItem.metadata),
+ },
+ onRootEventRecordReady: async (rootEventRecord) => {
+ await scheduleExperimentObservationEvals({
+ observation: convertEventRecordToObservationForEval(rootEventRecord),
+ });
+ },
+ }),
};
await fetchLLMCompletion({
@@ -222,10 +226,7 @@ async function processLLMCall(
traceSinkParams,
}).catch(); // catch errors and do not retry
- return {
- success: true,
- generationDetails: generationDetails ?? undefined,
- };
+ return { success: true };
}
async function getItemsToProcess(
diff --git a/worker/src/features/experiments/scheduleExperimentEvals.ts b/worker/src/features/experiments/scheduleExperimentEvals.ts
index 4fe89e7a4f..76bddd81a9 100644
--- a/worker/src/features/experiments/scheduleExperimentEvals.ts
+++ b/worker/src/features/experiments/scheduleExperimentEvals.ts
@@ -1,9 +1,3 @@
-import { DatasetItemDomain } from "@langfuse/shared";
-import { PromptExperimentConfig } from "./utils";
-import {
- GenerationDetails,
- LangfuseInternalTraceEnvironment,
-} from "@langfuse/shared/src/server";
import {
fetchObservationEvalConfigs,
scheduleObservationEvals,
@@ -13,83 +7,20 @@ import {
import { logger, traceException } from "@langfuse/shared/src/server";
interface ScheduleExperimentEvalsParams {
- projectId: string;
- traceId: string;
- datasetItem: DatasetItemDomain;
- config: PromptExperimentConfig;
- generationDetails: GenerationDetails;
+ observation: ObservationForEval;
}
-/**
- * Schedule observation evals for an experiment generation.
- *
- * This function is called after an experiment LLM call completes to schedule
- * any configured observation-level evals. It mirrors the eval scheduling that
- * happens in the OTEL ingestion queue for externally-ingested observations.
- *
- * @param params.projectId - The project ID
- * @param params.traceId - The trace ID for the experiment run
- * @param params.datasetItem - The dataset item being evaluated
- * @param params.config - The prompt experiment configuration
- * @param params.generationDetails - The generation details extracted from traced events
- */
export async function scheduleExperimentObservationEvals(
params: ScheduleExperimentEvalsParams,
): Promise<void> {
- const { projectId, traceId, datasetItem, config, generationDetails } = params;
+ const { observation } = params;
try {
- // 1. Fetch experiment-targeted eval configs
- const configs = await fetchObservationEvalConfigs(projectId);
- if (configs.length === 0) return;
-
- // 2. Build ObservationForEval with experiment context
- // Note: metadata from generation events contains additional context
- // (dataset_id, dataset_item_id, experiment_name, experiment_run_name, etc.)
- const observation: ObservationForEval = {
- // Identifiers
- span_id: generationDetails.observationId,
- trace_id: traceId,
- project_id: projectId,
-
- // Core properties
- type: "GENERATION",
- name: generationDetails.name || "generation",
- environment: LangfuseInternalTraceEnvironment.PromptExperiments,
- level: "DEFAULT",
-
- // Prompt info
- prompt_name: config.prompt?.name,
- prompt_version: config.prompt?.version,
-
- // Experiment fields - critical for matching
- experiment_id: config.runId,
- experiment_name: config.experimentName,
- experiment_dataset_id: datasetItem.datasetId,
- experiment_item_id: datasetItem.id,
- experiment_item_expected_output: datasetItem.expectedOutput
- ? JSON.stringify(datasetItem.expectedOutput)
- : null,
- experiment_item_root_span_id: generationDetails.observationId, // Same as span_id for root
-
- // Data fields
- input: generationDetails.input,
- output: generationDetails.output,
- metadata: generationDetails.metadata, // Include metadata from merged generation events
-
- // Empty defaults
- tags: [],
- provided_usage_details: {},
- provided_cost_details: {},
- usage_details: {},
- cost_details: {},
- tool_definitions: {},
- tool_calls: [],
- tool_call_names: [],
- tool_call_count: 0,
- };
+ const configs = await fetchObservationEvalConfigs(observation.project_id);
+ if (configs.length === 0) {
+ return;
+ }
- // 3. Schedule evals
const schedulerDeps = createObservationEvalSchedulerDeps();
await scheduleObservationEvals({
observation,
@@ -98,18 +29,18 @@ export async function scheduleExperimentObservationEvals(
});
logger.info("Scheduled experiment observation evals", {
- projectId,
- traceId,
- observationId: generationDetails.observationId,
+ projectId: observation.project_id,
+ traceId: observation.trace_id,
+ observationId: observation.span_id,
configCount: configs.length,
});
} catch (error) {
traceException(error);
logger.error("Failed to schedule experiment observation evals", {
error,
- projectId,
- traceId,
+ projectId: observation.project_id,
+ traceId: observation.trace_id,
+ observationId: observation.span_id,
});
- // Don't rethrow - eval scheduling should not fail the experiment
}
}
diff --git a/worker/src/features/internal-tracing/__tests__/getInternalTracingHandler.test.ts b/worker/src/features/internal-tracing/__tests__/getInternalTracingHandler.test.ts
new file mode 100644
index 0000000000..f7cbd1d117
--- /dev/null
+++ b/worker/src/features/internal-tracing/__tests__/getInternalTracingHandler.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { mockExportLocalEvents, mockProcessEventBatch, mockWrite } = vi.hoisted(
+ () => ({
+ mockExportLocalEvents: vi.fn(),
+ mockProcessEventBatch: vi.fn(),
+ mockWrite: vi.fn(),
+ }),
+);
+
+vi.mock("langfuse-langchain", () => {
+ return {
+ default: class MockCallbackHandler {
+ public langfuse = {
+ _exportLocalEvents: mockExportLocalEvents,
+ };
+
+ constructor(_params: Record<string, unknown>) {}
+ },
+ };
+});
+
+vi.mock(
+ "../../../../../packages/shared/src/server/ingestion/processEventBatch",
+ () => ({
+ processEventBatch: mockProcessEventBatch,
+ }),
+);
+
+import { getInternalTracingHandler } from "../../../../../packages/shared/src/server/llm/getInternalTracingHandler";
+import { LangfuseInternalTraceEnvironment } from "@langfuse/shared";
+
+const traceId = "trace-123";
+const processedEventsFixture = [
+ {
+ type: "trace-create",
+ timestamp: "2026-01-31T06:58:02.221Z",
+ body: {
+ id: traceId,
+ traceId,
+ startTime: "2026-01-31T06:58:02.218Z",
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ name: "dataset-run-item-008e4",
+ input: [{ role: "user", content: "Hello" }],
+ },
+ },
+ {
+ type: "generation-create",
+ timestamp: "2026-01-31T06:58:02.222Z",
+ body: {
+ id: "generation-123",
+ traceId,
+ parentObservationId: traceId,
+ startTime: "2026-01-31T06:58:02.220Z",
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ name: "ChatOpenAI",
+ input: [{ role: "user", content: "Hello" }],
+ model: "gpt-4.1",
+ },
+ },
+ {
+ type: "generation-update",
+ timestamp: "2026-01-31T06:58:03.708Z",
+ body: {
+ id: "generation-123",
+ traceId,
+ output: { role: "assistant", content: "Hi" },
+ endTime: "2026-01-31T06:58:03.707Z",
+ usageDetails: {
+ input: 10,
+ output: 5,
+ total: 15,
+ },
+ },
+ },
+];
+
+describe("getInternalTracingHandler", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockExportLocalEvents.mockResolvedValue(processedEventsFixture);
+ mockProcessEventBatch.mockResolvedValue({
+ successes: [],
+ errors: [],
+ });
+ mockWrite.mockResolvedValue(undefined);
+ });
+
+ it("disables staging propagation when direct event write is enabled", async () => {
+ const { processTracedEvents } = getInternalTracingHandler({
+ targetProjectId: "project-123",
+ traceId,
+ traceName: "internal-trace",
+ environment: LangfuseInternalTraceEnvironment.PromptExperiments,
+ eventsWriter: {
+ experimentContext: {
+ id: "run-123",
+ name: "Prompt run",
+ datasetId: "dataset-123",
+ itemId: "item-123",
+ itemVersion: "2026-01-31T06:57:38.646Z",
+ },
+ write: mockWrite,
+ },
+ });
+
+ await processTracedEvents();
+
+ expect(mockProcessEventBatch).toHaveBeenCalledWith(
+ expect.any(Array),
+ expect.any(Object),
+ expect.objectContaining({
+ isLangfuseInternal: true,
+ forwardToEventsTable: false,
+ }),
+ );
+ });
+
+ it("keeps legacy forwarding behavior when direct event write is disabled", async () => {
+ const { processTracedEvents } = getInternalTracingHandler({
+ targetProjectId: "project-123",
+ traceId,
+ traceName: "internal-trace",
+ environment: LangfuseInternalTraceEnvironment.LLMJudge,
+ });
+
+ await processTracedEvents();
+
+ expect(mockProcessEventBatch).toHaveBeenCalledWith(
+ expect.any(Array),
+ expect.any(Object),
+ expect.objectContaining({
+ isLangfuseInternal: true,
+ forwardToEventsTable: undefined,
+ }),
+ );
+ expect(mockWrite).not.toHaveBeenCalled();
+ });
+});
diff --git a/worker/src/features/internal-tracing/createInternalEventsWriter.ts b/worker/src/features/internal-tracing/createInternalEventsWriter.ts
new file mode 100644
index 0000000000..ac0bb914d6
--- /dev/null
+++ b/worker/src/features/internal-tracing/createInternalEventsWriter.ts
@@ -0,0 +1,83 @@
+import type {
+ EventRecordInsertType,
+ InternalEventsWriter,
+ InternalTraceEventInput,
+ InternalTraceExperimentContext,
+} from "@langfuse/shared/src/server";
+import { clickhouseClient, redis } from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { ClickhouseWriter } from "../../services/ClickhouseWriter";
+import { IngestionService } from "../../services/IngestionService";
+import { env } from "../../env";
+
+let internalTraceIngestionService: IngestionService | undefined;
+
+function getInternalTraceIngestionService(): IngestionService {
+ if (!internalTraceIngestionService) {
+ internalTraceIngestionService = new IngestionService(
+ redis as any,
+ prisma,
+ ClickhouseWriter.getInstance(),
+ clickhouseClient(),
+ );
+ }
+
+ return internalTraceIngestionService;
+}
+
+async function writeInternalEventInputs(params: {
+ rootSpanId: string;
+ eventInputs: InternalTraceEventInput[];
+}): Promise<{ rootEventRecord?: EventRecordInsertType }> {
+ const service = getInternalTraceIngestionService();
+
+ const eventRecords = await Promise.all(
+ params.eventInputs.map((eventInput) =>
+ service.createEventRecord(eventInput, ""),
+ ),
+ );
+
+ if (env.LANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE === "true") {
+ for (const eventRecord of eventRecords) {
+ service.writeEventRecord(eventRecord);
+ }
+ }
+
+ return {
+ rootEventRecord: eventRecords.find(
+ (record) => record.span_id === params.rootSpanId,
+ ),
+ };
+}
+
+/**
+ * Always materialize internal trace event records, even when direct events-table
+ * writes are disabled. Self-hosted setups may not have `events_full`
+ * configured, but experiment eval scheduling still depends on the normalized
+ * root event record. The env flag therefore gates only the actual enqueue into
+ * ClickHouse, not creation of the writer or invocation of the ready callback.
+ */
+export function createInternalEventsWriter(params?: {
+ experimentContext?: InternalTraceExperimentContext;
+ onRootEventRecordReady?: (
+ rootEventRecord: EventRecordInsertType,
+ ) => Promise<void>;
+}): InternalEventsWriter {
+ return {
+ experimentContext: params?.experimentContext,
+ write: async (writeParams: {
+ rootSpanId: string;
+ eventInputs: InternalTraceEventInput[];
+ }) => {
+ const { rootSpanId, eventInputs } = writeParams;
+ const { rootEventRecord } = await writeInternalEventInputs({
+ rootSpanId,
+ eventInputs,
+ });
+
+ if (rootEventRecord && params?.onRootEventRecordReady) {
+ await params.onRootEventRecordReady(rootEventRecord);
+ }
+ },
+ };
+}
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 93cfd018b5..7c5daee140 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -42,6 +42,7 @@ import {
validateAndInflateScore,
DatasetRunItemRecordInsertType,
EventRecordInsertType,
+ InternalTraceEventInput,
traceException,
flattenJsonToPathArrays,
getDatasetItemById,
@@ -80,104 +81,7 @@ type InsertRecord =
| ScoreRecordInsertType
| ObservationRecordInsertType
| DatasetRunItemRecordInsertType;
-
-/**
- * Flexible input type for writing events to the events table.
- * This is intentionally loose to allow for iteration as the events
- * table schema evolves. Only required fields are enforced.
- */
-export type EventInput = {
- // Required identifiers
- projectId: string;
- traceId: string;
- spanId: string;
- startTimeISO: string;
-
- // Optional identifiers
- orgId?: string;
- parentSpanId?: string;
-
- // Core properties
- name?: string;
- type?: string;
- environment?: string;
- version?: string;
- release?: string;
- endTimeISO: string;
- completionStartTime?: string;
-
- traceName?: string;
- tags?: string[];
- bookmarked?: boolean;
- public?: boolean;
-
- // User/session
- userId?: string;
- sessionId?: string;
- level?: string;
- statusMessage?: string;
-
- // Prompt
- promptId?: string;
- promptName?: string;
- promptVersion?: string;
-
- // Model
- modelId?: string;
- modelName?: string;
- modelParameters?: string | Record<string, unknown>;
-
- // Usage & Cost
- providedUsageDetails?: Record<string, number>;
- usageDetails?: Record<string, number>;
- providedCostDetails?: Record<string, number>;
- costDetails?: Record<string, number>;
-
- // Tool Calls
- toolDefinitions?: Record<string, string>;
- toolCalls?: string[];
- toolCallNames?: string[];
-
- // I/O
- input?: string;
- output?: string;
-
- // Metadata
- // metadata can be a complex nested object with attributes, resourceAttributes, scopeAttributes, etc.
- metadata: Record<string, unknown>;
-
- // Source/instrumentation metadata
- source: string;
- serviceName?: string;
- serviceVersion?: string;
- scopeName?: string;
- scopeVersion?: string;
- telemetrySdkLanguage?: string;
- telemetrySdkName?: string;
- telemetrySdkVersion?: string;
-
- // Storage
- blobStorageFilePath?: string;
- eventRaw?: string;
- eventBytes?: number;
-
- // Experiment fields
- experimentId?: string;
- experimentName?: string;
- experimentMetadataNames?: string[];
- experimentMetadataValues?: Array<string | null | undefined>;
- experimentDescription?: string;
- experimentDatasetId?: string;
- experimentItemId?: string;
- experimentItemVersion?: string;
- experimentItemRootSpanId?: string;
- experimentItemExpectedOutput?: string;
- experimentItemMetadataNames?: string[];
- experimentItemMetadataValues?: Array<string | null | undefined>;
-
- // Catch-all for future fields
- [key: string]: any;
-};
+export type EventInput = InternalTraceEventInput;
const immutableEntityKeys: {
[TableName.Traces]: (keyof TraceRecordInsertType)[];