🪢 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(ingestion): persist SDK attribution (#14593)
Max Deichmannb56c6b4aeb28
diff --git a/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.down.sql b/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.down.sqlnew file mode 100644index 0000000000..695a0383e5--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.down.sql@@ -0,0 +1,11 @@+ALTER TABLE scores ON CLUSTER default+ DROP COLUMN IF EXISTS ingestion_sdk_version+ SETTINGS alter_sync = 2;++ALTER TABLE scores ON CLUSTER default+ DROP COLUMN IF EXISTS ingestion_sdk_name+ SETTINGS alter_sync = 2;++ALTER TABLE scores ON CLUSTER default+ DROP COLUMN IF EXISTS ingestion_api_key+ SETTINGS alter_sync = 2;diff --git a/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.up.sql b/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.up.sqlnew file mode 100644index 0000000000..ae8e27730f--- /dev/null+++ b/packages/shared/clickhouse/migrations/clustered/0035_add_ingestion_attribution_columns.up.sql@@ -0,0 +1,11 @@+ALTER TABLE scores ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS alter_sync = 2;++ALTER TABLE scores ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS alter_sync = 2;++ALTER TABLE scores ON CLUSTER default+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS alter_sync = 2;diff --git a/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.down.sql b/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.down.sqlnew file mode 100644index 0000000000..162a83db91--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.down.sql@@ -0,0 +1,8 @@+ALTER TABLE scores+ DROP COLUMN IF EXISTS ingestion_sdk_version;++ALTER TABLE scores+ DROP COLUMN IF EXISTS ingestion_sdk_name;++ALTER TABLE scores+ DROP COLUMN IF EXISTS ingestion_api_key;diff --git a/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.up.sql b/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.up.sqlnew file mode 100644index 0000000000..f6b12e724b--- /dev/null+++ b/packages/shared/clickhouse/migrations/unclustered/0035_add_ingestion_attribution_columns.up.sql@@ -0,0 +1,8 @@+ALTER TABLE scores+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT '';++ALTER TABLE scores+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown';++ALTER TABLE scores+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown';diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex 55b07c11df..8ded993435 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -567,6 +567,118 @@ FROM events_coreWHERE toStartOfHour(start_time) <= toStartOfHour(subtractHours(now(), 1))GROUP BY project_id, hour;+-- Apply dev-table migrations for ingestion attribution.+ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;++ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE observations_batch_staging+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_full+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_api_key String DEFAULT ''+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_sdk_name LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++ALTER TABLE events_core+ ADD COLUMN IF NOT EXISTS ingestion_sdk_version LowCardinality(String) DEFAULT 'unknown'+ SETTINGS enable_full_text_index = 1;++-- Update events MV+ALTER TABLE events_core_mv MODIFY QUERY+SELECT+ project_id,+ trace_id,+ span_id,+ parent_span_id,+ start_time,+ end_time,+ name,+ type,+ environment,+ version,+ release,+ trace_name,+ user_id,+ session_id,+ tags,+ level,+ status_message,+ completion_start_time,+ is_app_root,+ bookmarked,+ public,+ prompt_id,+ prompt_name,+ prompt_version,+ model_id,+ provided_model_name,+ model_parameters,+ provided_usage_details,+ usage_details,+ provided_cost_details,+ cost_details,+ usage_pricing_tier_id,+ usage_pricing_tier_name,+ tool_definitions,+ tool_calls,+ tool_call_names,+ leftUTF8(input, 200) as input,+ leftUTF8(output, 200) as output,+ metadata_names,+ arrayMap(v -> leftUTF8(v, 200), metadata_values) as metadata_values,+ experiment_id,+ experiment_name,+ experiment_metadata_names,+ experiment_metadata_values,+ experiment_description,+ experiment_dataset_id,+ experiment_item_id,+ experiment_item_version,+ experiment_item_expected_output,+ experiment_item_metadata_names,+ experiment_item_metadata_values,+ experiment_item_root_span_id,+ source,+ service_name,+ service_version,+ scope_name,+ scope_version,+ telemetry_sdk_language,+ telemetry_sdk_name,+ telemetry_sdk_version,+ blob_storage_file_path,+ event_bytes,+ created_at,+ updated_at,+ event_ts,+ is_deleted,+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+FROM events_full+SETTINGS enable_full_text_index = 1;+EOFecho "Populating development tables with sample data..."@@ -577,7 +689,7 @@ clickhouse client \--user="${CLICKHOUSE_USER}" \--password="${CLICKHOUSE_PASSWORD}" \--database="${CLICKHOUSE_DB}" \- --multiquery <<EOF+ --multiquery <<'EOF'SET type_json_skip_duplicated_paths = 1;TRUNCATE events_core;TRUNCATE events_full;@@ -596,7 +708,8 @@ clickhouse client \experiment_item_metadata_names, experiment_item_metadata_values,experiment_item_root_span_id,source, blob_storage_file_path, event_bytes,- created_at, updated_at, event_ts, is_deleted)+ created_at, updated_at, event_ts, is_deleted,+ ingestion_api_key, ingestion_sdk_name, ingestion_sdk_version)SELECT o.project_id,o.trace_id,o.id AS span_id,@@ -656,7 +769,10 @@ clickhouse client \o.created_at,o.updated_at,o.event_ts,- o.is_deleted+ o.is_deleted,+ '' AS ingestion_api_key,+ 'unknown' AS ingestion_sdk_name,+ 'unknown' AS ingestion_sdk_versionFROM observations o FINALLEFT JOIN traces t ON o.project_id = t.project_id AND o.trace_id = t.idLEFT JOIN dataset_run_items_rmt dri ON o.project_id = dri.project_id AND o.trace_id = dri.trace_id@@ -678,7 +794,8 @@ clickhouse client \experiment_item_metadata_names, experiment_item_metadata_values,experiment_item_root_span_id,source, blob_storage_file_path, event_bytes,- created_at, updated_at, event_ts, is_deleted)+ created_at, updated_at, event_ts, is_deleted,+ ingestion_api_key, ingestion_sdk_name, ingestion_sdk_version)SELECT t.project_id,t.id,concat('t-', t.id) AS span_id,@@ -727,7 +844,10 @@ clickhouse client \t.created_at,t.updated_at,t.event_ts,- t.is_deleted+ t.is_deleted,+ '' AS ingestion_api_key,+ 'unknown' AS ingestion_sdk_name,+ 'unknown' AS ingestion_sdk_versionFROM traces t FINALLEFT JOIN dataset_run_items_rmt dri ON t.project_id = dri.project_id AND t.id = dri.trace_idWHERE (t.is_deleted = 0);diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.tsindex b3756432bd..0fa53d3873 100644--- a/packages/shared/scripts/seeder/utils/data-generators.ts+++ b/packages/shared/scripts/seeder/utils/data-generators.ts@@ -35,6 +35,7 @@ import {DatasetRunItemRecordInsertType,createDatasetRunItem,createDatasetRunScore,+ UNKNOWN_INGESTION_SDK_VALUE,} from "../../../src/server";/**@@ -94,6 +95,37 @@ export class DataGenerator {};}+ private buildSeedIngestionAttribution(+ projectId: string,+ client: "python-sdk" | "javascript-sdk" | "raw-api",+ ): Pick<+ ScoreRecordInsertType,+ "ingestion_api_key" | "ingestion_sdk_name" | "ingestion_sdk_version"+ > {+ const keySuffix = projectId.slice(-8);++ switch (client) {+ case "python-sdk":+ return {+ ingestion_api_key: `pk-lf-seed-${keySuffix}-python`,+ ingestion_sdk_name: "python",+ ingestion_sdk_version: "4.2.1",+ };+ case "javascript-sdk":+ return {+ ingestion_api_key: `pk-lf-seed-${keySuffix}-javascript`,+ ingestion_sdk_name: "javascript",+ ingestion_sdk_version: "5.1.3",+ };+ case "raw-api":+ return {+ ingestion_api_key: `pk-lf-seed-${keySuffix}-raw-api`,+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,+ };+ }+ }+/*** Creates dataset run items for dataset runs.* Use for: Dataset experiment scenarios.@@ -266,6 +298,7 @@ export class DataGenerator {data_type: "NUMERIC",source: "API",environment: "langfuse-prompt-experiment",+ ...this.buildSeedIngestionAttribution(projectId, "python-sdk"),});}@@ -294,6 +327,7 @@ export class DataGenerator {data_type: "NUMERIC",source: "API",environment: "langfuse-prompt-experiment",+ ...this.buildSeedIngestionAttribution(projectId, "javascript-sdk"),});}@@ -637,6 +671,10 @@ export class DataGenerator {source: "API",comment: "Generated score\ntest",environment: trace.environment,+ ...this.buildSeedIngestionAttribution(+ trace.project_id,+ this.randomElement(["python-sdk", "javascript-sdk", "raw-api"]),+ ),});scores.push(score);@@ -1250,6 +1288,7 @@ export class DataGenerator {string_value: null,long_string_value: "",queue_id: null,+ ...this.buildSeedIngestionAttribution(projectId, "javascript-sdk"),created_at: baseTs,updated_at: baseTs,timestamp: baseTs,@@ -1277,6 +1316,7 @@ export class DataGenerator {data_type: "BOOLEAN",string_value: safeVal === 1 ? "True" : "False",queue_id: null,+ ...this.buildSeedIngestionAttribution(projectId, "python-sdk"),created_at: baseTs + 10,updated_at: baseTs + 10,timestamp: baseTs + 10,@@ -1306,6 +1346,7 @@ export class DataGenerator {data_type: "BOOLEAN",string_value: "True",queue_id: null,+ ...this.buildSeedIngestionAttribution(projectId, "raw-api"),created_at: baseTs + 20,updated_at: baseTs + 20,timestamp: baseTs + 20,@@ -1354,6 +1395,7 @@ export class DataGenerator {source: "EVAL",comment: "Evaluation trace score",environment: trace.environment,+ ...this.buildSeedIngestionAttribution(projectId, "python-sdk"),});scores.push(score);diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex eb248bb732..db385a1282 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -71,6 +71,7 @@ export * from "./repositories/definitions";export * from "../utils/IORepresentation/chatML/types";export * from "../server/ingestion/types";export * from "../server/ingestion/modelMatch";+export * from "./ingestion/ingestionAttribution";export * from "./ingestion/processEventBatch";export * from "../server/ingestion/validateAndInflateScore";export * from "./ingestion/extractToolsBackend";diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.test.ts b/packages/shared/src/server/ingestion/ingestionAttribution.test.tsnew file mode 100644index 0000000000..f2c2aaa73f--- /dev/null+++ b/packages/shared/src/server/ingestion/ingestionAttribution.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from "vitest";++import type { AuthHeaderValidVerificationResult } from "../auth/types";+import {+ createIngestionAttribution,+ createUnknownSdkIngestionAttribution,+ UNKNOWN_INGESTION_SDK_VALUE,+} from "./ingestionAttribution";++const authCheck = {+ validKey: true,+ scope: {+ projectId: "project-id",+ accessLevel: "project",+ publicKey: "pk-lf-public",+ },+} as AuthHeaderValidVerificationResult;++describe("ingestion attribution", () => {+ it("reads SDK attribution from Langfuse request headers", () => {+ expect(+ createIngestionAttribution({+ headers: {+ "x-langfuse-sdk-name": "python",+ "x-langfuse-sdk-version": "3.4.0",+ },+ authCheck,+ }),+ ).toEqual({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: "python",+ ingestionSdkVersion: "3.4.0",+ });+ });++ it("reads SDK attribution from underscore header variants", () => {+ expect(+ createIngestionAttribution({+ headers: {+ x_langfuse_sdk_name: "langfuse-js",+ x_langfuse_sdk_version: "4.2.0",+ },+ authCheck,+ }),+ ).toEqual({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: "langfuse-js",+ ingestionSdkVersion: "4.2.0",+ });+ });++ it("uses the unknown SDK marker when requests do not include SDK headers", () => {+ expect(createIngestionAttribution({ headers: {}, authCheck })).toEqual({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,+ });+ });++ it("creates explicit unknown SDK attribution for non-SDK internal producers", () => {+ expect(createUnknownSdkIngestionAttribution({ authCheck })).toEqual({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,+ });+ });+});diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.ts b/packages/shared/src/server/ingestion/ingestionAttribution.tsnew file mode 100644index 0000000000..073feaa0c6--- /dev/null+++ b/packages/shared/src/server/ingestion/ingestionAttribution.ts@@ -0,0 +1,59 @@+import type { AuthHeaderValidVerificationResult } from "../auth/types";++type HeaderValue = string | string[] | undefined;+export type IngestionHeaderMap = Record<string, HeaderValue>;++export type IngestionAttribution = {+ ingestionApiKey: string;+ ingestionSdkName: string;+ ingestionSdkVersion: string;+};++export const UNKNOWN_INGESTION_SDK_VALUE = "unknown";++const getHeaderValue = (+ headers: IngestionHeaderMap | undefined,+ name: string,+): string => {+ if (!headers) return "";++ const directValue = headers[name];+ if (typeof directValue === "string") return directValue;++ const underscoreValue = headers[name.replaceAll("-", "_")];+ if (typeof underscoreValue === "string") return underscoreValue;++ return "";+};++const normalizeSdkValue = (value: string | undefined): string =>+ value || UNKNOWN_INGESTION_SDK_VALUE;++export const getLangfuseHeaderValue = getHeaderValue;++export const createIngestionAttribution = (params: {+ headers?: IngestionHeaderMap;+ authCheck: AuthHeaderValidVerificationResult;+}): IngestionAttribution => {+ const { headers, authCheck } = params;++ return {+ ingestionApiKey: authCheck.scope.publicKey,+ ingestionSdkName: normalizeSdkValue(+ getHeaderValue(headers, "x-langfuse-sdk-name"),+ ),+ ingestionSdkVersion: normalizeSdkValue(+ getHeaderValue(headers, "x-langfuse-sdk-version"),+ ),+ };+};++export const createUnknownSdkIngestionAttribution = (params: {+ authCheck: {+ scope: { publicKey?: string | null; projectId?: string | null };+ };+}): IngestionAttribution => ({+ ingestionApiKey: params.authCheck.scope.publicKey ?? "",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,+});diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex 04bb434279..882beefdd0 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -27,6 +27,7 @@ import {createIngestionEventSchema,IngestionEventType,} from "./types";+import type { IngestionAttribution } from "./ingestionAttribution";import {StorageService,StorageServiceFactory,@@ -96,12 +97,14 @@ const getDelay = (delay: number | null, source: "api" | "otel") => {* @property source - Source of the events for metrics tracking (e.g., "otel", "api").* @property isLangfuseInternal - Whether the events are being ingested by Langfuse internally (e.g. traces created for prompt experiments).* @property forwardToEventsTable - Whether to forward events to the staging events table for batch propagation. If undefined, falls back to environment flags.+ * @property attribution - Request-level ingestion attribution to persist on generated records.*/type ProcessEventBatchOptions = {delay?: number | null;source?: "api" | "otel";isLangfuseInternal?: boolean;forwardToEventsTable?: boolean;+ attribution: IngestionAttribution;};/**@@ -113,7 +116,7 @@ type ProcessEventBatchOptions = {export const processEventBatch = async (input: unknown[],authCheck: AuthHeaderValidVerificationResultIngestion,- options: ProcessEventBatchOptions = {},+ options: ProcessEventBatchOptions,): Promise<{successes: { id: string; status: number }[];errors: {@@ -131,6 +134,7 @@ export const processEventBatch = async (source = "api",isLangfuseInternal = false,forwardToEventsTable,+ attribution,} = options;// add context of api call to the span@@ -387,6 +391,9 @@ export const processEventBatch = async (skipS3List: shouldSkipS3List,forwardToEventsTable,bucketPrefix: eventData.bucketPrefix,+ ingestionApiKey: attribution.ingestionApiKey,+ ingestionSdkName: attribution.ingestionSdkName,+ ingestionSdkVersion: attribution.ingestionSdkVersion,},authCheck: authCheck as {validKey: true;diff --git a/packages/shared/src/server/llm/getInternalTracingHandler.ts b/packages/shared/src/server/llm/getInternalTracingHandler.tsindex e9f03c3b28..6454623f48 100644--- a/packages/shared/src/server/llm/getInternalTracingHandler.ts+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts@@ -2,6 +2,7 @@ import CallbackHandler from "langfuse-langchain";import { ProcessedTraceEvent, TraceSinkParams } from "./types";import { buildInternalTraceEventInputs } from "./internalTraceEvents";import { processEventBatch } from "../ingestion/processEventBatch";+import { createUnknownSdkIngestionAttribution } from "../ingestion/ingestionAttribution";import { logger } from "../logger";import { traceException } from "../instrumentation";@@ -97,18 +98,23 @@ export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {// Legacy write to traces/observations tablestry {+ const auth = {+ validKey: true as const,+ scope: {+ projectId: traceSinkParams.targetProjectId, // Important: this controls into what project traces are ingested.+ accessLevel: "project",+ } as any,+ };+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,- },+ auth,{isLangfuseInternal: true,forwardToEventsTable: eventsWriter ? false : undefined, // Do not dual write when we already direct event write+ attribution: createUnknownSdkIngestionAttribution({+ authCheck: auth,+ }),},);} catch (processingError) {diff --git a/packages/shared/src/server/llm/internalTraceEvents.ts b/packages/shared/src/server/llm/internalTraceEvents.tsindex 567f2d33a5..df7895bba9 100644--- a/packages/shared/src/server/llm/internalTraceEvents.ts+++ b/packages/shared/src/server/llm/internalTraceEvents.ts@@ -75,6 +75,9 @@ export type InternalTraceEventInput = {output?: string;metadata: Record<string, unknown>;source: string;+ ingestionApiKey?: string;+ ingestionSdkName?: string;+ ingestionSdkVersion?: string;serviceName?: string;serviceVersion?: string;scopeName?: string;diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 8837846402..4b9ac69be1 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -36,11 +36,11 @@ interface TraceState {export interface OtelIngestionProcessorConfig {projectId: string;- publicKey?: string;+ publicKey: string;orgId?: string;propagatedHeaders?: Record<string, string>;- sdkName?: string;- sdkVersion?: string;+ sdkName: string;+ sdkVersion: string;ingestionVersion?: string;}@@ -150,11 +150,11 @@ export class OtelIngestionProcessor {traceUpdated: 0,};private readonly projectId: string;- private readonly publicKey?: string;+ private readonly publicKey: string;private readonly orgId?: string;private readonly propagatedHeaders?: Record<string, string>;- private readonly sdkName?: string;- private readonly sdkVersion?: string;+ private readonly sdkName: string;+ private readonly sdkVersion: string;private readonly ingestionVersion?: string;constructor(config: OtelIngestionProcessorConfig) {@@ -163,7 +163,11 @@ export class OtelIngestionProcessor {this.orgId = config.orgId;this.propagatedHeaders = config.propagatedHeaders;this.sdkName = config.sdkName;+ // Langfuse SDK version from x-langfuse-sdk-version. This is persisted as+ // ingestionSdkVersion attribution on emitted events.this.sdkVersion = config.sdkVersion;+ // Ingestion protocol version from x-langfuse-ingestion-version. This is+ // only used as a write-path hint, not as SDK attribution.this.ingestionVersion = config.ingestionVersion;}@@ -479,6 +483,9 @@ export class OtelIngestionProcessor {// Instrumentation metadatasource: "otel",+ ingestionApiKey: this.publicKey,+ ingestionSdkName: this.sdkName,+ ingestionSdkVersion: this.sdkVersion,serviceName,serviceVersion,scopeName,diff --git a/packages/shared/src/server/queues.test.ts b/packages/shared/src/server/queues.test.tsindex 906aa4af4e..9cbeffff16 100644--- a/packages/shared/src/server/queues.test.ts+++ b/packages/shared/src/server/queues.test.ts@@ -1,6 +1,10 @@import { describe, it, expect } from "vitest";-import { WebhookOutboundEnvelopeSchema } from "./queues";+import {+ IngestionEvent,+ OtelIngestionEvent,+ WebhookOutboundEnvelopeSchema,+} from "./queues";const validMonitorEnvelope = {id: "exe_01",@@ -45,3 +49,40 @@ describe("WebhookOutboundEnvelopeSchema (discriminated union)", () => {).toBe(false);});});++describe("ingestion queue payload compatibility", () => {+ it("accepts ingestion jobs created before attribution fields existed", () => {+ const parsed = IngestionEvent.safeParse({+ data: {+ type: "trace-create",+ eventBodyId: "trace-01",+ fileKey: "event-01",+ },+ authCheck: {+ validKey: true,+ scope: {+ projectId: "project-01",+ },+ },+ });++ expect(parsed.success).toBe(true);+ });++ it("accepts otel jobs with omitted attribution fields", () => {+ const parsed = OtelIngestionEvent.safeParse({+ data: {+ fileKey: "otel-01",+ },+ authCheck: {+ validKey: true,+ scope: {+ projectId: "project-01",+ accessLevel: "project",+ },+ },+ });++ expect(parsed.success).toBe(true);+ });+});diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 794702e3cf..c04ff94c64 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -26,6 +26,11 @@ export const IngestionEvent = z.object({fileKey: z.string().optional(),skipS3List: z.boolean().optional(),forwardToEventsTable: z.boolean().optional(),+ // Optional for rolling deploy compatibility with in-flight jobs created+ // before ingestion attribution was added to the queue payload.+ ingestionApiKey: z.string().optional(),+ ingestionSdkName: z.string().optional(),+ ingestionSdkVersion: z.string().optional(),// Absolute S3 key prefix the producer used (ends with "/"). Set so the// consumer never reconstructs the path and therefore can't drift from// the producer when env values differ across containers. Optional for@@ -44,6 +49,8 @@ export const IngestionEvent = z.object({export const OtelIngestionEvent = z.object({data: z.object({fileKey: z.string(),+ // Optional for compatibility with queued/replayed payloads that do not+ // carry API-key attribution.publicKey: z.string().optional(),}),authCheck: z.object({@@ -55,6 +62,8 @@ export const OtelIngestionEvent = z.object({}),}),propagatedHeaders: z.record(z.string(), z.string()).optional(),+ // Optional for rolling deploy compatibility with in-flight jobs created+ // before SDK attribution was added to the queue payload.sdkName: z.string().optional(),sdkVersion: z.string().optional(),ingestionVersion: z.string().optional(),diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex b7b5f8fea9..9ee242a625 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -1,4 +1,6 @@import z from "zod";+import type { IngestionAttribution } from "../ingestion/ingestionAttribution";+import { UNKNOWN_INGESTION_SDK_VALUE } from "../ingestion/ingestionAttribution";import { DEFAULT_TRACE_ENVIRONMENT } from "../ingestion/types";export const clickhouseStringDateSchema = z@@ -96,6 +98,9 @@ export type ObservationRecordInsertType = z.infer<export const observationBatchStagingRecordInsertSchema =observationRecordInsertSchema.extend({+ ingestion_api_key: z.string(),+ ingestion_sdk_name: z.string(),+ ingestion_sdk_version: z.string(),s3_first_seen_timestamp: z.number(),});export type ObservationBatchStagingRecordInsertType = z.infer<@@ -227,6 +232,9 @@ export const scoreRecordBaseSchema = z.object({long_string_value: z.string(),queue_id: z.string().nullish(),execution_trace_id: z.string().nullish(),+ ingestion_api_key: z.string(),+ ingestion_sdk_name: z.string(),+ ingestion_sdk_version: z.string(),is_deleted: z.number(),});@@ -383,6 +391,7 @@ export const convertScoreReadToInsert = (export const convertTraceToStagingObservation = (traceRecord: TraceRecordInsertType,s3FirstSeenTimestamp: number,+ attribution: IngestionAttribution,): ObservationBatchStagingRecordInsertType => {return {// Identity - trace acts as its own span. Modify traceId to avoid cases where users set spanId = traceId.@@ -431,6 +440,11 @@ export const convertTraceToStagingObservation = (tool_calls: undefined,tool_call_names: undefined,+ // Ingestion attribution+ ingestion_api_key: attribution.ingestionApiKey,+ ingestion_sdk_name: attribution.ingestionSdkName,+ ingestion_sdk_version: attribution.ingestionSdkVersion,+// System fieldscreated_at: traceRecord.created_at,updated_at: traceRecord.updated_at,@@ -624,6 +638,9 @@ export const convertPostgresScoreToInsert = (long_string_value: "",queue_id: score.queue_id,execution_trace_id: null, // Postgres scores do not have eval execution traces+ ingestion_api_key: "",+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,created_at: score.created_at?.getTime(),updated_at: score.updated_at?.getTime(),event_ts: score.timestamp?.getTime(),@@ -709,6 +726,9 @@ export const eventRecordBaseSchema = z.object({// Source metadata (Instrumentation)source: z.string(),+ ingestion_api_key: z.string(),+ ingestion_sdk_name: z.string(),+ ingestion_sdk_version: z.string(),service_name: z.string().nullish(),service_version: z.string().nullish(),scope_name: z.string().nullish(),diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex c8d07e9384..a68b7f1712 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -1039,6 +1039,9 @@ export async function getScoresUiTable<config_id: string | null;queue_id: string | null;execution_trace_id: string | null;+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;is_deleted: number;event_ts: string;created_at: string;@@ -1128,6 +1131,9 @@ const getScoresUiGeneric = async <T>(props: {s.config_id,s.queue_id,s.execution_trace_id,+ s.ingestion_api_key,+ s.ingestion_sdk_name,+ s.ingestion_sdk_version,s.is_deleted,s.event_ts,t.user_id,@@ -1345,6 +1351,9 @@ const getScoresUiGenericFromEvents = async <T>(props: {s.config_id,s.queue_id,s.execution_trace_id,+ s.ingestion_api_key,+ s.ingestion_sdk_name,+ s.ingestion_sdk_version,s.is_deleted,s.event_ts${includeHasMetadataFlag ? ",length(mapKeys(s.metadata)) > 0 AS has_metadata" : ""}@@ -1444,6 +1453,9 @@ export async function getScoresUiTableFromEvents(props: {config_id: string | null;queue_id: string | null;execution_trace_id: string | null;+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;is_deleted: number;event_ts: string;created_at: string;diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex 421f3d20d9..6410fae6a0 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -6,6 +6,7 @@ import {DatasetRunItemRecordInsertType,EventRecordInsertType,} from "../repositories/definitions";+import { UNKNOWN_INGESTION_SDK_VALUE } from "../ingestion/ingestionAttribution";export const createTrace = (trace: Partial<TraceRecordInsertType>,@@ -126,6 +127,9 @@ export const createTraceScore = (created_at: Date.now(),updated_at: Date.now(),event_ts: Date.now(),+ ingestion_api_key: "",+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,is_deleted: 0,...score,session_id: null,@@ -152,6 +156,9 @@ export const createSessionScore = (created_at: Date.now(),updated_at: Date.now(),event_ts: Date.now(),+ ingestion_api_key: "",+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,is_deleted: 0,...score,observation_id: null,@@ -179,6 +186,9 @@ export const createDatasetRunScore = (created_at: Date.now(),updated_at: Date.now(),event_ts: Date.now(),+ ingestion_api_key: "",+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,is_deleted: 0,...score,observation_id: null,@@ -289,6 +299,9 @@ export const createEvent = (telemetry_sdk_language: null,telemetry_sdk_name: null,telemetry_sdk_version: null,+ ingestion_api_key: "pk-lf-1234567890",+ ingestion_sdk_name: "langfuse-js",+ ingestion_sdk_version: "5.0.1",// Generic propsblob_storage_file_path: "",diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 6694908c84..bb7d165fd5 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -1,8 +1,21 @@import {OtelIngestionProcessor,createIngestionEventSchema,+ type OtelIngestionProcessorConfig,} from "@langfuse/shared/src/server";+function createTestOtelProcessor(+ config: Partial<OtelIngestionProcessorConfig> = {},+) {+ return new OtelIngestionProcessor({+ projectId: "test-project",+ publicKey: "",+ sdkName: "",+ sdkVersion: "",+ ...config,+ });+}+// Test helper function to maintain backward compatibility with existing tests// This mimics the old convertOtelSpanToIngestionEvent function signatureasync function convertOtelSpanToIngestionEvent(@@ -10,9 +23,8 @@ async function convertOtelSpanToIngestionEvent(seenTraces: Set<string>,publicKey?: string,) {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- publicKey,+ const processor = createTestOtelProcessor({+ publicKey: publicKey ?? "",});// For tests, we bypass Redis initialization and directly set the seen traces@@ -1244,9 +1256,7 @@ describe("OTel Resource Span Mapping", () => {],};- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);@@ -4470,9 +4480,7 @@ describe("OTel Resource Span Mapping", () => {observation?.body.metadata?.attributes?.["gen_ai.tool.definitions"],).toBeUndefined();- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([span]);expect(eventInputs).toHaveLength(1);@@ -4574,9 +4582,7 @@ describe("OTel Resource Span Mapping", () => {tools,});- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);@@ -4898,9 +4904,7 @@ describe("OTel Resource Span Mapping", () => {describe("Span Counting", () => {it("should count spans correctly across multiple resource spans", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const resourceSpans = [{@@ -4922,27 +4926,21 @@ describe("OTel Resource Span Mapping", () => {});it("should handle empty resource spans", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const count = (processor as any).getTotalSpanCount([]);expect(count).toBe(0);});it("should handle null/undefined resource spans", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();expect((processor as any).getTotalSpanCount(null)).toBe(0);expect((processor as any).getTotalSpanCount(undefined)).toBe(0);});it("should handle malformed resource spans", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const resourceSpans = [{ scopeSpans: null },@@ -4963,9 +4961,7 @@ describe("OTel Resource Span Mapping", () => {});it("should return 0 for non-array input", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();expect((processor as any).getTotalSpanCount("not-an-array")).toBe(0);expect((processor as any).getTotalSpanCount({})).toBe(0);@@ -4973,9 +4969,7 @@ describe("OTel Resource Span Mapping", () => {});it("should handle deeply nested null/undefined structures", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const resourceSpans = [null,@@ -4994,9 +4988,7 @@ describe("OTel Resource Span Mapping", () => {});it("should return -1 and not throw on unexpected errors", () => {- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();// Create a malicious object that throws when accessedconst maliciousResourceSpan = {@@ -5117,9 +5109,7 @@ describe("OTel Resource Span Mapping", () => {],};- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);expect(eventInputs[0].startTimeISO).toBeDefined();@@ -5176,9 +5166,7 @@ describe("OTel Resource Span Mapping", () => {],};- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);expect(eventInputs[0].startTimeISO).toBe(expectedISO);@@ -5285,9 +5273,7 @@ describe("OTel Resource Span Mapping", () => {],};- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);expect(eventInputs[0].name).toBe("chat:generateText");diff --git a/web/src/__tests__/server/ingestion-api.servertest.ts b/web/src/__tests__/server/ingestion-api.servertest.tsindex 696fa28958..ced5005db0 100644--- a/web/src/__tests__/server/ingestion-api.servertest.ts+++ b/web/src/__tests__/server/ingestion-api.servertest.ts@@ -2,6 +2,7 @@ import { randomUUID } from "crypto";import { makeAPICall } from "@/src/__tests__/test-utils";import waitForExpect from "wait-for-expect";import {+ clickhouseClient,getBlobStorageByProjectAndEntityId,getObservationById,getScoreById,@@ -12,15 +13,47 @@ import { v4 } from "uuid";let projectId: string;let auth: string;+let publicKey: string;++const postIngestion = (body: unknown, customHeaders?: Record<string, string>) =>+ makeAPICall("POST", "/api/public/ingestion", body, auth, customHeaders);++type IngestionAttributionRow = {+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+};++const getIngestionAttribution = async (table: "scores", id: string) => {+ const result = await clickhouseClient().query({+ query: `+ SELECT+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+ FROM ${table}+ WHERE project_id = {projectId: String}+ AND id = {id: String}+ ORDER BY event_ts DESC+ LIMIT 1+ `,+ query_params: {+ projectId,+ id,+ },+ format: "JSONEachRow",+ });-const postIngestion = (body: unknown) =>- makeAPICall("POST", "/api/public/ingestion", body, auth);+ const rows = await result.json<IngestionAttributionRow>();+ return rows[0];+};describe("/api/public/ingestion API Endpoint", () => {beforeEach(async () => {const fixture = await createOrgProjectAndApiKey();projectId = fixture.projectId;auth = fixture.auth;+ publicKey = fixture.publicKey;});it.each([[@@ -458,6 +491,71 @@ describe("/api/public/ingestion API Endpoint", () => {},);+ it("should persist ingestion attribution for scores", async () => {+ const timestamp = new Date().toISOString();+ const traceId = randomUUID();+ const observationId = randomUUID();+ const scoreId = randomUUID();++ const response = await postIngestion(+ {+ batch: [+ {+ id: randomUUID(),+ type: "generation-create",+ timestamp,+ body: {+ id: observationId,+ traceId,+ startTime: timestamp,+ model: "gpt-4",+ environment: "default",+ },+ },+ {+ id: randomUUID(),+ type: "score-create",+ timestamp,+ body: {+ id: scoreId,+ name: "score-name",+ traceId,+ observationId,+ value: 100.5,+ environment: "default",+ },+ },+ ],+ },+ {+ "x-langfuse-sdk-name": "python",+ "x-langfuse-sdk-version": "3.4.0",+ },+ );++ expect(response.status).toBe(207);++ await waitForExpect(async () => {+ const observation = await getObservationById({+ id: observationId,+ projectId,+ });+ expect(observation).toBeDefined();++ const score = await getScoreById({+ projectId,+ scoreId,+ });+ expect(score).toBeDefined();++ expect(await getIngestionAttribution("scores", scoreId)).toEqual({+ ingestion_api_key: publicKey,+ ingestion_sdk_name: "python",+ ingestion_sdk_version: "3.4.0",+ });+ }, 15_000);+ }, 20_000);+it.each(["&","$",diff --git a/web/src/__tests__/server/otel-api.servertest.ts b/web/src/__tests__/server/otel-api.servertest.tsindex 0194f9ee6e..258f30c38b 100644--- a/web/src/__tests__/server/otel-api.servertest.ts+++ b/web/src/__tests__/server/otel-api.servertest.ts@@ -1,13 +1,51 @@import { makeAPICall } from "@/src/__tests__/test-utils";import waitForExpect from "wait-for-expect";import {+ clickhouseClient,getObservationById,getObservationByIdFromEventsTable,getTraceById,} from "@langfuse/shared/src/server";import { randomBytes } from "crypto";+import { env } from "@/src/env.mjs";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+const eventsTableAvailable =+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+const maybeEventsTable = eventsTableAvailable ? it : it.skip;++type IngestionAttributionRow = {+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+};++const getEventsAttribution = async (+ table: "events_full" | "events_core",+ spanId: string,+) => {+ const result = await clickhouseClient().query({+ query: `+ SELECT+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+ FROM ${table}+ WHERE project_id = {projectId: String}+ AND span_id = {spanId: String}+ ORDER BY event_ts DESC+ LIMIT 1+ `,+ query_params: {+ projectId,+ spanId,+ },+ format: "JSONEachRow",+ });++ const rows = await result.json<IngestionAttributionRow>();+ return rows[0];+};describe("/api/public/otel/v1/traces API Endpoint", () => {it("should process a json payload correctly", async () => {@@ -330,83 +368,121 @@ 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);+ maybeEventsTable(+ "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: [+ const payload = {+ resourceSpans: [+ {+ resource: {+ attributes: [],+ },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "4.0.0",+ attributes: [+ {+ key: "public_key",+ value: { stringValue: "pk-lf-1234567890" },+ },+ ],+ },+ spans: [{- key: "public_key",- value: { stringValue: "pk-lf-1234567890" },+ traceId,+ spanId,+ name: "underscore-header-span",+ kind: 1,+ startTimeUnixNano: {+ low: 466848096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467248096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [],+ status: {},},],},- 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 observation = await getObservationByIdFromEventsTable({+ projectId,+ id: spanId.toString("hex"),+ });+ expect(observation).toBeDefined();+ expect(observation!.name).toBe("underscore-header-span");++ const expectedAttribution = {+ ingestion_api_key: "pk-lf-1234567890",+ ingestion_sdk_name: "python",+ ingestion_sdk_version: "4.0.0",+ };++ expect(+ await Promise.all([+ getEventsAttribution("events_full", spanId.toString("hex")),+ getEventsAttribution("events_core", spanId.toString("hex")),+ ]),+ ).toEqual([expectedAttribution, expectedAttribution]);+ }, 25_000);+ },+ 30_000,+ );++ it("should reject unsupported ingestion versions in underscore format", async () => {const response = await makeAPICall("POST","/api/public/otel/v1/traces",- payload,+ {+ resourceSpans: [+ {+ resource: {+ attributes: [],+ },+ scopeSpans: [],+ },+ ],+ },undefined,{- x_langfuse_sdk_name: "python",- x_langfuse_sdk_version: "4.0.0",- x_langfuse_ingestion_version: "4",+ x_langfuse_ingestion_version: "5",},);- 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);+ expect(response.status).toBe(400);+ expect(response.body).toEqual({+ error:+ 'Unsupported x-langfuse-ingestion-version: "5". Maximum supported: "4".',+ });+ });it("should transform deployment.environment to lowercase", async () => {const traceId = randomBytes(16);diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex cc4806bef7..9df6ef2cea 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -1,4 +1,5 @@import {+ clickhouseClient,createObservation,createTraceScore,createTrace,@@ -26,6 +27,39 @@ import { v4 } from "uuid";import { z } from "zod";import waitForExpect from "wait-for-expect";+type IngestionAttributionRow = {+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+};++const getScoreIngestionAttribution = async (+ projectId: string,+ scoreId: string,+) => {+ const result = await clickhouseClient().query({+ query: `+ SELECT+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+ FROM scores+ WHERE project_id = {projectId: String}+ AND id = {scoreId: String}+ ORDER BY event_ts DESC+ LIMIT 1+ `,+ query_params: {+ projectId,+ scoreId,+ },+ format: "JSONEachRow",+ });++ const rows = await result.json<IngestionAttributionRow>();+ return rows[0];+};+describe("/api/public/scores API Endpoint", () => {describe("GET /api/public/scores/:scoreId", () => {it("should GET a score", async () => {@@ -1507,6 +1541,40 @@ describe("/api/public/scores API Endpoint", () => {});describe("POST /api/public/scores source field", () => {+ it("persists SDK attribution for POST /api/public/scores", async () => {+ const { projectId, auth, publicKey } = await createOrgProjectAndApiKey();+ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const scoreId = v4();+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ { id: scoreId, traceId, name: "feedback", value: 1 },+ auth,+ {+ "x-langfuse-sdk-name": "python",+ "x-langfuse-sdk-version": "3.4.0",+ },+ );++ expect(response.status).toBe(200);++ await waitForExpect(async () => {+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ expect(score!.id).toBe(scoreId);++ expect(await getScoreIngestionAttribution(projectId, scoreId)).toEqual({+ ingestion_api_key: publicKey,+ ingestion_sdk_name: "python",+ ingestion_sdk_version: "3.4.0",+ });+ }, 15_000);+ }, 20_000);+it("defaults source to API when omitted", async () => {const { projectId, auth } = await createOrgProjectAndApiKey();const traceId = v4();diff --git a/web/src/features/datasets/server/publicDatasetService.ts b/web/src/features/datasets/server/publicDatasetService.tsindex 2d37e741b4..8617c35eb3 100644--- a/web/src/features/datasets/server/publicDatasetService.ts+++ b/web/src/features/datasets/server/publicDatasetService.ts@@ -45,6 +45,7 @@ import { upsertDataset } from "./actions/createDataset";import {addToDeleteDatasetQueue,createDatasetItemFilterState,+ createUnknownSdkIngestionAttribution,deleteDatasetItem,eventTypes,getDatasetItemById,@@ -811,6 +812,7 @@ export const createDatasetRunItemForApi = async ({// Note: currently we do not accept user defined ids for dataset run items.const ingestionResult = await processEventBatch([event], auth, {+ attribution: createUnknownSdkIngestionAttribution({ authCheck: auth }),isLangfuseInternal: true,});diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.tsindex 6015e0bdb9..45c83c0fbc 100644--- a/web/src/features/evals/server/codeEvalTestRun.ts+++ b/web/src/features/evals/server/codeEvalTestRun.ts@@ -1,6 +1,7 @@import { randomUUID } from "node:crypto";import {DEFAULT_TRACE_ENVIRONMENT,+ createUnknownSdkIngestionAttribution,eventTypes,createW3CTraceId,extractObservationVariables,@@ -427,17 +428,19 @@ async function writeTraceViaIngestion(trace: InternalTraceWriteInput) {},}));- const result = await processEventBatch(- [traceEvent, ...spanEvents],- {- validKey: true,- scope: {- projectId: rootEventInput.projectId,- accessLevel: "project",- },- } satisfies Parameters<typeof processEventBatch>[1],- { delay: 0, isLangfuseInternal: true },- );+ const auth = {+ validKey: true,+ scope: {+ projectId: rootEventInput.projectId,+ accessLevel: "project",+ },+ } satisfies Parameters<typeof processEventBatch>[1];++ const result = await processEventBatch([traceEvent, ...spanEvents], auth, {+ delay: 0,+ isLangfuseInternal: true,+ attribution: createUnknownSdkIngestionAttribution({ authCheck: auth }),+ });if (result.errors.length > 0) {throw new Error(result.errors[0]?.error ?? "Failed to write trace");diff --git a/web/src/features/mcp/features/observations/index.ts b/web/src/features/mcp/features/observations/index.tsindex c2f0ce001d..ef03f3ba1c 100644--- a/web/src/features/mcp/features/observations/index.ts+++ b/web/src/features/mcp/features/observations/index.ts@@ -24,7 +24,7 @@ import { env } from "@/src/env.mjs";export const observationsFeature = {name: "observations",description:- "Inspect generations, spans, events, and other observations in Langfuse",+ "Inspect traces, generations, spans, events, and other observations in Langfuse",tools: [{definition: listObservationsTool,diff --git a/web/src/features/mcp/features/scores/tools/createScore.ts b/web/src/features/mcp/features/scores/tools/createScore.tsindex a2b009dc99..40701c0c54 100644--- a/web/src/features/mcp/features/scores/tools/createScore.ts+++ b/web/src/features/mcp/features/scores/tools/createScore.ts@@ -7,6 +7,7 @@ import {UnauthorizedError,} from "@langfuse/shared";import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";+import { createUnknownSdkIngestionAttribution } from "@langfuse/shared/src/server";import { defineTool } from "../../../core/define-tool";import { buildScoreTargetUrl } from "@/src/utils/product-url";import { runMcpTool } from "../../../core/run-mcp-tool";@@ -89,20 +90,24 @@ export const [createScoreTool, handleCreateScore] = defineTool({},fn: async (span) => {const scoresApiService = new ScoresApiService("v2");+ const auth = {+ validKey: true as const,+ scope: {+ projectId: context.projectId,+ orgId: context.orgId,+ apiKeyId: context.apiKeyId,+ publicKey: context.publicKey,+ accessLevel: context.accessLevel,+ isIngestionSuspended: false,+ },+ };const { id: scoreId, result } = await scoresApiService.createScore({body: input,- auth: {- validKey: true,- scope: {- projectId: context.projectId,- orgId: context.orgId,- apiKeyId: context.apiKeyId,- publicKey: context.publicKey,- accessLevel: context.accessLevel,- isIngestionSuspended: false,- },- },+ auth,auditScope: context,+ attribution: createUnknownSdkIngestionAttribution({+ authCheck: auth,+ }),});span.setAttribute("mcp.score_id", scoreId);diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.tsindex 7acf83d639..7b2948377c 100644--- a/web/src/features/public-api/server/scores-api-service.ts+++ b/web/src/features/public-api/server/scores-api-service.ts@@ -22,6 +22,7 @@ import {QueueJobs,ScoreDeleteQueue,type AuthHeaderValidVerificationResultIngestion,+ type IngestionAttribution,StringFilter,StringOptionsFilter,type FilterList,@@ -224,11 +225,13 @@ export class ScoresApiService {auth,auditScope,scoreId = body.id ?? randomUUID(),+ attribution,}: {body: z.infer<typeof PostScoresBodyV1>;auth: AuthHeaderValidVerificationResultIngestion;auditScope?: { projectId: string; orgId: string; apiKeyId: string };scoreId?: string;+ attribution: IngestionAttribution;}) {const existingScore = auditScope? await _handleGetScoreById({@@ -252,6 +255,7 @@ export class ScoresApiService {},],auth,+ { attribution },);if (diff --git a/web/src/pages/api/admin/ingestion-replay.ts b/web/src/pages/api/admin/ingestion-replay.tsindex bdcef76c7d..e52ef6d8fb 100644--- a/web/src/pages/api/admin/ingestion-replay.ts+++ b/web/src/pages/api/admin/ingestion-replay.ts@@ -9,6 +9,7 @@ import {rawEventBucketPrefix,SecondaryIngestionQueue,OtelIngestionQueue,+ UNKNOWN_INGESTION_SDK_VALUE,} from "@langfuse/shared/src/server";import type { QueueName, TQueueJobTypes } from "@langfuse/shared/src/server";import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";@@ -147,11 +148,13 @@ export default async function handler(timestamp: new Date(),id: randomUUID(),payload: {- data: { fileKey: key },+ data: { fileKey: key, publicKey: "" },authCheck: {validKey: true,scope: { projectId: parsed.projectId, accessLevel: "project" },},+ sdkName: UNKNOWN_INGESTION_SDK_VALUE,+ sdkVersion: UNKNOWN_INGESTION_SDK_VALUE,},name: QueueJobs.OtelIngestionJob,});@@ -188,6 +191,9 @@ export default async function handler(eventBodyId,fileKey: eventId,bucketPrefix,+ ingestionApiKey: "",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,},authCheck: {validKey: true,diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.tsindex f947fd6b33..50be748710 100644--- a/web/src/pages/api/public/events.ts+++ b/web/src/pages/api/public/events.ts@@ -5,6 +5,7 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {+ createIngestionAttribution,eventTypes,logger,processEventBatch,@@ -19,7 +20,7 @@ export default withMiddlewares({// Writes an observation-create event that lands in the legacy observations// ClickHouse table; events_only deployments expect OTel ingestion.rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {const event = {id: v4(),type: eventTypes.OBSERVATION_CREATE,@@ -32,7 +33,12 @@ export default withMiddlewares({if (!event.body.id) {event.body.id = v4();}- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];resdiff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.tsindex 5052e52af3..0c6074a6a6 100644--- a/web/src/pages/api/public/generations.ts+++ b/web/src/pages/api/public/generations.ts@@ -7,6 +7,7 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {+ createIngestionAttribution,eventTypes,logger,processEventBatch,@@ -22,7 +23,7 @@ export default withMiddlewares({// Writes an observation-create event that lands in the legacy observations// ClickHouse table; events_only deployments expect OTel ingestion.rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {const { prompt, completion, ...rest } = body;const event = {id: v4(),@@ -38,7 +39,12 @@ export default withMiddlewares({if (!event.body.id) {event.body.id = v4();}- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];res@@ -59,7 +65,7 @@ export default withMiddlewares({responseSchema: PatchGenerationsV1Response,rateLimitResource: "legacy-ingestion",rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {const { generationId, prompt, completion, ...rest } = body;const event = {id: v4(),@@ -73,7 +79,12 @@ export default withMiddlewares({output: completion,},};- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];resdiff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 771d36a98a..8913e41bb1 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -9,6 +9,7 @@ import {contextWithLangfuseProps,eventTypes,markProjectIngestFailure,+ createIngestionAttribution,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";@@ -155,7 +156,12 @@ export default async function handler(env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only",);- const result = await processEventBatch(batchForProcessing, authCheck);+ const result = await processEventBatch(batchForProcessing, authCheck, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck,+ }),+ });if (rejectedErrors.length > 0) {result.errors = [...result.errors, ...rejectedErrors];}diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 25bcfd1f1d..2f17bd7881 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -5,6 +5,8 @@ import {markProjectIngestFailure,OtelIngestionProcessor,markProjectAsOtelUser,+ createIngestionAttribution,+ getLangfuseHeaderValue,} from "@langfuse/shared/src/server";import { z } from "zod";import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";@@ -12,18 +14,6 @@ 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,@@ -134,12 +124,11 @@ export default withMiddlewares({}// 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(+ const attribution = createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ });+ const ingestionVersion = getLangfuseHeaderValue(req.headers,"x-langfuse-ingestion-version",);@@ -178,8 +167,8 @@ export default withMiddlewares({Object.keys(propagatedHeaders).length > 0? propagatedHeaders: undefined,- sdkName,- sdkVersion,+ sdkName: attribution.ingestionSdkName,+ sdkVersion: attribution.ingestionSdkVersion,ingestionVersion,});diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex df4800e0fa..d326f5d8b8 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -7,7 +7,10 @@ import {PostScoresBodyV1,PostScoresResponseV1,} from "@langfuse/shared";-import { logger } from "@langfuse/shared/src/server";+import {+ createIngestionAttribution,+ logger,+} from "@langfuse/shared/src/server";import { ForbiddenError } from "@langfuse/shared";import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";import { randomUUID } from "crypto";@@ -18,7 +21,7 @@ export default withMiddlewares({bodySchema: PostScoresBodyV1,responseSchema: PostScoresResponseV1,allowedAccessLevels: ["project", "scores"],- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {if (auth.scope.isIngestionSuspended) {throw new ForbiddenError("Ingestion suspended: Usage threshold exceeded. Please upgrade your plan.",@@ -37,6 +40,10 @@ export default withMiddlewares({const { id, result } = await scoresApiService.createScore({body: conformedBody,auth,+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),});if (result.errors.length > 0) {const error = result.errors[0];diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.tsindex 5894901ae1..46fdc849c6 100644--- a/web/src/pages/api/public/spans.ts+++ b/web/src/pages/api/public/spans.ts@@ -7,6 +7,7 @@ import {import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {+ createIngestionAttribution,eventTypes,logger,processEventBatch,@@ -21,7 +22,7 @@ export default withMiddlewares({// Writes an observation-create event that lands in the legacy observations// ClickHouse table; events_only deployments expect OTel ingestion.rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {const event = {id: v4(),type: eventTypes.OBSERVATION_CREATE,@@ -34,7 +35,12 @@ export default withMiddlewares({if (!event.body.id) {event.body.id = v4();}- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];res@@ -54,7 +60,7 @@ export default withMiddlewares({bodySchema: PatchSpansV1Body,responseSchema: PatchSpansV1Response,rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {const event = {id: v4(),type: eventTypes.OBSERVATION_UPDATE,@@ -65,7 +71,12 @@ export default withMiddlewares({type: "SPAN",},};- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];resdiff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex 87a8ff445e..64e01c0f9d 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -16,6 +16,7 @@ import {import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { processEventBatch } from "@langfuse/shared/src/server";import {+ createIngestionAttribution,eventTypes,logger,traceDeletionProcessor,@@ -42,7 +43,7 @@ export default withMiddlewares(// Legacy POST writes a trace-create event that lands in the legacy traces// ClickHouse table; events_only deployments expect OTel ingestion.rejectInEventsOnlyMode: true,- fn: async ({ body, auth, res }) => {+ fn: async ({ body, auth, req, res }) => {await telemetry();const event = {id: v4(),@@ -53,7 +54,12 @@ export default withMiddlewares(if (!event.body.id) {event.body.id = v4();}- const result = await processEventBatch([event], auth);+ const result = await processEventBatch([event], auth, {+ attribution: createIngestionAttribution({+ headers: req.headers,+ authCheck: auth,+ }),+ });if (result.errors.length > 0) {const error = result.errors[0];resdiff --git a/worker/src/__tests__/eventPropagationJob.test.ts b/worker/src/__tests__/eventPropagationJob.test.tsnew file mode 100644index 0000000000..6ef13ca1ff--- /dev/null+++ b/worker/src/__tests__/eventPropagationJob.test.ts@@ -0,0 +1,223 @@+import { randomUUID } from "node:crypto";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ type TestContext,+} from "vitest";+import waitForExpect from "wait-for-expect";+import {+ clickhouseClient,+ createObservation,+ createOrgProjectAndApiKey,+ createTrace,+ createTracesCh,+ queryClickhouse,+ redis,+} from "@langfuse/shared/src/server";+import { handleEventPropagationJob } from "../features/eventPropagation/handleEventPropagationJob";+import { TableName } from "../services/ClickhouseWriter";++const LAST_PROCESSED_PARTITION_KEY =+ "langfuse:event-propagation:last-processed-partition";++let previousLastProcessedPartition: string | null = null;++async function clickhouseTableExists(table: string): Promise<boolean> {+ const rows = await queryClickhouse<{ count: number | string }>({+ query: `+ SELECT count() AS count+ FROM system.tables+ WHERE database = currentDatabase()+ AND name = {table: String}+ `,+ params: { table },+ });++ return Number(rows[0]?.count ?? 0) > 0;+}++async function skipUnlessEventPropagationTablesExist(+ ctx: TestContext,+): Promise<void> {+ const eventPropagationTablesExist =+ (await clickhouseTableExists(TableName.ObservationsBatchStaging)) &&+ (await clickhouseTableExists(TableName.EventsFull));++ if (!eventPropagationTablesExist) {+ ctx.skip("event propagation ClickHouse tables are not enabled");+ }+}++function formatClickHouseDateTime(date: Date): string {+ return date.toISOString().slice(0, 19).replace("T", " ");+}++describe("handleEventPropagationJob", () => {+ beforeEach(async () => {+ if (!redis) throw new Error("Redis not initialized");++ previousLastProcessedPartition = await redis.get(+ LAST_PROCESSED_PARTITION_KEY,+ );+ await redis.del(LAST_PROCESSED_PARTITION_KEY);+ });++ afterEach(async () => {+ if (!redis) return;++ if (previousLastProcessedPartition === null) {+ await redis.del(LAST_PROCESSED_PARTITION_KEY);+ } else {+ await redis.set(+ LAST_PROCESSED_PARTITION_KEY,+ previousLastProcessedPartition,+ );+ }+ });++ it("propagates observation staging rows into events_full", async (ctx) => {+ await skipUnlessEventPropagationTablesExist(ctx);++ const { projectId } = await createOrgProjectAndApiKey();+ const traceId = randomUUID();+ const observationId = randomUUID();+ const oldEnoughForPropagation = Date.now() - 20 * 60 * 1000;++ await createTracesCh([+ createTrace({+ id: traceId,+ project_id: projectId,+ name: "propagation-trace",+ user_id: "propagation-user",+ session_id: "propagation-session",+ timestamp: oldEnoughForPropagation,+ created_at: oldEnoughForPropagation,+ updated_at: oldEnoughForPropagation,+ event_ts: oldEnoughForPropagation,+ }),+ ]);++ await clickhouseClient().insert({+ table: TableName.ObservationsBatchStaging,+ format: "JSONEachRow",+ values: [+ {+ ...createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: projectId,+ type: "GENERATION",+ environment: "default",+ name: "propagated-observation",+ parent_observation_id: null,+ start_time: oldEnoughForPropagation,+ end_time: oldEnoughForPropagation + 1_000,+ created_at: oldEnoughForPropagation,+ updated_at: oldEnoughForPropagation,+ event_ts: oldEnoughForPropagation,+ }),+ ingestion_api_key: "pk-lf-propagation-test",+ ingestion_sdk_name: "langfuse-js",+ ingestion_sdk_version: "4.2.0",+ s3_first_seen_timestamp: oldEnoughForPropagation,+ },+ ],+ });++ const partitionRows = await queryClickhouse<{ partition: string }>({+ query: `+ SELECT toString(tupleElement(_partition_value, 1)) AS partition+ FROM observations_batch_staging+ WHERE project_id = {projectId: String}+ AND trace_id = {traceId: String}+ AND id = {observationId: String}+ LIMIT 1+ `,+ params: {+ projectId,+ traceId,+ observationId,+ },+ });+ expect(partitionRows[0]?.partition).toBeDefined();++ const partitionCursor = formatClickHouseDateTime(+ new Date(+ new Date(+ `${partitionRows[0]!.partition.replace(" ", "T")}Z`,+ ).getTime() - 1_000,+ ),+ );+ await redis!.set(LAST_PROCESSED_PARTITION_KEY, partitionCursor);++ await handleEventPropagationJob({+ data: { id: "event-propagation-job-test" },+ } as Parameters<typeof handleEventPropagationJob>[0]);++ await waitForExpect(async () => {+ const rows = await queryClickhouse<{+ trace_id: string;+ span_id: string;+ parent_span_id: string;+ name: string;+ type: string;+ environment: string;+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+ trace_name: string;+ user_id: string;+ session_id: string;+ source: string;+ }>({+ query: `+ SELECT+ trace_id,+ span_id,+ parent_span_id,+ name,+ type,+ environment,+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version,+ trace_name,+ user_id,+ session_id,+ source+ FROM events_full FINAL+ WHERE project_id = {projectId: String}+ AND trace_id = {traceId: String}+ AND span_id = {observationId: String}+ LIMIT 1+ `,+ params: {+ projectId,+ traceId,+ observationId,+ },+ });++ expect(rows).toEqual([+ {+ trace_id: traceId,+ span_id: observationId,+ parent_span_id: `t-${traceId}`,+ name: "propagated-observation",+ type: "GENERATION",+ environment: "default",+ ingestion_api_key: "pk-lf-propagation-test",+ ingestion_sdk_name: "langfuse-js",+ ingestion_sdk_version: "4.2.0",+ trace_name: "propagation-trace",+ user_id: "propagation-user",+ session_id: "propagation-session",+ source: "ingestion-api-dual-write",+ },+ ]);+ }, 5_000);+ }, 15_000);+});diff --git a/worker/src/__tests__/processEventBatch.test.ts b/worker/src/__tests__/processEventBatch.test.tsindex 41b91b8c65..e40acaeea7 100644--- a/worker/src/__tests__/processEventBatch.test.ts+++ b/worker/src/__tests__/processEventBatch.test.ts@@ -1,7 +1,73 @@-import { describe, it, expect, assert } from "vitest";-import { processEventBatch } from "@langfuse/shared/src/server";+import { beforeEach, describe, it, expect, assert, vi } from "vitest";+import { eventTypes } from "../../../packages/shared/src/server/ingestion/types";+import { processEventBatch } from "../../../packages/shared/src/server/ingestion/processEventBatch";+import {+ createUnknownSdkIngestionAttribution,+ UNKNOWN_INGESTION_SDK_VALUE,+} from "../../../packages/shared/src/server/ingestion/ingestionAttribution";++const { getQueueInstanceMock, queueAddMock, uploadJsonMock } = vi.hoisted(+ () => ({+ getQueueInstanceMock: vi.fn(),+ queueAddMock: vi.fn(),+ uploadJsonMock: vi.fn(),+ }),+);++vi.mock("../../../packages/shared/src/server/redis/redis", () => ({+ redis: {},+}));++vi.mock("../../../packages/shared/src/env", () => ({+ env: {+ LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS: new Map(),+ LANGFUSE_INGESTION_QUEUE_DELAY_MS: 5000,+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: "event-upload",+ LANGFUSE_S3_EVENT_UPLOAD_PREFIX: "",+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: "false",+ LANGFUSE_SKIP_S3_LIST_FOR_OBSERVATIONS_PROJECT_IDS: "",+ },+}));++vi.mock("../../../packages/shared/src/server/redis/ingestionQueue", () => ({+ IngestionQueue: {+ getInstance: getQueueInstanceMock,+ },+}));++vi.mock("../../../packages/shared/src/server/services/StorageService", () => ({+ StorageService: undefined,+ StorageServiceFactory: {+ getInstance: () => ({+ uploadJson: uploadJsonMock,+ }),+ },+}));++const createTraceCreateEvent = () => {+ const timestamp = "2024-10-12T12:13:14.123Z";++ return {+ id: "event-id",+ timestamp,+ type: eventTypes.TRACE_CREATE,+ body: {+ id: "trace-id",+ timestamp,+ name: "trace",+ environment: "default",+ },+ };+};describe("processEventBatch", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getQueueInstanceMock.mockReturnValue({ add: queueAddMock });+ queueAddMock.mockResolvedValue(undefined);+ uploadJsonMock.mockResolvedValue(undefined);+ });+it("returns early on empty input", async () => {// Auth check with missing projectId will cause an exception unless// there is an early return in processEventBatch@@ -13,13 +79,72 @@ describe("processEventBatch", () => {},};+ const attribution = createUnknownSdkIngestionAttribution({ authCheck });+assert.doesNotThrow(- async () => await processEventBatch([], authCheck, {}),+ async () => await processEventBatch([], authCheck, { attribution }),"UnauthorizedError",);- const res = await processEventBatch([], authCheck, {});+ const res = await processEventBatch([], authCheck, { attribution });expect(res.successes).toEqual([]);expect(res.errors).toEqual([]);});++ it("adds request attribution to ingestion queue payloads", async () => {+ const authCheck = {+ validKey: true as const,+ scope: {+ projectId: "project-id",+ accessLevel: "project" as const,+ publicKey: "pk-lf-public",+ },+ };++ const result = await processEventBatch(+ [createTraceCreateEvent()],+ authCheck,+ {+ delay: 0,+ attribution: {+ ingestionApiKey: "pk-lf-attributed",+ ingestionSdkName: "python",+ ingestionSdkVersion: "3.4.0",+ },+ },+ );++ expect(result).toEqual({+ successes: [{ id: "event-id", status: 201 }],+ errors: [],+ });+ expect(queueAddMock).toHaveBeenCalledTimes(1);+ expect(queueAddMock.mock.calls[0][1].payload.data).toMatchObject({+ ingestionApiKey: "pk-lf-attributed",+ ingestionSdkName: "python",+ ingestionSdkVersion: "3.4.0",+ });+ });++ it("forwards explicit unknown SDK attribution", async () => {+ const authCheck = {+ validKey: true as const,+ scope: {+ projectId: "project-id",+ accessLevel: "project" as const,+ publicKey: "pk-lf-public",+ },+ };++ await processEventBatch([createTraceCreateEvent()], authCheck, {+ delay: 0,+ attribution: createUnknownSdkIngestionAttribution({ authCheck }),+ });++ expect(queueAddMock.mock.calls[0][1].payload.data).toMatchObject({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,+ });+ });});diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.tsindex f5ef61d8da..d3a9d8b7b4 100644--- a/worker/src/features/evaluation/evalExecutionDeps.ts+++ b/worker/src/features/evaluation/evalExecutionDeps.ts@@ -10,6 +10,7 @@ import {LLMAdapter,QueueJobs,ScoreEventType,+ UNKNOWN_INGESTION_SDK_VALUE,} from "@langfuse/shared/src/server";import { buildEvalMessages } from "./evalRuntime";import { getEvalS3StorageClient } from "./s3StorageClient";@@ -190,6 +191,9 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {eventBodyId: params.scoreId,fileKey: params.eventId,bucketPrefix,+ ingestionApiKey: "",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,},authCheck: {validKey: true,diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex e81a1b18f7..a65b8a714a 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -260,7 +260,10 @@ export const handleEventPropagationJob = async (created_at,updated_at,event_ts,- is_deleted+ is_deleted,+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version)SELECTobs.project_id,@@ -316,7 +319,10 @@ export const handleEventPropagationJob = async (obs.created_at,obs.updated_at,obs.event_ts,- obs.is_deleted+ obs.is_deleted,+ obs.ingestion_api_key AS ingestion_api_key,+ obs.ingestion_sdk_name AS ingestion_sdk_name,+ obs.ingestion_sdk_version AS ingestion_sdk_versionFROM observations_batch_staging obs FINALLEFT JOIN relevant_traces tON (diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex d4c2057810..6d54cc5b70 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -5,6 +5,7 @@ import {convertDateToClickhouseDateTime,flattenJsonToPathArrays,recordGauge,+ UNKNOWN_INGESTION_SDK_VALUE,type EventRecordInsertType,} from "@langfuse/shared/src/server";import { env } from "../../env";@@ -623,6 +624,9 @@ export function convertEnrichedSpansToEventRecords(metadata_values: flattened.values.map((v) => v ?? ""),source: span.source,+ ingestion_api_key: "",+ ingestion_sdk_name: UNKNOWN_INGESTION_SDK_VALUE,+ ingestion_sdk_version: UNKNOWN_INGESTION_SDK_VALUE,blob_storage_file_path: "",event_bytes: 0,diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.tsindex f23073da65..dc692dc34e 100644--- a/worker/src/features/experiments/experimentServiceClickhouse.ts+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts@@ -7,6 +7,7 @@ import {import {ChatMessage,convertDateToClickhouseDateTime,+ createUnknownSdkIngestionAttribution,createDatasetItemFilterState,DatasetRunItemUpsertQueue,eventTypes,@@ -92,19 +93,18 @@ async function processItem(},};- const ingestionResult = await processEventBatch(- [event],- {- validKey: true,- scope: {- projectId: config.projectId,- accessLevel: "project" as const,- },- },- {- isLangfuseInternal: true,+ const auth = {+ validKey: true as const,+ scope: {+ projectId: config.projectId,+ accessLevel: "project" as const,},- );+ };++ const ingestionResult = await processEventBatch([event], auth, {+ isLangfuseInternal: true,+ attribution: createUnknownSdkIngestionAttribution({ authCheck: auth }),+ });if (ingestionResult.errors.length > 0) {const error = ingestionResult.errors[0];@@ -459,16 +459,17 @@ async function createAllDatasetRunItemsWithConfigError(`Creating ${events.length / 3} dataset run items with config error`,);- await processEventBatch(- events,- {- validKey: true,- scope: {- projectId,- accessLevel: "project" as const,- },+ const auth = {+ validKey: true as const,+ scope: {+ projectId,+ accessLevel: "project" as const,},- { isLangfuseInternal: true },- );+ };++ await processEventBatch(events, auth, {+ isLangfuseInternal: true,+ attribution: createUnknownSdkIngestionAttribution({ authCheck: auth }),+ });}}diff --git a/worker/src/queues/__tests__/otelFlueMapping.test.ts b/worker/src/queues/__tests__/otelFlueMapping.test.tsindex 16a28bd1b9..180f4d7b59 100644--- a/worker/src/queues/__tests__/otelFlueMapping.test.ts+++ b/worker/src/queues/__tests__/otelFlueMapping.test.ts@@ -10,7 +10,10 @@* Flow tested: ResourceSpan -> OtelIngestionProcessor.processToEvent()*/import { describe, it, expect } from "vitest";-import { OtelIngestionProcessor } from "@langfuse/shared/src/server";+import {+ OtelIngestionProcessor,+ type OtelIngestionProcessorConfig,+} from "@langfuse/shared/src/server";const FLUE_SCOPE = "@flue/opentelemetry";@@ -45,6 +48,7 @@ function attrs(record: Record<string, string>): Attr[] {function processFlueSpan(params: {name: string;attributes: Record<string, string>;+ config?: Partial<OtelIngestionProcessorConfig>;}): any {const resourceSpan = {resource: {@@ -68,13 +72,40 @@ function processFlueSpan(params: {],};- const processor = new OtelIngestionProcessor({ projectId: "test-project" });+ const processor = new OtelIngestionProcessor({+ projectId: "test-project",+ publicKey: "",+ sdkName: "",+ sdkVersion: "",+ ...params.config,+ });const events = processor.processToEvent([resourceSpan]);expect(events).toHaveLength(1);return events[0];}describe("Flue OTel span mapping", () => {+ it("adds request attribution to processed OTel events", () => {+ const event = processFlueSpan({+ name: "flue.operation prompt",+ attributes: {+ "flue.operation.id": "op_01",+ "flue.operation.kind": "prompt",+ },+ config: {+ publicKey: "pk-lf-public",+ sdkName: "python",+ sdkVersion: "3.4.0",+ },+ });++ expect(event).toMatchObject({+ ingestionApiKey: "pk-lf-public",+ ingestionSdkName: "python",+ ingestionSdkVersion: "3.4.0",+ });+ });+it("maps a model-turn span to a GENERATION with flue.turn.input/output", () => {const event = processFlueSpan({name: "chat gpt-4o-mini",diff --git a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts b/worker/src/queues/__tests__/otelMetadataProcessing.test.tsindex 1b6817cbe1..ab6da8357a 100644--- a/worker/src/queues/__tests__/otelMetadataProcessing.test.ts+++ b/worker/src/queues/__tests__/otelMetadataProcessing.test.ts@@ -13,6 +13,14 @@ import { prisma } from "@langfuse/shared/src/db";import { IngestionService } from "../../services/IngestionService";import * as clickhouseWriterExports from "../../services/ClickhouseWriter";+const createTestOtelProcessor = () =>+ new OtelIngestionProcessor({+ projectId: "test-project",+ publicKey: "",+ sdkName: "",+ sdkVersion: "",+ });+// vi.hoisted ensures this is declared before vi.mock's hoisted factory runs.// Without it, the variable would be undefined when the factory executes.const { mockAddToClickhouseWriter } = vi.hoisted(() => ({@@ -118,7 +126,7 @@ function buildOtelSpan(params: {async function processAndCreateEvent(otelSpan: ReturnType<typeof buildOtelSpan>,) {- const processor = new OtelIngestionProcessor({ projectId: "test-project" });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([otelSpan]);expect(eventInputs.length).toBeGreaterThan(0);diff --git a/worker/src/queues/__tests__/otelToObservationForEval.test.ts b/worker/src/queues/__tests__/otelToObservationForEval.test.tsindex cf577b555e..52ad7824b3 100644--- a/worker/src/queues/__tests__/otelToObservationForEval.test.ts+++ b/worker/src/queues/__tests__/otelToObservationForEval.test.ts@@ -21,6 +21,14 @@ import { prisma } from "@langfuse/shared/src/db";import { IngestionService } from "../../services/IngestionService";import * as clickhouseWriterExports from "../../services/ClickhouseWriter";+const createTestOtelProcessor = (projectId = "test-project") =>+ new OtelIngestionProcessor({+ projectId,+ publicKey: "",+ sdkName: "",+ sdkVersion: "",+ });+// Mock ClickhouseWriter to avoid actual database writes.// vi.hoisted ensures this is declared before vi.mock's hoisted factory runs.// Without it, the variable would be undefined when the factory executes.@@ -86,7 +94,7 @@ async function processOtelSpanToObservationForEval(resourceSpan: any,projectId = "test-project",): Promise<ObservationForEval[]> {- const processor = new OtelIngestionProcessor({ projectId });+ const processor = createTestOtelProcessor(projectId);// Process to EventInput array using the real OtelIngestionProcessorconst eventInputs = processor.processToEvent([resourceSpan]);@@ -825,9 +833,7 @@ describe("OTEL to ObservationForEval Schema Validation", () => {],};- const processor = new OtelIngestionProcessor({- projectId: "test-project",- });+ const processor = createTestOtelProcessor();const eventInputs = processor.processToEvent([resourceSpan]);expect(eventInputs).toHaveLength(1);diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex 2c54fda817..5d010b21fa 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -19,6 +19,8 @@ import {SecondaryIngestionQueue,TQueueJobTypes,traceException,+ type IngestionAttribution,+ UNKNOWN_INGESTION_SDK_VALUE,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";@@ -270,6 +272,14 @@ export const ingestionQueueProcessorBuilder = (const forwardToEventsTable =job.data.payload.data.forwardToEventsTable ??v4WritesToEventsTable(env);+ const attribution: IngestionAttribution = {+ ingestionApiKey: job.data.payload.data.ingestionApiKey ?? "",+ ingestionSdkName:+ job.data.payload.data.ingestionSdkName || UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion:+ job.data.payload.data.ingestionSdkVersion ||+ UNKNOWN_INGESTION_SDK_VALUE,+ };// Recover the canonical entity id from the downloaded event body, not// from the queue payload. On replay, `payload.data.eventBodyId` is the@@ -308,14 +318,15 @@ export const ingestionQueueProcessorBuilder = (prisma,clickhouseWriter,clickhouseClient(),- ).mergeAndWrite(- getClickhouseEntityType(events[0].type),- job.data.payload.authCheck.scope.projectId,- canonicalEntityId,- firstS3WriteTime,+ ).mergeAndWrite({+ eventType: getClickhouseEntityType(events[0].type),+ projectId: job.data.payload.authCheck.scope.projectId,+ entityId: canonicalEntityId,+ createdAtTimestamp: firstS3WriteTime,events,forwardToEventsTable,- );+ attribution,+ });} catch (e) {// Check if this is a SlowDown error and mark the project for secondary queueif (isS3SlowDownError(e)) {diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 5b0a9e8c3f..ea8ab81329 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -20,6 +20,8 @@ import {traceException,compareVersions,ResourceSpan,+ type IngestionAttribution,+ UNKNOWN_INGESTION_SDK_VALUE,} from "@langfuse/shared/src/server";import {applyIngestionMasking,@@ -60,7 +62,7 @@ export function checkHeaderBasedDirectWrite(params: {}): boolean {const { sdkName, sdkVersion, ingestionVersion } = params;- // Check x-langfuse-ingestion-version (>= 4 means direct write eligible).+ // Check x-langfuse-ingestion-version.// 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) {@@ -209,9 +211,16 @@ export const otelIngestionQueueProcessorBuilder = (): Promise<void> => {try {const projectId = job.data.payload.authCheck.scope.projectId;- const publicKey = job.data.payload.data.publicKey;+ const publicKey = job.data.payload.data.publicKey ?? "";const fileKey = job.data.payload.data.fileKey;const auth = job.data.payload.authCheck;+ const attribution: IngestionAttribution = {+ ingestionApiKey: publicKey,+ ingestionSdkName:+ job.data.payload.sdkName || UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion:+ job.data.payload.sdkVersion || UNKNOWN_INGESTION_SDK_VALUE,+ };const span = getCurrentSpan();if (span) {@@ -300,7 +309,9 @@ export const otelIngestionQueueProcessorBuilder = (// Generate events via OtelIngestionProcessorconst processor = new OtelIngestionProcessor({projectId,- publicKey,+ publicKey: attribution.ingestionApiKey,+ sdkName: attribution.ingestionSdkName,+ sdkVersion: attribution.ingestionSdkVersion,});const events: IngestionEventType[] =await processor.processToIngestionEvents(parsedSpans);@@ -436,14 +447,15 @@ export const otelIngestionQueueProcessorBuilder = (// Process observations via mergeAndWriteconst observationWritePromise = Promise.all(observations.map((observation) =>- ingestionService.mergeAndWrite(- getClickhouseEntityType(observation.type),- auth.scope.projectId,- observation.body.id || "", // id is always defined for observations- new Date(), // Use the current timestamp as event time- [observation],- shouldForwardToEventsTable,- ),+ ingestionService.mergeAndWrite({+ eventType: getClickhouseEntityType(observation.type),+ projectId: auth.scope.projectId,+ entityId: observation.body.id || "", // id is always defined for observations+ createdAtTimestamp: new Date(), // Use the current timestamp as event time+ events: [observation],+ forwardToEventsTable: shouldForwardToEventsTable,+ attribution,+ }),),);@@ -454,6 +466,7 @@ export const otelIngestionQueueProcessorBuilder = (delay: 0,source: "otel",forwardToEventsTable: shouldForwardToEventsTable,+ attribution,}),]);}diff --git a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.tsindex e657e772cd..8c4f6a0bac 100644--- a/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts+++ b/worker/src/scripts/replayIngestionEvents/s3-ingestion-event-replay.ts@@ -23,6 +23,7 @@ import {rawEventBucketPrefix,SecondaryIngestionQueue,TQueueJobTypes,+ UNKNOWN_INGESTION_SDK_VALUE,} from "@langfuse/shared/src/server";const INPUT_FILE = "events.csv";@@ -58,6 +59,9 @@ interface JsonOutputItem {fileKey: string;type: string;bucketPrefix: string;+ ingestionApiKey: string;+ ingestionSdkName: string;+ ingestionSdkVersion: string;};}@@ -71,7 +75,10 @@ interface OTelJsonOutputItem {};data: {fileKey: string;+ publicKey?: string;};+ sdkName: string;+ sdkVersion: string;}async function filterCsvFile(@@ -349,7 +356,10 @@ async function convertCsvToJsonl(},data: {fileKey: keyValue,+ publicKey: "",},+ sdkName: UNKNOWN_INGESTION_SDK_VALUE,+ sdkVersion: UNKNOWN_INGESTION_SDK_VALUE,};// Write each OTEL JSON object as a single line (JSONL format)@@ -382,6 +392,9 @@ async function convertCsvToJsonl(fileKey: eventId,type: `${entityType}-create`,bucketPrefix,+ ingestionApiKey: "",+ ingestionSdkName: UNKNOWN_INGESTION_SDK_VALUE,+ ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,},};diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 387128c344..163675f51c 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -50,6 +50,7 @@ import {normalizeToolsForObservation,hasNoEvalConfigsCache,buildClickHouseLogComment,+ type IngestionAttribution,} from "@langfuse/shared/src/server";import { tokenCountAsync } from "../../features/tokenisation/async-usage";@@ -76,12 +77,21 @@ function parseUInt16(value: string | null | undefined): number | undefined {return num;}+export type EventInput = InternalTraceEventInput;type InsertRecord =| TraceRecordInsertType| ScoreRecordInsertType| ObservationRecordInsertType| DatasetRunItemRecordInsertType;-export type EventInput = InternalTraceEventInput;+type MergeAndWriteParams = {+ eventType: IngestionEntityTypes;+ projectId: string;+ entityId: string;+ createdAtTimestamp: Date;+ events: IngestionEventType[];+ forwardToEventsTable: boolean;+ attribution: IngestionAttribution;+};const immutableEntityKeys: {[TableName.Traces]: (keyof TraceRecordInsertType)[];@@ -146,14 +156,17 @@ export class IngestionService {this.promptService = new PromptService(prisma, redis);}- public async mergeAndWrite(- eventType: IngestionEntityTypes,- projectId: string,- entityId: string,- createdAtTimestamp: Date,- events: IngestionEventType[],- forwardToEventsTable: boolean,- ): Promise<void> {+ public async mergeAndWrite(params: MergeAndWriteParams): Promise<void> {+ const {+ eventType,+ projectId,+ entityId,+ createdAtTimestamp,+ events,+ forwardToEventsTable,+ attribution,+ } = params;+logger.debug(`Merging ingestion ${eventType} event for project ${projectId} and event ${entityId}`,);@@ -166,6 +179,7 @@ export class IngestionService {createdAtTimestamp,traceEventList: events as TraceEventType[],createEventTraceRecord: forwardToEventsTable,+ attribution,});case "observation":return await this.processObservationEventList({@@ -174,6 +188,7 @@ export class IngestionService {createdAtTimestamp,observationEventList: events as ObservationEvent[],writeToStagingTables: forwardToEventsTable,+ attribution,});case "score": {return await this.processScoreEventList({@@ -181,6 +196,7 @@ export class IngestionService {entityId,createdAtTimestamp,scoreEventList: events as ScoreEventType[],+ attribution,});}case "dataset_run_item": {@@ -344,6 +360,9 @@ export class IngestionService {// Source/instrumentation metadatasource: eventData.source,+ ingestion_api_key: eventData.ingestionApiKey ?? "",+ ingestion_sdk_name: eventData.ingestionSdkName ?? "",+ ingestion_sdk_version: eventData.ingestionSdkVersion ?? "",service_name: eventData.serviceName,service_version: eventData.serviceVersion,scope_name: eventData.scopeName,@@ -492,8 +511,15 @@ export class IngestionService {entityId: string;createdAtTimestamp: Date;scoreEventList: ScoreEventType[];+ attribution: IngestionAttribution;}) {- const { projectId, entityId, createdAtTimestamp, scoreEventList } = params;+ const {+ projectId,+ entityId,+ createdAtTimestamp,+ scoreEventList,+ attribution,+ } = params;if (scoreEventList.length === 0) return;const timeSortedEvents =@@ -551,6 +577,9 @@ export class IngestionService {long_string_value: validatedScore.longStringValue,execution_trace_id: validatedScore.executionTraceId,queue_id: validatedScore.queueId ?? null,+ ingestion_api_key: attribution.ingestionApiKey,+ ingestion_sdk_name: attribution.ingestionSdkName,+ ingestion_sdk_version: attribution.ingestionSdkVersion,created_at: Date.now(),updated_at: Date.now(),event_ts: new Date(scoreEvent.timestamp).getTime(),@@ -596,6 +625,7 @@ export class IngestionService {createdAtTimestamp: Date;traceEventList: TraceEventType[];createEventTraceRecord: boolean;+ attribution: IngestionAttribution;}) {const {projectId,@@ -603,6 +633,7 @@ export class IngestionService {createdAtTimestamp,traceEventList,createEventTraceRecord,+ attribution,} = params;if (traceEventList.length === 0) return;@@ -695,6 +726,7 @@ export class IngestionService {const traceAsStagingObservation = convertTraceToStagingObservation(finalTraceRecord,this.getPartitionAwareTimestamp(createdAtTimestamp),+ attribution,);this.clickHouseWriter.addToQueue(TableName.ObservationsBatchStaging,@@ -741,6 +773,7 @@ export class IngestionService {createdAtTimestamp: Date;observationEventList: ObservationEvent[];writeToStagingTables: boolean;+ attribution: IngestionAttribution;}) {const {projectId,@@ -748,6 +781,7 @@ export class IngestionService {createdAtTimestamp,observationEventList,writeToStagingTables,+ attribution,} = params;if (observationEventList.length === 0) return;@@ -886,6 +920,9 @@ export class IngestionService {if (writeToStagingTables) {const stagingRecord = {...finalObservationRecord,+ ingestion_api_key: attribution.ingestionApiKey,+ ingestion_sdk_name: attribution.ingestionSdkName,+ ingestion_sdk_version: attribution.ingestionSdkVersion,s3_first_seen_timestamp:this.getPartitionAwareTimestamp(createdAtTimestamp),};diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 5e6c2d3a9c..78b1957ee8 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -1,5 +1,13 @@import { randomUUID } from "node:crypto";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type TestContext,+} from "vitest";import { uuid, z } from "zod";import { prisma } from "@langfuse/shared/src/db";import {@@ -16,6 +24,7 @@ import {TraceRecordReadType,createOrgProjectAndApiKey,createIngestionEventSchema,+ queryClickhouse,setNoEvalConfigsCache,} from "@langfuse/shared/src/server";import waitForExpect from "wait-for-expect";@@ -25,6 +34,12 @@ import { ModelUsageUnit, ScoreSourceEnum } from "@langfuse/shared";let projectId = "";const environment = "default";+const testIngestionAttribution = {+ ingestionApiKey: "pk-lf-ingestion-service-test",+ ingestionSdkName: "langfuse-test",+ ingestionSdkVersion: "0.0.0",+};+let observationsBatchStagingTableEnabled: boolean | undefined;describe("Ingestion end-to-end tests", () => {let ingestionService: IngestionService;@@ -104,6 +119,60 @@ describe("Ingestion end-to-end tests", () => {expect(trace.timestamp).toBe(timestamp);});+ it("should write ingestion attribution to observation staging records", async (ctx) => {+ await skipUnlessObservationsBatchStagingEnabled(ctx);++ const traceId = randomUUID();+ const generationId = randomUUID();+ const timestamp = new Date().toISOString();+ const attribution = {+ ingestionApiKey: "pk-lf-ingestion-service-integration",+ ingestionSdkName: "langfuse-js",+ ingestionSdkVersion: "4.2.0",+ };++ const generationEventList: ObservationEvent[] = [+ {+ id: randomUUID(),+ type: "generation-create",+ timestamp,+ body: {+ id: generationId,+ traceId,+ startTime: timestamp,+ name: "generation-with-attribution",+ environment,+ },+ },+ ];++ await ingestionService.mergeAndWrite({+ projectId,+ entityId: generationId,+ createdAtTimestamp: new Date(timestamp),+ eventType: "observation",+ events: generationEventList,+ forwardToEventsTable: true,+ attribution,+ });++ await clickhouseWriter.flushAll(true);++ const generation = await getClickhouseRecord(+ TableName.Observations,+ generationId,+ );+ const stagingAttribution =+ await getClickhouseObservationBatchStagingAttribution(generationId);++ expect(generation.id).toBe(generationId);+ expect(stagingAttribution).toEqual({+ ingestion_api_key: attribution.ingestionApiKey,+ ingestion_sdk_name: attribution.ingestionSdkName,+ ingestion_sdk_version: attribution.ingestionSdkVersion,+ });+ });+[{usage: {@@ -554,6 +623,7 @@ describe("Ingestion end-to-end tests", () => {entityId: scoreId,createdAtTimestamp: new Date(),scoreEventList,+ attribution: testIngestionAttribution,}),]);@@ -664,6 +734,7 @@ describe("Ingestion end-to-end tests", () => {entityId: scoreId,createdAtTimestamp: new Date(),scoreEventList,+ attribution: testIngestionAttribution,}),]);@@ -1139,6 +1210,7 @@ describe("Ingestion end-to-end tests", () => {entityId: scoreId,createdAtTimestamp: new Date(),scoreEventList,+ attribution: testIngestionAttribution,}),]);@@ -1251,6 +1323,7 @@ describe("Ingestion end-to-end tests", () => {projectId,entityId: validScoreId1,createdAtTimestamp: new Date(),+ attribution: testIngestionAttribution,scoreEventList: [{id: validScoreId1,@@ -1274,6 +1347,7 @@ describe("Ingestion end-to-end tests", () => {projectId,entityId: validScoreId2,createdAtTimestamp: new Date(),+ attribution: testIngestionAttribution,scoreEventList: [// invalid score 1{@@ -2947,6 +3021,43 @@ async function getClickhouseRecord<T extends TableName>() as RecordReadType<T>;}+async function getClickhouseObservationBatchStagingAttribution(+ entityId: string,+): Promise<{+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+}> {+ let result: unknown;++ const loadResult = async () => {+ const query = await clickhouseClient().query({+ query: `+ SELECT+ ingestion_api_key,+ ingestion_sdk_name,+ ingestion_sdk_version+ FROM ${TableName.ObservationsBatchStaging} FINAL+ WHERE project_id = '${projectId}' AND id = '${entityId}'+ `,+ format: "JSONEachRow",+ });++ result = (await query.json())[0];+ };++ await waitForExpect(async () => {+ await loadResult();+ expect(result).toBeDefined();+ }, 1_500);++ return result as {+ ingestion_api_key: string;+ ingestion_sdk_name: string;+ ingestion_sdk_version: string;+ };+}+type RecordReadType<T extends TableName> = T extends TableName.Scores? ScoreRecordReadType: T extends TableName.Observations@@ -2954,3 +3065,36 @@ type RecordReadType<T extends TableName> = T extends TableName.Scores: T extends TableName.Traces? TraceRecordReadType: never;++async function isObservationsBatchStagingEnabled(): Promise<boolean> {+ if (observationsBatchStagingTableEnabled !== undefined) {+ return observationsBatchStagingTableEnabled;+ }++ try {+ const rows = await queryClickhouse<{ count: number | string }>({+ query: `+ SELECT count() AS count+ FROM system.tables+ WHERE database = currentDatabase()+ AND name = {table: String}+ `,+ params: {+ table: TableName.ObservationsBatchStaging,+ },+ });+ observationsBatchStagingTableEnabled = Number(rows[0]?.count ?? 0) > 0;+ } catch {+ observationsBatchStagingTableEnabled = false;+ }++ return observationsBatchStagingTableEnabled;+}++async function skipUnlessObservationsBatchStagingEnabled(+ ctx: TestContext,+): Promise<void> {+ if (!(await isObservationsBatchStagingEnabled())) {+ ctx.skip("observations_batch_staging is not enabled in this ClickHouse");+ }+}