🪢 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: introducing a single-level SELECt optimization in queryBuilder. (#11060)
Valery Meleshkina752bcf2ded4
diff --git a/web/src/__tests__/queryBuilder.servertest.ts b/web/src/__tests__/queryBuilder.servertest.tsindex 183227ba53..e4dd31c7a5 100644--- a/web/src/__tests__/queryBuilder.servertest.ts+++ b/web/src/__tests__/queryBuilder.servertest.ts@@ -3265,4 +3265,348 @@ describe("queryBuilder", () => {});});});++ describe("single-level SELECT optimization", () => {+ it("should produce same results with and without optimization for observations view", async () => {+ const projectId = randomUUID();++ // Create test data+ const traces = [+ createTrace({+ project_id: projectId,+ name: "test-trace-1",+ timestamp: new Date().getTime(),+ }),+ createTrace({+ project_id: projectId,+ name: "test-trace-2",+ timestamp: new Date().getTime(),+ }),+ ];+ await createTracesCh(traces);++ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traces[0].id,+ name: "obs-1",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 1000,+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[1].id,+ name: "obs-2",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 2000,+ }),+ ];+ await createObservationsCh(observations);++ // Query with measures that support optimization (all have aggs)+ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "latency", aggregation: "avg" },+ { measure: "latency", aggregation: "max" },+ { measure: "totalCost", aggregation: "sum" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: [{ field: "name", direction: "asc" }],+ };++ // Execute without optimization+ const resultWithoutOpt = await executeQuery(+ projectId,+ query,+ "v1",+ false,+ );++ // Execute with optimization+ const resultWithOpt = await executeQuery(projectId, query, "v1", true);++ // Results should be identical+ expect(resultWithOpt).toHaveLength(resultWithoutOpt.length);+ expect(resultWithOpt).toEqual(resultWithoutOpt);+ });++ it("should NOT optimize when measure without aggs is included (countScores)", async () => {+ const projectId = randomUUID();++ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "latency", aggregation: "avg" }, // Has aggs+ { measure: "countScores", aggregation: "sum" }, // NO aggs - relation table measure+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ };++ // Build query with optimization enabled+ const builder = new QueryBuilder(undefined, "v1");+ const { query: compiledQuery } = await builder.build(+ query,+ projectId,+ true,+ );++ // Should use two-level query (because countScores doesn't have aggs)+ expect(compiledQuery).toContain("FROM (");+ expect(compiledQuery.match(/GROUP BY/g)?.length).toBe(2); // Two GROUP BY clauses++ // Should have the JOIN+ expect(compiledQuery).toContain("LEFT JOIN scores");+ });++ it("should handle complex multi-aggregation measure (tokensPerSecond)", async () => {+ const projectId = randomUUID();++ // Create observation with token usage+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ name: "test-obs",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 1000,+ usage_details: { total: 100 },+ }),+ ];+ await createObservationsCh(observations);++ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "name" }],+ metrics: [+ { measure: "tokensPerSecond", aggregation: "avg" }, // Uses BOTH sumMap AND any+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ };++ const builder = new QueryBuilder(undefined, "v1");+ const { query: compiledQuery } = await builder.build(+ query,+ projectId,+ true,+ );++ // Verify template substitution for multiple aggs was stripped+ expect(compiledQuery).not.toContain("${agg"); // No templates left++ // Verify results match+ const resultWithOpt = await executeQuery(projectId, query, "v1", true);+ const resultWithoutOpt = await executeQuery(+ projectId,+ query,+ "v1",+ false,+ );+ expect(resultWithOpt).toEqual(resultWithoutOpt);+ });++ it("should verify SQL query structure with optimization enabled", async () => {+ const projectId = randomUUID();++ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "name" }],+ metrics: [{ measure: "latency", aggregation: "avg" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ };++ const builder = new QueryBuilder(undefined, "v1");+ const { query: compiledQuery } = await builder.build(+ query,+ projectId,+ true,+ );++ // Verify single-level structure+ expect(compiledQuery).not.toContain("FROM ("); // No subquery+ expect(compiledQuery.match(/GROUP BY/g)?.length).toBe(1); // Only one GROUP BY++ // Verify @@AGG1@@, @@AGG2@@, etc. templates were substituted or removed+ expect(compiledQuery).not.toContain("@@AGG");++ // Verify direct aggregation (should have date_diff without template wrappers)+ expect(compiledQuery).toContain("date_diff");+ });++ it("should handle totalCost measure correctly in both modes", async () => {+ const projectId = randomUUID();++ // Create observations with cost data+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ name: "obs-1",+ start_time: new Date().getTime(),+ total_cost: 0.05,+ }),+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ name: "obs-2",+ start_time: new Date().getTime(),+ total_cost: 0.15,+ }),+ ];+ await createObservationsCh(observations);++ const query: QueryType = {+ view: "observations",+ dimensions: [],+ metrics: [+ { measure: "totalCost", aggregation: "sum" },+ { measure: "totalCost", aggregation: "avg" },+ ],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ };++ // Verify results match between optimized and non-optimized+ const resultWithOpt = await executeQuery(projectId, query, "v1", true);+ const resultWithoutOpt = await executeQuery(+ projectId,+ query,+ "v1",+ false,+ );++ expect(resultWithOpt).toEqual(resultWithoutOpt);+ expect(resultWithOpt).toHaveLength(1);+ // Should have sum (0.05 + 0.15 = 0.20) and avg (0.10)+ expect(Number(resultWithOpt[0].sum_totalCost)).toBeCloseTo(0.2, 2);+ expect(Number(resultWithOpt[0].avg_totalCost)).toBeCloseTo(0.1, 2);+ });++ it("should optimize queries with dimensions from relation tables", async () => {+ const projectId = randomUUID();++ // Create traces+ const traces = [+ createTrace({+ project_id: projectId,+ name: "trace-alpha",+ timestamp: new Date().getTime(),+ }),+ createTrace({+ project_id: projectId,+ name: "trace-beta",+ timestamp: new Date().getTime(),+ }),+ ];+ await createTracesCh(traces);++ // Create observations linked to traces+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: traces[0].id,+ name: "obs-1",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 1000,+ }),+ createObservation({+ project_id: projectId,+ trace_id: traces[1].id,+ name: "obs-2",+ start_time: new Date().getTime(),+ end_time: new Date().getTime() + 2000,+ }),+ ];+ await createObservationsCh(observations);++ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "traceName" }], // Dimension from relation table!+ metrics: [{ measure: "latency", aggregation: "avg" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: new Date(Date.now() - 86400000).toISOString(),+ toTimestamp: new Date(Date.now() + 86400000).toISOString(),+ orderBy: null,+ };++ // Execute with optimization+ const resultWithOpt = await executeQuery(projectId, query, "v1", true);+ const resultWithoutOpt = await executeQuery(+ projectId,+ query,+ "v1",+ false,+ );++ // Results should match+ expect(resultWithOpt).toEqual(resultWithoutOpt);+ expect(resultWithOpt).toHaveLength(2);++ // Verify we got the trace names+ const traceNames = resultWithOpt.map((r) => r.traceName).sort();+ expect(traceNames).toEqual(["trace-alpha", "trace-beta"]);+ });++ it("should optimize queries with computed dimensions like startTimeMonth", async () => {+ const projectId = randomUUID();++ // Create observations in March 2024+ const marchDate = new Date("2024-03-15T12:00:00.000Z");+ const observations = [+ createObservation({+ project_id: projectId,+ trace_id: randomUUID(),+ name: "obs-march",+ start_time: marchDate.getTime(),+ }),+ ];+ await createObservationsCh(observations);++ const query: QueryType = {+ view: "observations",+ dimensions: [{ field: "startTimeMonth" }], // Computed dimension!+ metrics: [{ measure: "latency", aggregation: "avg" }],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2024-03-01T00:00:00.000Z",+ toTimestamp: "2024-03-31T23:59:59.999Z",+ orderBy: null,+ };++ // Execute with optimization+ const resultWithOpt = await executeQuery(projectId, query, "v1", true);+ const resultWithoutOpt = await executeQuery(+ projectId,+ query,+ "v1",+ false,+ );++ // Results should match+ expect(resultWithOpt).toEqual(resultWithoutOpt);+ expect(resultWithOpt).toHaveLength(1);+ expect(resultWithOpt[0].startTimeMonth).toBe("2024-03");+ });+ });});diff --git a/web/src/env.mjs b/web/src/env.mjsindex 98c026c9a9..0a909530d8 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -339,6 +339,10 @@ export const env = createEnv({LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS: z.enum(["true", "false"]).default("false"),++ LANGFUSE_ENABLE_QUERY_OPTIMIZATION_SHADOW_TEST: z+ .enum(["true", "false"])+ .default("false"),},/**@@ -664,6 +668,8 @@ export const env = createEnv({process.env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS,LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS:process.env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS,+ LANGFUSE_ENABLE_QUERY_OPTIMIZATION_SHADOW_TEST:+ process.env.LANGFUSE_ENABLE_QUERY_OPTIMIZATION_SHADOW_TEST,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsindex 6f0773f012..0753428217 100644--- a/web/src/features/query/dataModel.ts+++ b/web/src/features/query/dataModel.ts@@ -429,14 +429,16 @@ export const observationsView: ViewDeclarationType = {},measures: {count: {- sql: "count(*)",+ sql: "@@AGG@@(id)",+ aggs: { agg: "count" },alias: "count",type: "integer",description: "Total number of observations.",unit: "observations",},latency: {- sql: "date_diff('millisecond', any(observations.start_time), any(observations.end_time))",+ sql: "date_diff('millisecond', @@AGG1@@(observations.start_time), @@AGG1@@(observations.end_time))",+ aggs: { agg1: "any" },alias: "latency",type: "integer",description:@@ -445,7 +447,8 @@ export const observationsView: ViewDeclarationType = {},streamingLatency: {// Return NULL if `completion_start_time` is NULL to avoid misleading latency values- sql: "if(isNull(any(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(observations.completion_start_time), any(observations.end_time)))",+ sql: "if(isNull(@@AGG1@@(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', @@AGG1@@(observations.completion_start_time), @@AGG1@@(observations.end_time)))",+ aggs: { agg1: "any" },alias: "streamingLatency",type: "integer",description:@@ -453,21 +456,24 @@ export const observationsView: ViewDeclarationType = {unit: "millisecond",},inputTokens: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(usage_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, @@AGG1@@(usage_details))))",+ aggs: { agg1: "any" },alias: "inputTokens",type: "integer",description: "Sum of input tokens consumed by the observation.",unit: "tokens",},outputTokens: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(usage_details))))",+ aggs: { agg1: "any" },alias: "outputTokens",type: "integer",description: "Sum of output tokens produced by the observation.",unit: "tokens",},totalTokens: {- sql: "sumMap(usage_details)['total']",+ sql: "@@AGG1@@(usage_details)['total']",+ aggs: { agg1: "sumMap" },alias: "totalTokens",type: "integer",description: "Sum of tokens consumed by the observation.",@@ -477,7 +483,8 @@ export const observationsView: ViewDeclarationType = {// Calculate average output tokens per second. Denominator uses seconds to align// with the `tokens/s` unit; NULL values avoided by guarding against a 0-second// duration.- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details)))) / nullIf(date_diff('second', any(observations.completion_start_time), any(observations.end_time)), 0)",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(usage_details)))) / nullIf(date_diff('second', @@AGG1@@(observations.completion_start_time), @@AGG1@@(observations.end_time)), 0)",+ aggs: { agg1: "any" },alias: "outputTokensPerSecond",type: "decimal",description:@@ -485,7 +492,8 @@ export const observationsView: ViewDeclarationType = {unit: "tokens/s",},tokensPerSecond: {- sql: "sumMap(usage_details)['total'] / date_diff('second', any(observations.start_time), any(observations.end_time))",+ sql: "@@AGG1@@(usage_details)['total'] / date_diff('second', @@AGG2@@(observations.start_time), @@AGG2@@(observations.end_time))",+ aggs: { agg1: "sumMap", agg2: "any" },alias: "tokensPerSecond",type: "decimal",description:@@ -493,21 +501,24 @@ export const observationsView: ViewDeclarationType = {unit: "tokens/s",},inputCost: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(cost_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, @@AGG1@@(cost_details))))",+ aggs: { agg1: "any" },alias: "inputCost",type: "decimal",description: "Sum of input cost incurred by the observation.",unit: "USD",},outputCost: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(cost_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(cost_details))))",+ aggs: { agg1: "any" },alias: "outputCost",type: "decimal",description: "Sum of output cost incurred by the observation.",unit: "USD",},totalCost: {- sql: "sum(total_cost)",+ sql: "@@AGG1@@(total_cost)",+ aggs: { agg1: "sum" },alias: "totalCost",type: "decimal",description: "Total cost incurred by the observation.",@@ -515,7 +526,8 @@ export const observationsView: ViewDeclarationType = {},timeToFirstToken: {// Return NULL if `completion_start_time` is NULL to represent unknown TTFT- sql: "if(isNull(any(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(observations.start_time), any(observations.completion_start_time)))",+ sql: "if(isNull(@@AGG1@@(observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', @@AGG1@@(observations.start_time), @@AGG1@@(observations.completion_start_time)))",+ aggs: { agg1: "any" },alias: "timeToFirstToken",type: "integer",description: "Time to first token for the observation.",@@ -1027,14 +1039,16 @@ export const eventsObservationsView: ViewDeclarationType = {},measures: {count: {- sql: "count(*)",+ sql: "@@AGG@@(events_observations.span_id)",+ aggs: { agg: "count" },alias: "count",type: "integer",description: "Total number of observations.",unit: "observations",},latency: {- sql: "date_diff('millisecond', any(events_observations.start_time), any(events_observations.end_time))",+ sql: "date_diff('millisecond', @@AGG1@@(events_observations.start_time), @@AGG1@@(events_observations.end_time))",+ aggs: { agg1: "any" },alias: "latency",type: "integer",description:@@ -1042,7 +1056,8 @@ export const eventsObservationsView: ViewDeclarationType = {unit: "millisecond",},streamingLatency: {- sql: "if(isNull(any(events_observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(events_observations.completion_start_time), any(events_observations.end_time)))",+ sql: "if(isNull(@@AGG1@@(events_observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', @@AGG1@@(events_observations.completion_start_time), @@AGG1@@(events_observations.end_time)))",+ aggs: { agg1: "any" },alias: "streamingLatency",type: "integer",description:@@ -1050,28 +1065,32 @@ export const eventsObservationsView: ViewDeclarationType = {unit: "millisecond",},inputTokens: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(usage_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, @@AGG1@@(usage_details))))",+ aggs: { agg1: "any" },alias: "inputTokens",type: "integer",description: "Sum of input tokens consumed by the observation.",unit: "tokens",},outputTokens: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(usage_details))))",+ aggs: { agg1: "any" },alias: "outputTokens",type: "integer",description: "Sum of output tokens produced by the observation.",unit: "tokens",},totalTokens: {- sql: "sumMap(usage_details)['total']",+ sql: "@@AGG1@@(usage_details)['total']",+ aggs: { agg1: "sumMap" },alias: "totalTokens",type: "integer",description: "Sum of tokens consumed by the observation.",unit: "tokens",},outputTokensPerSecond: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(usage_details)))) / nullIf(date_diff('second', any(events_observations.completion_start_time), any(events_observations.end_time)), 0)",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(usage_details)))) / nullIf(date_diff('second', @@AGG1@@(events_observations.completion_start_time), @@AGG1@@(events_observations.end_time)), 0)",+ aggs: { agg1: "any" },alias: "outputTokensPerSecond",type: "decimal",description:@@ -1079,7 +1098,8 @@ export const eventsObservationsView: ViewDeclarationType = {unit: "tokens/s",},tokensPerSecond: {- sql: "sumMap(usage_details)['total'] / date_diff('second', any(events_observations.start_time), any(events_observations.end_time))",+ sql: "@@AGG1@@(usage_details)['total'] / date_diff('second', @@AGG2@@(events_observations.start_time), @@AGG2@@(events_observations.end_time))",+ aggs: { agg1: "sumMap", agg2: "any" },alias: "tokensPerSecond",type: "decimal",description:@@ -1087,28 +1107,32 @@ export const eventsObservationsView: ViewDeclarationType = {unit: "tokens/s",},inputCost: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, any(cost_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, @@AGG1@@(cost_details))))",+ aggs: { agg1: "any" },alias: "inputCost",type: "decimal",description: "Sum of input cost incurred by the observation.",unit: "USD",},outputCost: {- sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, any(cost_details))))",+ sql: "arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, @@AGG1@@(cost_details))))",+ aggs: { agg1: "any" },alias: "outputCost",type: "decimal",description: "Sum of output cost incurred by the observation.",unit: "USD",},totalCost: {- sql: "sum(total_cost)",+ sql: "@@AGG1@@(total_cost)",+ aggs: { agg1: "sum" },alias: "totalCost",type: "decimal",description: "Total cost incurred by the observation.",unit: "USD",},timeToFirstToken: {- sql: "if(isNull(any(events_observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', any(events_observations.start_time), any(events_observations.completion_start_time)))",+ sql: "if(isNull(@@AGG1@@(events_observations.completion_start_time)), CAST(NULL AS Nullable(Int64)), date_diff('millisecond', @@AGG1@@(events_observations.start_time), @@AGG1@@(events_observations.completion_start_time)))",+ aggs: { agg1: "any" },alias: "timeToFirstToken",type: "integer",description: "Time to first token for the observation.",diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex c49b95bf02..d27bd7cfa1 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -32,6 +32,7 @@ type AppliedMetricType = {aggregation: z.infer<typeof metricAggregations>;alias?: string;relationTable?: string;+ aggs?: Record<string, string>;};export class QueryBuilder {@@ -118,6 +119,7 @@ export class QueryBuilder {return {...view.measures[metric.measure],aggregation: metric.aggregation,+ aggs: view.measures[metric.measure].aggs,};});}@@ -374,6 +376,39 @@ export class QueryBuilder {return relationTables;}+ private canUseSingleLevelQuery(+ appliedDimensions: AppliedDimensionType[],+ appliedMetrics: AppliedMetricType[],+ ): boolean {+ // Single-level query requires:+ // 1. All metrics have aggs configuration+ // 2. No custom aggregation functions on dimensions+ // Measures without .aggs: {} (like uniq(scores.id)) must use two-level approach+ const allMetricsHaveAggs =+ appliedMetrics.length === 0 ||+ appliedMetrics.every((m) => m.aggs !== undefined);++ // Check if any dimension has custom aggregation+ const hasCustomDimensionAgg = appliedDimensions.some(+ (d) => d.aggregationFunction !== undefined,+ );++ return allMetricsHaveAggs && !hasCustomDimensionAgg;+ }++ private substituteAggTemplates(+ sql: string,+ aggs: Record<string, string>,+ ): string {+ let result = sql;+ // Replace each @@AGGN@@ placeholder with its corresponding aggregation function+ for (const [placeholder, aggFunc] of Object.entries(aggs)) {+ const marker = `@@${placeholder.toUpperCase()}@@`;+ result = result.replaceAll(marker, aggFunc);+ }+ return result;+ }+private buildJoins(relationTables: Set<string>,view: ViewDeclarationType,@@ -506,6 +541,34 @@ export class QueryBuilder {}}+ private buildTimeDimensionSql(+ view: ViewDeclarationType,+ query: QueryType,+ wrapInAgg?: string,+ ): string {+ if (!query.timeDimension) {+ return "";+ }++ const actualTableName = this.actualTableName(view);+ const granularity =+ query.timeDimension.granularity === "auto"+ ? this.determineTimeGranularity(query.fromTimestamp, query.toTimestamp)+ : query.timeDimension.granularity;++ const timeDimensionSql = this.getTimeDimensionSql(+ `${actualTableName}.${view.timeDimension}`,+ granularity,+ );++ // Optionally wrap in aggregation function (e.g., "any" for two-level inner SELECT)+ const wrappedSql = wrapInAgg+ ? `${wrapInAgg}(${timeDimensionSql})`+ : timeDimensionSql;++ return `${wrappedSql} as time_dimension`;+ }+private buildInnerDimensionsPart(appliedDimensions: AppliedDimensionType[],query: QueryType,@@ -527,30 +590,32 @@ export class QueryBuilder {.join(",\n")},`;}- // Add time dimension if specified- if (query.timeDimension) {- const granularity =- query.timeDimension.granularity === "auto"- ? this.determineTimeGranularity(- query.fromTimestamp,- query.toTimestamp,- )- : query.timeDimension.granularity;-- const timeDimensionSql = this.getTimeDimensionSql(- `${view.name}.${view.timeDimension}`,- granularity,- );- dimensions += `any(${timeDimensionSql}) as time_dimension,`;+ // Add time dimension if specified - reuse unified builder with any() wrapper+ const timeDimensionSql = this.buildTimeDimensionSql(view, query, "any");+ if (timeDimensionSql) {+ dimensions += `${timeDimensionSql},`;}return dimensions;}private buildInnerMetricsPart(appliedMetrics: AppliedMetricType[]) {- return appliedMetrics.length > 0- ? `${appliedMetrics.map((metric) => `${metric.sql} as ${metric.alias || metric.sql}`).join(",\n")}`- : "count(*) as count";+ if (appliedMetrics.length === 0) {+ return "count(*) as count";+ }++ return appliedMetrics+ .map((metric) => {+ let sql = metric.sql;++ // For two-level queries, substitute ${aggN} with actual agg function from template+ if (metric.aggs) {+ sql = this.substituteAggTemplates(sql, metric.aggs);+ }++ return `${sql} as ${metric.alias || metric.sql}`;+ })+ .join(",\n");}private buildInnerSelect(@@ -705,6 +770,86 @@ export class QueryBuilder {${withFillClause}`;}+ private buildSingleLevelMetricsPart(+ appliedMetrics: AppliedMetricType[],+ ): string {+ if (appliedMetrics.length === 0) {+ return "count(*) as count";+ }++ return appliedMetrics+ .map((m) => {+ // For single-level: REMOVE @@AGGN@@ markers (strip template aggregations)+ let baseSql = m.sql;+ if (m.aggs) {+ for (const placeholder of Object.keys(m.aggs)) {+ const marker = `@@${placeholder.toUpperCase()}@@`;+ baseSql = baseSql.replaceAll(marker, "");+ }+ }+ // Apply user-requested aggregation to the stripped SQL+ // Important: Clear alias so translateAggregation uses the sql directly+ const aggregatedSql = this.translateAggregation({+ ...m,+ sql: baseSql,+ alias: undefined, // Force use of sql instead of alias+ });+ return `${aggregatedSql} as ${m.aggregation}_${m.alias || m.sql}`;+ })+ .join(",\n");+ }++ private buildSingleLevelDimensionsPart(+ appliedDimensions: AppliedDimensionType[],+ query: QueryType,+ view: ViewDeclarationType,+ ): string {+ let dimensionsPart = "";+ if (appliedDimensions.length > 0) {+ dimensionsPart =+ appliedDimensions+ .map((d) => `${d.sql} as ${d.alias ?? d.sql}`)+ .join(",\n") + ",\n";+ }++ // Reuse unified time dimension builder (no wrapper for single-level)+ const timeDimensionSql = this.buildTimeDimensionSql(view, query);+ if (timeDimensionSql) {+ dimensionsPart += `${timeDimensionSql},\n`;+ }++ return dimensionsPart;+ }++ private buildSingleLevelSelect(+ view: ViewDeclarationType,+ appliedDimensions: AppliedDimensionType[],+ appliedMetrics: AppliedMetricType[],+ query: QueryType,+ fromClause: string,+ groupByClause: string,+ orderByClause: string,+ withFillClause: string,+ ): string {+ // Build dimensions using dedicated helper+ const dimensionsPart = this.buildSingleLevelDimensionsPart(+ appliedDimensions,+ query,+ view,+ );++ // Build optimized metrics (strip templates, apply user aggregation)+ const metricsPart = this.buildSingleLevelMetricsPart(appliedMetrics);++ return `+ SELECT+ ${dimensionsPart}${metricsPart}+ ${fromClause}+ ${groupByClause}+ ${orderByClause}+ ${withFillClause}`;+ }+/*** Validates that the provided orderBy fields exist in the dimensions or metrics* and returns the processed orderBy array with fully qualified field names.@@ -798,7 +943,8 @@ export class QueryBuilder {/*** We want to build a ClickHouse query based on the query provided and the viewDeclaration that was selected.- * The final query should always follow this pattern:+ *+ * When enableSingleLevelOptimization is false (default), the query follows a two-level pattern:* ```* SELECT* <...dimensions>,@@ -817,10 +963,28 @@ export class QueryBuilder {* GROUP BY <...dimensions>* ORDER BY <fields with directions>* ```+ *+ * When `enableSingleLevelOptimization` is true AND `canUseSingleLevelQuery()` returns true,+ * the query uses a single-level pattern (skips high-cardinality GROUP BY):+ * ```+ * SELECT+ * <...dimensions>,+ * <...metrics.map(metric => `${metric.aggregation}(stripped ${metric.sql})`>+ * FROM <baseCte>+ * (...tableRelations.joinConditionSql)+ * WHERE <...filters>+ * GROUP BY <...dimensions>+ * ORDER BY <fields with directions>+ * ```+ *+ * Note: Template placeholders @@AGGN@@ in metric SQL are substituted with:+ * - Two-level mode: Actual aggregation from aggs config (e.g., sum, any, sumMap)+ * - Single-level mode: Stripped out, user's aggregation applied directly to raw expression*/public async build(query: QueryType,projectId: string,+ enableSingleLevelOptimization: boolean = false,): Promise<{ query: string; parameters: Record<string, unknown> }> {// Run zod validationconst parseResult = queryModel.safeParse(query);@@ -890,28 +1054,13 @@ export class QueryBuilder {// Build WHERE clause with parametersfromClause += this.buildWhereClause(filterList, parameters);- // Build inner SELECT parts- const innerDimensionsPart = this.buildInnerDimensionsPart(- appliedDimensions,- query,- view,- );- const innerMetricsPart = this.buildInnerMetricsPart(appliedMetrics);+ // Check if single-level optimization is applicable+ // Note: Relation tables are OK as long as measures have aggs configuration+ const canOptimize =+ enableSingleLevelOptimization &&+ this.canUseSingleLevelQuery(appliedDimensions, appliedMetrics);- // Build inner SELECT- const innerQuery = this.buildInnerSelect(- view,- innerDimensionsPart,- innerMetricsPart,- fromClause,- );-- // Build outer SELECT parts- const outerDimensionsPart = this.buildOuterDimensionsPart(- appliedDimensions,- !!query.timeDimension,- );- const outerMetricsPart = this.buildOuterMetricsPart(appliedMetrics);+ // Build GROUP BY clause (used by both single-level and two-level queries)const groupByClause = this.buildGroupByClause(appliedDimensions,!!query.timeDimension,@@ -937,15 +1086,54 @@ export class QueryBuilder {parameters,);- // Build final query- const sql = this.buildOuterSelect(- outerDimensionsPart,- outerMetricsPart,- innerQuery,- groupByClause,- orderByClause,- withFillClause,- );+ // Build final query - branch based on optimization+ let sql: string;+ if (canOptimize) {+ // Single-level query: Skip inner SELECT+ sql = this.buildSingleLevelSelect(+ view,+ appliedDimensions,+ appliedMetrics,+ query,+ fromClause,+ groupByClause,+ orderByClause,+ withFillClause,+ );+ } else {+ // Two-level query: Original approach+ // Build inner SELECT parts+ const innerDimensionsPart = this.buildInnerDimensionsPart(+ appliedDimensions,+ query,+ view,+ );+ const innerMetricsPart = this.buildInnerMetricsPart(appliedMetrics);++ // Build inner SELECT+ const innerQuery = this.buildInnerSelect(+ view,+ innerDimensionsPart,+ innerMetricsPart,+ fromClause,+ );++ // Build outer SELECT parts+ const outerDimensionsPart = this.buildOuterDimensionsPart(+ appliedDimensions,+ !!query.timeDimension,+ );+ const outerMetricsPart = this.buildOuterMetricsPart(appliedMetrics);++ sql = this.buildOuterSelect(+ outerDimensionsPart,+ outerMetricsPart,+ innerQuery,+ groupByClause,+ orderByClause,+ withFillClause,+ );+ }return {query: sql,diff --git a/web/src/features/query/server/queryExecutor.ts b/web/src/features/query/server/queryExecutor.tsindex e110d4b0d9..26709b2b60 100644--- a/web/src/features/query/server/queryExecutor.ts+++ b/web/src/features/query/server/queryExecutor.ts@@ -1,6 +1,65 @@-import { queryClickhouse, measureAndReturn } from "@langfuse/shared/src/server";+import {+ queryClickhouse,+ measureAndReturn,+ logger,+} from "@langfuse/shared/src/server";import { QueryBuilder } from "@/src/features/query/server/queryBuilder";import { type QueryType, type ViewVersion } from "@/src/features/query/types";+import { env } from "@/src/env.mjs";++/**+ * Compares two query results for equivalence.+ * Returns true if results match, false otherwise.+ * Optimized for performance - avoids expensive JSON.stringify on large result sets.+ */+function compareQueryResults(+ result1: Array<Record<string, unknown>>,+ result2: Array<Record<string, unknown>>,+): boolean {+ if (result1.length !== result2.length) {+ return false;+ }++ if (result1.length === 0) {+ return true;+ }++ // Get all keys from first row of each result+ const keys1 = Object.keys(result1[0]);+ const keys2 = Object.keys(result2[0]);++ // Quick check: same number of columns+ if (keys1.length !== keys2.length) {+ return false;+ }++ // Sort keys once for performance (avoid sorting on every row)+ const sortedKeys = keys1.sort();++ // Create a simple hash for each row to enable fast comparison+ const createRowHash = (row: Record<string, unknown>): string => {+ // Use a simple concatenation of key-value pairs (sorted by key for consistency)+ return sortedKeys.map((k) => `${k}:${row[k]}`).join("|");+ };++ // Build sets of row hashes+ const hashes1 = new Set(result1.map(createRowHash));+ const hashes2 = new Set(result2.map(createRowHash));++ // Compare sets+ if (hashes1.size !== hashes2.size) {+ return false;+ }++ // Check if all hashes from result1 exist in result2+ for (const hash of hashes1) {+ if (!hashes2.has(hash)) {+ return false;+ }+ }++ return true;+}/*** Execute a query using the QueryBuilder.@@ -8,68 +67,163 @@ import { type QueryType, type ViewVersion } from "@/src/features/query/types";* @param projectId - The project ID* @param query - The query configuration as defined in QueryType* @param version - The view version to use (v1 or v2), defaults to v1+ * @param enableSingleLevelOptimization - Enable single-level SELECT optimization (default: false)* @returns The query result data*/export async function executeQuery(projectId: string,query: QueryType,version: ViewVersion = "v1",+ enableSingleLevelOptimization: boolean = false,): Promise<Array<Record<string, unknown>>> {- const { query: compiledQuery, parameters } = await new QueryBuilder(- query.chartConfig,- version,- ).build(query, projectId);+ const queryBuilder = new QueryBuilder(query.chartConfig, version);- // Check if the query contains trace table references- const usesTraceTable = compiledQuery.includes("traces");+ // Build the primary query (with or without optimization based on flag)+ const { query: compiledQuery, parameters } = await queryBuilder.build(+ query,+ projectId,+ enableSingleLevelOptimization,+ );- if (!usesTraceTable) {- // No trace table placeholders, execute normally- const result = await queryClickhouse<Record<string, unknown>>({+ // Shadow testing: Build list of queries to execute in parallel+ const queriesToExecute: Array<{+ type: "regular" | "shadow";+ query: string;+ params: Record<string, unknown>;+ }> = [+ {+ type: "regular",query: compiledQuery,params: parameters,- clickhouseConfigs: {- clickhouse_settings: {- date_time_output_format: "iso",- },- },- tags: {- feature: "custom-queries",- type: query.view,- kind: "analytic",- projectId,- },- });- return result;+ },+ ];++ // Add shadow test query if optimization is OFF and shadow testing is enabled+ const shadowTestEnabled =+ env.LANGFUSE_ENABLE_QUERY_OPTIMIZATION_SHADOW_TEST === "true";++ if (!enableSingleLevelOptimization && shadowTestEnabled) {+ const { query: optimizedQuery, parameters: optimizedParams } =+ await queryBuilder.build(query, projectId, true);++ // Only run shadow test if optimization actually changed the query+ if (optimizedQuery !== compiledQuery) {+ queriesToExecute.push({+ type: "shadow",+ query: optimizedQuery,+ params: optimizedParams,+ });+ }}- // Use measureAndReturn for trace table queries- return measureAndReturn({- operationName: "executeQuery",- projectId,- input: {- query: compiledQuery,- params: parameters,- fromTimestamp: query.fromTimestamp,- tags: {- feature: "custom-queries",- type: query.view,- kind: "analytic",- projectId,- operation_name: "executeQuery",+ // Check if the query contains trace table references+ const usesTraceTable = compiledQuery.includes("traces");++ // Execute all queries in parallel+ const results = await Promise.all(+ queriesToExecute.map(+ async (+ queryToExecute,+ ): Promise<Array<Record<string, unknown>> | null> => {+ try {+ if (!usesTraceTable) {+ // No trace table placeholders, execute normally+ return await queryClickhouse<Record<string, unknown>>({+ query: queryToExecute.query,+ params: queryToExecute.params,+ clickhouseConfigs: {+ clickhouse_settings: {+ date_time_output_format: "iso",+ },+ },+ tags: {+ feature:+ queryToExecute.type === "shadow"+ ? "custom-queries-shadow-test"+ : "custom-queries",+ type: query.view,+ kind: "analytic",+ projectId,+ },+ });+ } else {+ // Use measureAndReturn for trace table queries+ return await measureAndReturn({+ operationName: "executeQuery",+ projectId,+ input: {+ query: queryToExecute.query,+ params: queryToExecute.params,+ fromTimestamp: query.fromTimestamp,+ tags: {+ feature:+ queryToExecute.type === "shadow"+ ? "custom-queries-shadow-test"+ : "custom-queries",+ type: query.view,+ kind: "analytic",+ projectId,+ operation_name: "executeQuery",+ },+ },+ fn: async (input) => {+ return queryClickhouse<Record<string, unknown>>({+ query: input.query,+ params: input.params,+ clickhouseConfigs: {+ clickhouse_settings: {+ date_time_output_format: "iso",+ },+ },+ tags: input.tags,+ });+ },+ });+ }+ } catch (error) {+ // Only log shadow test errors+ if (queryToExecute.type === "shadow") {+ logger.warn("Shadow test query failed", {+ view: query.view,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ // Re-throw errors from regular query+ throw error;+ }},- },- fn: async (input) => {- return queryClickhouse<Record<string, unknown>>({- query: input.query,- params: input.params,- clickhouseConfigs: {- clickhouse_settings: {- date_time_output_format: "iso",- },- },- tags: input.tags,+ ),+ );++ // Extract results - regularResult should never be null (would have thrown)+ const regularResult = results[0]!;+ const shadowResult = results[1] ?? null;++ // Compare shadow test results if available+ if (shadowResult !== null) {+ const resultsMatch = compareQueryResults(regularResult, shadowResult);++ if (resultsMatch) {+ // Log success (can be aggregated to track optimization coverage)+ logger.info("Shadow test: Optimization query matches", {+ view: query.view,+ version,});- },- });+ } else {+ // Log discrepancy with full details+ logger.error("Shadow test: Optimization query MISMATCH", {+ view: query.view,+ version,+ projectId,+ query: query,+ regularResultCount: regularResult.length,+ optimizedResultCount: shadowResult.length,+ regularResult: regularResult,+ optimizedResult: shadowResult,+ });+ }+ }++ return regularResult;}diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.tsindex b8a5f0c61d..818df909c0 100644--- a/web/src/features/query/types.ts+++ b/web/src/features/query/types.ts@@ -32,6 +32,7 @@ export const viewDeclaration = z.object({description: z.string().optional(),type: z.string().optional(),unit: z.string().optional(),+ aggs: z.record(z.string(), z.string()).optional(),}),),tableRelations: z.record(