🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: head based opt-in for the direct writes into v4 tables (#12025)
Valery Meleshkinb3a2628d99ea
diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 39fa02f678..e1c021b399 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -40,6 +40,9 @@ export interface OtelIngestionProcessorConfig {publicKey?: string;orgId?: string;propagatedHeaders?: Record<string, string>;+ sdkName?: string;+ sdkVersion?: string;+ ingestionVersion?: string;}interface CreateTraceEventParams {@@ -118,12 +121,18 @@ export class OtelIngestionProcessor {private readonly publicKey?: string;private readonly orgId?: string;private readonly propagatedHeaders?: Record<string, string>;+ private readonly sdkName?: string;+ private readonly sdkVersion?: string;+ private readonly ingestionVersion?: string;constructor(config: OtelIngestionProcessorConfig) {this.projectId = config.projectId;this.publicKey = config.publicKey;this.orgId = config.orgId;this.propagatedHeaders = config.propagatedHeaders;+ this.sdkName = config.sdkName;+ this.sdkVersion = config.sdkVersion;+ this.ingestionVersion = config.ingestionVersion;}/**@@ -167,6 +176,9 @@ export class OtelIngestionProcessor {},},propagatedHeaders: this.propagatedHeaders,+ sdkName: this.sdkName,+ sdkVersion: this.sdkVersion,+ ingestionVersion: this.ingestionVersion,},}): Promise.reject("Failed to instantiate otel ingestion queue");diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex aa12a14cd5..0aa8c93827 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -40,6 +40,9 @@ export const OtelIngestionEvent = z.object({}),}),propagatedHeaders: z.record(z.string(), z.string()).optional(),+ sdkName: z.string().optional(),+ sdkVersion: z.string().optional(),+ ingestionVersion: z.string().optional(),});export const BatchExportJobSchema = z.object({diff --git a/web/src/__tests__/async/otel-api.servertest.ts b/web/src/__tests__/async/otel-api.servertest.tsindex 2fc757cc83..fdd1ba76af 100644--- a/web/src/__tests__/async/otel-api.servertest.ts+++ b/web/src/__tests__/async/otel-api.servertest.ts@@ -330,6 +330,84 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {}, 25_000);}, 30_000);+ it("should accept sdk headers in underscore format", async () => {+ const traceId = randomBytes(16);+ const spanId = randomBytes(8);++ const payload = {+ resourceSpans: [+ {+ resource: {+ attributes: [],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "4.0.0",+ attributes: [+ {+ key: "public_key",+ value: { stringValue: "pk-lf-1234567890" },+ },+ ],+ },+ spans: [+ {+ traceId,+ spanId,+ name: "underscore-header-span",+ kind: 1,+ startTimeUnixNano: {+ low: 466848096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467248096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [],+ status: {},+ },+ ],+ },+ ],+ },+ ],+ };++ const response = await makeAPICall(+ "POST",+ "/api/public/otel/v1/traces",+ payload,+ undefined,+ {+ x_langfuse_sdk_name: "python",+ x_langfuse_sdk_version: "4.0.0",+ x_langfuse_ingestion_version: "4",+ },+ );++ expect(response.status).toBe(200);++ await waitForExpect(async () => {+ const trace = await getTraceById({+ projectId,+ traceId: traceId.toString("hex"),+ });+ expect(trace).toBeDefined();++ const observation = await getObservationById({+ projectId,+ id: spanId.toString("hex"),+ });+ expect(observation).toBeDefined();+ expect(observation!.name).toBe("underscore-header-span");+ }, 25_000);+ }, 30_000);+it("should transform deployment.environment to lowercase", async () => {const traceId = randomBytes(16);const spanId = randomBytes(8);diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 75c7fa957a..142cd8593b 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -11,6 +11,18 @@ import { gunzip } from "node:zlib";import { ForbiddenError } from "@langfuse/shared";import { env } from "@/src/env.mjs";+/** Read a Langfuse header that may arrive with hyphens or underscores. */+function getLangfuseHeader(+ headers: Record<string, string | string[] | undefined>,+ name: string,+): string | undefined {+ const hyphenVal = headers[name];+ if (typeof hyphenVal === "string") return hyphenVal;+ const underscoreVal = headers[name.replaceAll("-", "_")];+ if (typeof underscoreVal === "string") return underscoreVal;+ return undefined;+}+export const config = {api: {bodyParser: false,@@ -104,6 +116,32 @@ export default withMiddlewares({return {};}+ // Extract SDK headers for write path decision (supports both hyphen and underscore formats)+ const sdkName = getLangfuseHeader(req.headers, "x-langfuse-sdk-name");+ const sdkVersion = getLangfuseHeader(+ req.headers,+ "x-langfuse-sdk-version",+ );+ const ingestionVersion = getLangfuseHeader(+ req.headers,+ "x-langfuse-ingestion-version",+ );++ // Reject unsupported future ingestion versions (> 4)+ // Lower versions are valid but use dual write (path A)+ const parsedIngestionVersion = ingestionVersion+ ? parseInt(ingestionVersion, 10)+ : undefined;+ if (+ parsedIngestionVersion !== undefined &&+ (isNaN(parsedIngestionVersion) || parsedIngestionVersion > 4)+ ) {+ res.status(400);+ return {+ error: `Unsupported x-langfuse-ingestion-version: "${ingestionVersion}". Maximum supported: "4".`,+ };+ }+// Extract headers to propagate for ingestion maskingconst propagatedHeaderNames =env.LANGFUSE_INGESTION_MASKING_PROPAGATED_HEADERS;@@ -123,6 +161,9 @@ export default withMiddlewares({Object.keys(propagatedHeaders).length > 0? propagatedHeaders: undefined,+ sdkName,+ sdkVersion,+ ingestionVersion,});// At this point, we have the raw OpenTelemetry Span body. We upload the full batch to S3diff --git a/worker/src/queues/__tests__/otelDirectEventWrite.test.ts b/worker/src/queues/__tests__/otelDirectEventWrite.test.tsnew file mode 100644index 0000000000..1713c2ee2a--- /dev/null+++ b/worker/src/queues/__tests__/otelDirectEventWrite.test.ts@@ -0,0 +1,235 @@+import { describe, it, expect } from "vitest";+import {+ checkHeaderBasedDirectWrite,+ checkSdkVersionRequirements,+ getSdkInfoFromResourceSpans,+ type SdkInfo,+} from "../otelIngestionQueue";++describe("checkHeaderBasedDirectWrite", () => {+ it.each<{+ input: Parameters<typeof checkHeaderBasedDirectWrite>[0];+ expected: boolean;+ label: string;+ }>([+ // Python SDK version checks+ {+ input: { sdkName: "python", sdkVersion: "4.0.0" },+ expected: true,+ label: "python 4.0.0 (exact minimum)",+ },+ {+ input: { sdkName: "python", sdkVersion: "4.2.1" },+ expected: true,+ label: "python 4.2.1 (above minimum)",+ },+ {+ input: { sdkName: "python", sdkVersion: "3.9.0" },+ expected: false,+ label: "python 3.9.0 (below minimum)",+ },++ // JS SDK version checks+ {+ input: { sdkName: "javascript", sdkVersion: "5.0.0" },+ expected: true,+ label: "javascript 5.0.0 (exact minimum)",+ },+ {+ input: { sdkName: "javascript", sdkVersion: "5.1.3" },+ expected: true,+ label: "javascript 5.1.3 (above minimum)",+ },+ {+ input: { sdkName: "javascript", sdkVersion: "4.6.0" },+ expected: false,+ label: "javascript 4.6.0 (below minimum)",+ },++ // Pre-release versions (stripped before comparison)+ {+ input: { sdkName: "python", sdkVersion: "4.0.0-rc.1" },+ expected: true,+ label: "python 4.0.0-rc.1 (pre-release at minimum)",+ },+ {+ input: { sdkName: "javascript", sdkVersion: "5.0.0-beta.1" },+ expected: true,+ label: "javascript 5.0.0-beta.1 (pre-release at minimum)",+ },+ {+ input: { sdkName: "python", sdkVersion: "4.1.0-rc.1" },+ expected: true,+ label: "python 4.1.0-rc.1 (pre-release above minimum)",+ },+ {+ input: { sdkName: "python", sdkVersion: "3.9.0-rc.1" },+ expected: false,+ label: "python 3.9.0-rc.1 (pre-release below minimum)",+ },++ // Unknown / missing SDK name+ {+ input: { sdkName: "ruby", sdkVersion: "1.0.0" },+ expected: false,+ label: "unknown SDK name",+ },+ {+ input: { sdkName: "python" },+ expected: false,+ label: "sdkName without sdkVersion",+ },+ {+ input: { sdkVersion: "4.0.0" },+ expected: false,+ label: "sdkVersion without sdkName",+ },++ // Malformed versions+ {+ input: { sdkName: "python", sdkVersion: "not-a-version" },+ expected: false,+ label: "non-semver sdkVersion",+ },+ {+ input: { sdkName: "python", sdkVersion: "" },+ expected: false,+ label: "empty sdkVersion",+ },++ // ingestionVersion+ {+ input: { ingestionVersion: "4" },+ expected: true,+ label: "ingestionVersion '4'",+ },+ {+ input: {+ ingestionVersion: "4",+ sdkName: undefined,+ sdkVersion: undefined,+ },+ expected: true,+ label: "ingestionVersion '4' without SDK headers",+ },+ {+ input: { ingestionVersion: "3" },+ expected: false,+ label: "ingestionVersion '3' (below)",+ },+ {+ input: { ingestionVersion: "1" },+ expected: false,+ label: "ingestionVersion '1' (below)",+ },+ {+ input: { sdkName: "python", sdkVersion: "3.0.0", ingestionVersion: "4" },+ expected: true,+ label: "ingestionVersion '4' overrides old SDK version",+ },++ // No headers+ { input: {}, expected: false, label: "empty input" },+ {+ input: {+ sdkName: undefined,+ sdkVersion: undefined,+ ingestionVersion: undefined,+ },+ expected: false,+ label: "all undefined",+ },+ ])("$label → $expected", ({ input, expected }) => {+ expect(checkHeaderBasedDirectWrite(input)).toBe(expected);+ });+});++describe("checkSdkVersionRequirements (legacy fallback)", () => {+ it.each<{+ sdkInfo: SdkInfo;+ isExperiment: boolean;+ expected: boolean;+ label: string;+ }>([+ {+ sdkInfo: {+ scopeName: "openlit",+ scopeVersion: "3.9.0",+ telemetrySdkLanguage: "python",+ },+ isExperiment: true,+ expected: false,+ label: "non-Langfuse scope name",+ },+ {+ sdkInfo: {+ scopeName: "langfuse-sdk",+ scopeVersion: "3.9.0",+ telemetrySdkLanguage: "python",+ },+ isExperiment: false,+ expected: false,+ label: "experiment batch false",+ },+ {+ sdkInfo: {+ scopeName: "langfuse-sdk",+ scopeVersion: "3.9.0",+ telemetrySdkLanguage: "python",+ },+ isExperiment: true,+ expected: true,+ label: "python 3.9.0 (exact minimum)",+ },+ {+ sdkInfo: {+ scopeName: "langfuse-sdk",+ scopeVersion: "4.4.0",+ telemetrySdkLanguage: "js",+ },+ isExperiment: true,+ expected: true,+ label: "js 4.4.0 (exact minimum)",+ },+ ])("$label → $expected", ({ sdkInfo, isExperiment, expected }) => {+ expect(checkSdkVersionRequirements(sdkInfo, isExperiment)).toBe(expected);+ });+});++describe("getSdkInfoFromResourceSpans (legacy fallback)", () => {+ it.each<{+ input: Parameters<typeof getSdkInfoFromResourceSpans>[0];+ expected: ReturnType<typeof getSdkInfoFromResourceSpans>;+ label: string;+ }>([+ {+ input: {+ resource: {+ attributes: [+ { key: "telemetry.sdk.language", value: { stringValue: "python" } },+ ],+ },+ scopeSpans: [+ { scope: { name: "langfuse-sdk", version: "3.14.1" }, spans: [] },+ ],+ },+ expected: {+ scopeName: "langfuse-sdk",+ scopeVersion: "3.14.1",+ telemetrySdkLanguage: "python",+ },+ label: "well-formed input",+ },+ {+ input: {},+ expected: {+ scopeName: null,+ scopeVersion: null,+ telemetrySdkLanguage: null,+ },+ label: "empty input",+ },+ ])("$label", ({ input, expected }) => {+ expect(getSdkInfoFromResourceSpans(input)).toEqual(expected);+ });+});diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex f7778ad914..1f6c4f36db 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -37,10 +37,59 @@ import {createObservationEvalSchedulerDeps,} from "../features/evaluation/observationEval";+/**+ * Check if HTTP headers from the SDK request indicate the batch is eligible+ * for direct event writes.+ *+ * Requirements:+ * - x-langfuse-sdk-name "python" with x-langfuse-sdk-version >= 4.0.0+ * - x-langfuse-sdk-name "javascript" with x-langfuse-sdk-version >= 5.0.0+ * - x-langfuse-ingestion-version === "4" (custom OTel exporter opt-in)+ */+export function checkHeaderBasedDirectWrite(params: {+ sdkName?: string;+ sdkVersion?: string;+ ingestionVersion?: string;+}): boolean {+ const { sdkName, sdkVersion, ingestionVersion } = params;++ // Check x-langfuse-ingestion-version (>= 4 means direct write eligible).+ // Values > 4 are rejected at the API route, so anything reaching here is valid.+ const parsed = ingestionVersion ? parseInt(ingestionVersion, 10) : NaN;+ if (!isNaN(parsed) && parsed >= 4) {+ return true;+ }++ // Check Langfuse SDK name + version+ if (!sdkName || !sdkVersion) {+ return false;+ }++ try {+ // compareVersions returns null when current >= minimum (no update needed).+ // Strip pre-release/build metadata so that e.g. 4.0.0-rc.1 qualifies as 4.0.0.+ const baseVersion = sdkVersion.split(/[-+]/)[0];++ if (sdkName === "python") {+ return compareVersions(baseVersion, "v4.0.0") === null;+ }++ if (sdkName === "javascript") {+ return compareVersions(baseVersion, "v5.0.0") === null;+ }+ } catch {+ logger.warn(+ `Failed to parse SDK version from headers: ${sdkName}@${sdkVersion}`,+ );+ }++ return false;+}+/*** SDK information extracted from OTEL resourceSpans.*/-type SdkInfo = {+export type SdkInfo = {scopeName: string | null;scopeVersion: string | null;telemetrySdkLanguage: string | null;@@ -50,7 +99,9 @@ type SdkInfo = {* Extract SDK information from resourceSpans.* Gets scope name/version and telemetry SDK language from the OTEL structure.*/-function getSdkInfoFromResourceSpans(resourceSpans: ResourceSpan): SdkInfo {+export function getSdkInfoFromResourceSpans(+ resourceSpans: ResourceSpan,+): SdkInfo {try {// Get the first scopeSpan (all spans in a batch share the same scope)const firstScopeSpan = resourceSpans?.scopeSpans?.[0];@@ -78,7 +129,7 @@ function getSdkInfoFromResourceSpans(resourceSpans: ResourceSpan): SdkInfo {* - Python SDK: scope_version >= 3.9.0* - JS/JavaScript SDK: scope_version >= 4.4.0*/-function checkSdkVersionRequirements(+export function checkSdkVersionRequirements(sdkInfo: SdkInfo,isSdkExperimentBatch: boolean,): boolean {@@ -242,24 +293,50 @@ export const otelIngestionQueueProcessor: Processor = async (// Decide whether observations should be processed via new flow (directly to events table)// or via the dual write (staging table and batch job to events).- // Rules:- // 1. If the environment is `sdk-experiment`, JS SDK 4.4.0+ and python SDK 3.9.0+ will write directly to events.- // 2. All other observations will go through the dual write until we have SDKs in place that have old trace updates- // deprecated and new methods in place.- // 3. Non-Langfuse SDK spans will go through the dual write until a yet to be determined cutoff date.- // Check if any observation has environment='sdk-experiment'- const hasExperimentEnvironment = observations.some((o) => {- const body = o.body as { environment?: string };- return body.environment === "sdk-experiment";+ //+ // Priority 1: HTTP headers from the SDK request (batch-level decision).+ // - x-langfuse-sdk-name/version: Python >= 4.0.0 or JS >= 5.0.0+ // - x-langfuse-ingestion-version: "4" (custom OTel exporter opt-in)+ // When headers qualify, ALL spans in the batch (including third-party scoped) use direct write.+ //+ // Priority 2 (fallback): Per-span OTEL scope inspection (legacy).+ // - scope.name contains "langfuse", sdk-experiment environment, Python >= 3.9.0 or JS >= 4.4.0+ const headerBasedDirectWrite = checkHeaderBasedDirectWrite({+ sdkName: job.data.payload.sdkName,+ sdkVersion: job.data.payload.sdkVersion,+ ingestionVersion: job.data.payload.ingestionVersion,+ });++ let useDirectEventWrite = headerBasedDirectWrite;++ if (!useDirectEventWrite) {+ const hasExperimentEnvironment = observations.some((o) => {+ const body = o.body as { environment?: string };+ return body.environment === "sdk-experiment";+ });+ const sdkInfo =+ parsedSpans.length > 0+ ? getSdkInfoFromResourceSpans(parsedSpans[0])+ : {+ scopeName: null,+ scopeVersion: null,+ telemetrySdkLanguage: null,+ };+ useDirectEventWrite = checkSdkVersionRequirements(+ sdkInfo,+ hasExperimentEnvironment,+ );+ }++ const writePath = useDirectEventWrite+ ? headerBasedDirectWrite+ ? "direct_header"+ : "direct_scope"+ : "dual";+ span?.setAttribute("langfuse.ingestion.otel.write_path", writePath);+ recordIncrement("langfuse.ingestion.otel.write_path", 1, {+ path: writePath,});- const sdkInfo =- parsedSpans.length > 0- ? getSdkInfoFromResourceSpans(parsedSpans[0])- : { scopeName: null, scopeVersion: null, telemetrySdkLanguage: null };- const useDirectEventWrite = checkSdkVersionRequirements(- sdkInfo,- hasExperimentEnvironment,- );const shouldForwardToEventsTable =!useDirectEventWrite &&