🪢 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
perf: opt-out of FINAL modifier on observations for otel projects (#10558)
Steffen Schmitz1f3affc02532
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 9970f857e8..a5727e2d20 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -227,6 +227,18 @@ const EnvSchema = z.object({LANGFUSE_AWS_BEDROCK_REGION: z.string().optional(),+ // API Performance Flags+ // Whether to add a `FINAL` modifier to the observations CTE in GET /api/public/traces.+ // Can be used to improve performance for self-hosters that are fully on the new OTel SDKs.+ LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL: z+ .enum(["true", "false"])+ .default("false"),+ // Enable Redis-based tracking of projects using OTEL API to optimize ClickHouse queries.+ // When enabled, projects ingesting via OTEL API skip the FINAL modifier on some observations queries for better performance.+ LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS: z+ .enum(["true", "false"])+ .default("false"),+// Langfuse AI FeaturesLANGFUSE_AI_FEATURES_PUBLIC_KEY: z.string().optional(),LANGFUSE_AI_FEATURES_SECRET_KEY: z.string().optional(),diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex bf106a465d..0dac5bcdfb 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -71,6 +71,7 @@ export * from "./redis/experimentCreateQueue";export * from "./redis/dlqRetryQueue";export * from "./redis/entityChangeQueue";export * from "./redis/eventPropagationQueue";+export * from "./redis/otelProjectTracking";export * from "./auth/types";export * from "./queues";export * from "./orderByToPrisma";@@ -79,6 +80,7 @@ export * from "./instrumentation";export * from "./logger";export * from "./headerPropagation";export * from "./queries";+export * from "./queries/clickhouse-sql/query-options";export * from "./repositories";export * from "./repositories/traces";export * from "./utils/rendering";diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-options.ts b/packages/shared/src/server/queries/clickhouse-sql/query-options.tsnew file mode 100644index 0000000000..6ff34697ec--- /dev/null+++ b/packages/shared/src/server/queries/clickhouse-sql/query-options.ts@@ -0,0 +1,35 @@+import { isProjectOtelUser } from "../../redis/otelProjectTracking";+import { recordIncrement } from "../../";+import { env } from "../../../env";++/**+ * Determines whether the FINAL modifier should be skipped for observations queries.+ *+ * Logic flow:+ * 1. Check LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL (takes precedence)+ * 2. If LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS is enabled, check Redis for project OTEL usage+ * 3. Returns boolean+ */+export async function shouldSkipObservationsFinal(+ projectId: string,+): Promise<boolean> {+ // Check env var first (takes precedence) - only if env is provided+ if (env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL === "true") {+ recordIncrement("query.final_modifier.skipped", 1, {+ reason: "env_var",+ });+ return true;+ }++ // Check if OTEL tracking feature is enabled and if project uses OTEL+ const isOtelProject = await isProjectOtelUser(projectId);++ if (isOtelProject) {+ recordIncrement("query.final_modifier.skipped", 1, {+ reason: "otel_tracking",+ });+ return true;+ }++ return false;+}diff --git a/packages/shared/src/server/redis/otelProjectTracking.ts b/packages/shared/src/server/redis/otelProjectTracking.tsnew file mode 100644index 0000000000..2aef382e88--- /dev/null+++ b/packages/shared/src/server/redis/otelProjectTracking.ts@@ -0,0 +1,51 @@+import { redis } from "./redis";+import { env } from "../../env";+import { logger, traceException, recordIncrement } from "../";++const TTL_SECONDS = 86400; // 24 hours++/**+ * Marks a project as using OTEL API ingestion in Redis with a 24-hour TTL.+ * Only performs the operation if LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS is enabled.+ */+export async function markProjectAsOtelUser(projectId: string): Promise<void> {+ // Check if feature is enabled+ if (env.LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS !== "true") {+ return;+ }++ try {+ const key = `langfuse:project:${projectId}:otel:active`;+ await redis?.set(key, "1", "EX", TTL_SECONDS);+ recordIncrement("redis.otel_tracking.marked", 1);+ } catch (error) {+ // Log error but don't throw - Redis failures should not break ingestion+ traceException(error);+ logger.error("Failed to mark project as OTEL user", { projectId, error });+ }+}++/**+ * Checks if a project is currently marked as using OTEL API ingestion.+ * Returns false if feature is disabled or if Redis key doesn't exist.+ */+export async function isProjectOtelUser(projectId: string): Promise<boolean> {+ // If feature is disabled, always return false+ if (env.LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS !== "true") {+ return false;+ }++ try {+ const key = `langfuse:project:${projectId}:otel:active`;+ const result = await redis?.get(key);+ return result === "1";+ } catch (error) {+ // Log error and return false (safe fallback - keep FINAL)+ traceException(error);+ logger.error("Failed to check if project is OTEL user", {+ projectId,+ error,+ });+ return false;+ }+}diff --git a/web/src/__tests__/dashboard-router-pivot-table.servertest.ts b/web/src/__tests__/dashboard-router-pivot-table.servertest.tsindex 0bd897867e..23e6e46a70 100644--- a/web/src/__tests__/dashboard-router-pivot-table.servertest.ts+++ b/web/src/__tests__/dashboard-router-pivot-table.servertest.ts@@ -359,7 +359,7 @@ describe("Dashboard Router - Pivot Table Integration", () => {});describe("Query Builder integration with pivot table configurations", () => {- it("should generate correct SQL for zero-dimension pivot table", () => {+ it("should generate correct SQL for zero-dimension pivot table", async () => {const query: QueryType = {view: "traces",dimensions: [],@@ -378,7 +378,10 @@ describe("Dashboard Router - Pivot Table Integration", () => {};const queryBuilder = new QueryBuilder(query.chartConfig);- const { query: sql, parameters } = queryBuilder.build(query, projectId);+ const { query: sql, parameters } = await queryBuilder.build(+ query,+ projectId,+ );// Verify SQL generationexpect(sql).toBeDefined();@@ -393,7 +396,7 @@ describe("Dashboard Router - Pivot Table Integration", () => {expect(sql.toLowerCase()).toContain("count(");});- it("should generate correct SQL for single-dimension pivot table", () => {+ it("should generate correct SQL for single-dimension pivot table", async () => {const query: QueryType = {view: "traces",dimensions: [{ field: "environment" }],@@ -412,7 +415,10 @@ describe("Dashboard Router - Pivot Table Integration", () => {};const queryBuilder = new QueryBuilder(query.chartConfig);- const { query: sql, parameters } = queryBuilder.build(query, projectId);+ const { query: sql, parameters } = await queryBuilder.build(+ query,+ projectId,+ );// Verify SQL generationexpect(sql).toBeDefined();@@ -427,7 +433,7 @@ describe("Dashboard Router - Pivot Table Integration", () => {expect(sql.toLowerCase()).toContain("order by");});- it("should generate correct SQL for two-dimension pivot table", () => {+ it("should generate correct SQL for two-dimension pivot table", async () => {const query: QueryType = {view: "observations",dimensions: [{ field: "environment" }, { field: "providedModelName" }],@@ -452,7 +458,10 @@ describe("Dashboard Router - Pivot Table Integration", () => {};const queryBuilder = new QueryBuilder(query.chartConfig);- const { query: sql, parameters } = queryBuilder.build(query, projectId);+ const { query: sql, parameters } = await queryBuilder.build(+ query,+ projectId,+ );// Verify SQL generationexpect(sql).toBeDefined();diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsindex fd0047aa86..183227ba53 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -971,7 +971,10 @@ describe("queryBuilder", () => {// Execute queryconst queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause is present in the queryexpect(compiledQuery).toContain("ORDER BY name asc");@@ -1016,7 +1019,10 @@ describe("queryBuilder", () => {// Execute queryconst queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause is present in the queryexpect(compiledQuery).toContain("ORDER BY sum_observationsCount desc");@@ -1064,7 +1070,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause is present in the query with both fieldsexpect(compiledQuery).toContain(@@ -1132,7 +1141,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause includes default time dimension orderingexpect(compiledQuery).toContain("ORDER BY time_dimension asc");@@ -1185,7 +1197,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause includes default metric ordering (descending)expect(compiledQuery).toContain("ORDER BY sum_observationsCount desc");@@ -1229,7 +1244,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify ORDER BY clause includes default dimension ordering (ascending)expect(compiledQuery).toContain("ORDER BY name asc");@@ -1390,7 +1408,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify WITH FILL clause is present in the queryexpect(compiledQuery).toContain("WITH FILL");@@ -1865,7 +1886,7 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery, parameters } = queryBuilder.build(+ const { query: compiledQuery, parameters } = await queryBuilder.build(query,projectId,);@@ -2085,7 +2106,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify joins includedexpect(compiledQuery).toContain("LEFT JOIN traces");@@ -2360,7 +2384,10 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery } = queryBuilder.build(query, projectId);+ const { query: compiledQuery } = await queryBuilder.build(+ query,+ projectId,+ );// Verify the compiled query contains filtering on nameexpect(compiledQuery).toContain("scores_numeric.name");@@ -2490,7 +2517,7 @@ describe("queryBuilder", () => {};const queryBuilder = new QueryBuilder();- const { query: compiledQuery, parameters } = queryBuilder.build(+ const { query: compiledQuery, parameters } = await queryBuilder.build(query,projectId,);@@ -3149,7 +3176,7 @@ describe("queryBuilder", () => {const queryBuilder = new QueryBuilder(customBinHistogramQuery.chartConfig,);- const { query: compiledQuery } = queryBuilder.build(+ const { query: compiledQuery } = await queryBuilder.build(customBinHistogramQuery,projectId,);diff --git a/web/src/__tests__/queryBuilderSQLI.servertest.ts b/web/src/__tests__/queryBuilderSQLI.servertest.tsindex 7ae578c916..20e4baebe8 100644--- a/web/src/__tests__/queryBuilderSQLI.servertest.ts+++ b/web/src/__tests__/queryBuilderSQLI.servertest.ts@@ -56,12 +56,13 @@ describe("QueryBuilder SQL Injection Tests", () => {timeDimension: null,fromTimestamp: defaultFromTime,toTimestamp: defaultToTime,+ orderBy: null,};// Should throw an error rather than allow the injection- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});});@@ -82,9 +83,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid dimension- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid dimension");+ ).rejects.toThrow("Invalid dimension");});it("should safely handle special characters in valid dimension fields", async () => {@@ -109,7 +110,7 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should build a valid query using parameterized queries for safety- const result = buildQueryWithoutExecuting(query, projectId);+ const result = await buildQueryWithoutExecuting(query, projectId);// Ensure the value is parameterized and not directly included in the SQLexpect(result.query).not.toContain("chat'; DROP TABLE traces; --");@@ -140,9 +141,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid metric- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid metric");+ ).rejects.toThrow("Invalid metric");});it("should prevent injection via metric aggregation", async () => {@@ -165,9 +166,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid aggregation- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});});@@ -193,9 +194,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid filter field- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid filter");+ ).rejects.toThrow("Invalid filter");});it("should prevent injection via filter operator", async () => {@@ -219,9 +220,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid operator- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});it("should safely handle special characters in filter values", async () => {@@ -245,7 +246,7 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should build a valid query with parameterization- const result = buildQueryWithoutExecuting(query, projectId);+ const result = await buildQueryWithoutExecuting(query, projectId);// Check for parameterizationexpect(result.query).not.toContain("production'; DROP TABLE traces; --");@@ -275,7 +276,7 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should parameterize the values- const result = buildQueryWithoutExecuting(query, projectId);+ const result = await buildQueryWithoutExecuting(query, projectId);expect(result.query).not.toContain("production,development'); DROP TABLE traces; --",@@ -304,9 +305,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid filter field- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid filter");+ ).rejects.toThrow("Invalid filter");});it("should prevent SQL injection via metadata operator", async () => {@@ -331,9 +332,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid operator- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});it("should safely handle special characters in metadata key path", async () => {@@ -358,7 +359,7 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should build a valid query with parameterization- const result = buildQueryWithoutExecuting(query, projectId);+ const result = await buildQueryWithoutExecuting(query, projectId);// Check for parameterizationexpect(result.query).not.toContain(@@ -391,7 +392,7 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should build a valid query with parameterization- const result = buildQueryWithoutExecuting(query, projectId);+ const result = await buildQueryWithoutExecuting(query, projectId);// Check for parameterizationexpect(result.query).not.toContain("test'); DROP TABLE traces; --");@@ -422,9 +423,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid type- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});});@@ -444,9 +445,9 @@ describe("QueryBuilder SQL Injection Tests", () => {orderBy: null,};// Should throw an error for invalid granularity- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});});@@ -465,9 +466,9 @@ describe("QueryBuilder SQL Injection Tests", () => {orderBy: null,};// Should throw an error for invalid timestamp format- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});});@@ -488,7 +489,10 @@ describe("QueryBuilder SQL Injection Tests", () => {const maliciousProjectId = "fake-id'; DROP TABLE traces; --";// Should parameterize the project ID- const result = buildQueryWithoutExecuting(query, maliciousProjectId);+ const result = await buildQueryWithoutExecuting(+ query,+ maliciousProjectId,+ );// Check for parameterizationexpect(result.query).not.toContain(maliciousProjectId);@@ -517,9 +521,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid orderBy field- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid orderBy field");+ ).rejects.toThrow("Invalid orderBy field");});it("should prevent injection via orderBy direction", async () => {@@ -541,9 +545,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid direction- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid query");+ ).rejects.toThrow("Invalid query");});it("should prevent injection via non-existing metric field in orderBy", async () => {@@ -565,9 +569,9 @@ describe("QueryBuilder SQL Injection Tests", () => {};// Should throw an error for invalid orderBy field- expect(() =>+ await expect(buildQueryWithoutExecuting(maliciousQuery, projectId),- ).toThrow("Invalid orderBy field");+ ).rejects.toThrow("Invalid orderBy field");});});diff --git a/web/src/env.mjs b/web/src/env.mjsindex 82081daa6f..b401e296d5 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -318,9 +318,9 @@ export const env = createEnv({LANGFUSE_AI_FEATURES_PROJECT_ID: z.string().optional(),// API Performance Flags- // Whether to add a `FINAL` modifier to the observations CTE in GET /api/public/traces.- // Can be used to improve performance for self-hosters that are fully on the new OTel SDKs.- LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL: z+ // Enable Redis-based tracking of projects using OTEL API to optimize ClickHouse queries.+ // When enabled, projects ingesting via OTEL API skip the FINAL modifier on some observations queries for better performance.+ LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS: z.enum(["true", "false"]).default("false"),// Whether to propagate the toTimestamp restriction (including a server-side offset)@@ -647,8 +647,8 @@ export const env = createEnv({// Api Performance FlagsLANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS:process.env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS,- LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL:- process.env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL,+ LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS:+ process.env.LANGFUSE_SKIP_FINAL_FOR_OTEL_PROJECTS,// Natural Language FiltersLANGFUSE_AI_FEATURES_PUBLIC_KEY:diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.tsindex 106153d39e..67339670a8 100644--- a/web/src/features/public-api/server/observations.ts+++ b/web/src/features/public-api/server/observations.ts@@ -7,9 +7,9 @@ import {measureAndReturn,observationsTableUiColumnDefinitions,convertObservation,+ shouldSkipObservationsFinal,} from "@langfuse/shared/src/server";import type { FilterState } from "@langfuse/shared";-import { env } from "@/src/env.mjs";type QueryType = {page: number;@@ -32,8 +32,9 @@ export const generateObservationsForPublicApi = async (props: QueryType) => {const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");// ClickHouse query optimizations for List Observations API- const disableObservationsFinal =- env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL === "true";+ const disableObservationsFinal = await shouldSkipObservationsFinal(+ props.projectId,+ );const query = `with clickhouse_keys as (diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.tsindex 22990d80a4..0a1db227b9 100644--- a/web/src/features/public-api/server/traces.ts+++ b/web/src/features/public-api/server/traces.ts@@ -10,6 +10,7 @@ import {deriveFilters,createPublicApiTracesColumnMapping,tracesTableUiColumnDefinitions,+ shouldSkipObservationsFinal,} from "@langfuse/shared/src/server";import { type OrderByState } from "@langfuse/shared";import {@@ -40,7 +41,7 @@ export type TraceQueryType = {useEventsTable?: boolean | null;};-function buildTracesBaseQuery(+async function buildTracesBaseQuery(props: TraceQueryType,select:| {@@ -59,14 +60,15 @@ function buildTracesBaseQuery(},advancedFilters?: FilterState,orderBy?: OrderByState,-): {+): Promise<{query: string;params: Record<string, any>;fromTimeFilter?: DateTimeFilter | undefined;-} {+}> {// ClickHouse query optimizations for List Traces API- const disableObservationsFinal =- env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL === "true";+ const disableObservationsFinal = await shouldSkipObservationsFinal(+ props.projectId,+ );const propagateObservationsTimeBounds =env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS === "true";@@ -319,7 +321,7 @@ export const generateTracesForPublicApi = async ({const includeObservations = requestedFields.includes("observations");const includeMetrics = requestedFields.includes("metrics");- const { query, params, fromTimeFilter } = buildTracesBaseQuery(+ const { query, params, fromTimeFilter } = await buildTracesBaseQuery(props,{includeIO,@@ -399,7 +401,7 @@ export const getTracesCountForPublicApi = async ({};if (advancedFilters !== undefined && advancedFilters.length > 0) {- ({ query, params } = buildTracesBaseQuery(+ ({ query, params } = await buildTracesBaseQuery(props,{includeObservations: false,diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex f0737e5ec8..897bcd6194 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -1,5 +1,8 @@import { type z } from "zod/v4";-import { convertDateToClickhouseDateTime } from "@langfuse/shared/src/server";+import {+ convertDateToClickhouseDateTime,+ shouldSkipObservationsFinal,+} from "@langfuse/shared/src/server";import {type QueryType,type ViewDeclarationType,@@ -359,6 +362,7 @@ export class QueryBuilder {view: ViewDeclarationType,filterList: FilterList,query: QueryType,+ skipObservationsFinal: boolean,) {const relationJoins = [];for (const relationTableName of relationTables) {@@ -369,7 +373,11 @@ export class QueryBuilder {}const relation = view.tableRelations[relationTableName];- let joinStatement = `LEFT JOIN ${relation.name} FINAL ${relation.joinConditionSql}`;+ // Conditionally add FINAL - skip for observations if flag is set+ const shouldUseFinal = !(+ relation.name === "observations" && skipObservationsFinal+ );+ let joinStatement = `LEFT JOIN ${relation.name}${shouldUseFinal ? " FINAL" : ""} ${relation.joinConditionSql}`;// Create time dimension mapping for the relation tableconst relationTimeDimensionMapping = {@@ -784,10 +792,10 @@ export class QueryBuilder {* ORDER BY <fields with directions>* ```*/- public build(+ public async build(query: QueryType,projectId: string,- ): { query: string; parameters: Record<string, unknown> } {+ ): Promise<{ query: string; parameters: Record<string, unknown> }> {// Run zod validationconst parseResult = queryModel.safeParse(query);if (!parseResult.success) {@@ -799,8 +807,16 @@ export class QueryBuilder {// Initialize parameters objectconst parameters: Record<string, unknown> = {};- // Get view declaration- const view = this.getViewDeclaration(query.view);+ // Check if we should skip FINAL modifier for observations (OTEL optimization)+ const skipObservationsFinal = await shouldSkipObservationsFinal(projectId);+ let view = this.getViewDeclaration(query.view);+ // Skip FINAL on observations base table if OTEL project+ if (view.name === "observations" && skipObservationsFinal) {+ view = {+ ...view,+ baseCte: "observations", // Remove FINAL (was "observations FINAL")+ };+ }// Map dimensions and metricsconst appliedDimensions = this.mapDimensions(query.dimensions, view);@@ -834,6 +850,7 @@ export class QueryBuilder {view,filterList,query,+ skipObservationsFinal,);fromClause += ` ${relationJoins.join(" ")}`;}diff --git a/web/src/features/query/server/queryExecutor.ts b/web/src/features/query/server/queryExecutor.tsindex c76b78511d..63d26db610 100644--- a/web/src/features/query/server/queryExecutor.ts+++ b/web/src/features/query/server/queryExecutor.ts@@ -13,7 +13,7 @@ export async function executeQuery(projectId: string,query: QueryType,): Promise<Array<Record<string, unknown>>> {- const { query: compiledQuery, parameters } = new QueryBuilder(+ const { query: compiledQuery, parameters } = await new QueryBuilder(query.chartConfig,).build(query, projectId);diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex 0ba0b78df3..7152b12d7d 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -1,6 +1,10 @@import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";-import { logger, OtelIngestionProcessor } from "@langfuse/shared/src/server";+import {+ logger,+ OtelIngestionProcessor,+ markProjectAsOtelUser,+} from "@langfuse/shared/src/server";import { z } from "zod/v4";import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";import { gunzip } from "node:zlib";@@ -26,6 +30,9 @@ export default withMiddlewares({);}+ // Mark project as using OTEL API+ await markProjectAsOtelUser(auth.scope.projectId);+let body: Buffer;try {body = await new Promise((resolve, reject) => {