🪢 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
fix: fix time dimension query to use root event timestamp (#12118)
Valery Meleshkina809478be540
diff --git a/.env.dev.example b/.env.dev.exampleindex 3544f77fbc..6e0d26281e 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -151,3 +151,5 @@ LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS=trueLANGFUSE_ENABLE_EVENTS_TABLE_FLAGS=trueLANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS=trueLANGFUSE_EXPERIMENT_INSERT_INTO_EVENTS_TABLE=true++CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE="true"diff --git a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.tsindex ba6447555b..272cb5ab5e 100644--- a/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts+++ b/web/src/__tests__/async/dashboard-v1-v2-consistency.servertest.ts@@ -484,9 +484,9 @@ describe("dashboard v1 vs v2 consistency", () => {maybe("traces by time (day granularity)", () => {it.each(["1d", "7d"] as const)(- "should have matching totals for %s window",+ "should have matching per-bucket counts for %s window",async (window) => {- await expectExactTotalCount({+ const query: QueryType = {view: "traces",dimensions: [],metrics: [{ measure: "count", aggregation: "count" }],@@ -495,7 +495,33 @@ describe("dashboard v1 vs v2 consistency", () => {orderBy: null,fromTimestamp: fromFor(window),toTimestamp,- });+ };+ const { v1, v2 } = await runBothVersions(query);++ // Total must match (existing invariant)+ const sum = (rows: Array<Record<string, unknown>>) =>+ rows.reduce((s, r) => s + Number(r.count_count), 0);+ expect(sum(v2)).toBe(sum(v1));++ // Per-bucket counts must also match exactly.+ // A mismatch here indicates traces are being assigned to wrong time+ // buckets in v2 (e.g. due to using min(start_time) across all events+ // instead of only the root event's timestamp).+ const v1Map = toMap(+ v1.filter((r) => Number(r.count_count) > 0),+ "time_dimension",+ );+ const v2Map = toMap(+ v2.filter((r) => Number(r.count_count) > 0),+ "time_dimension",+ );++ expect(v2Map.size).toBe(v1Map.size);+ for (const [ts, v1Row] of v1Map) {+ const v2Row = v2Map.get(ts);+ expect(v2Row).toBeDefined();+ expect(Number(v2Row!.count_count)).toBe(Number(v1Row.count_count));+ }},);});@@ -547,10 +573,6 @@ describe("dashboard v1 vs v2 consistency", () => {const v2Row = v2Map.get(userId)!;expect(Number(v1Row.count_count)).toBe(Number(v2Row.count_count));}-- // Note: totalCost may differ between v1 (observations.total_cost column)- // and v2 (events_core cost_details['total'] ALIAS) due to how costs are- // stored/computed in the two tables. This is a known data consistency gap.});it("should have overlapping users with counts within 3x for 1d window", async () => {diff --git a/web/src/features/query/dataModel.ts b/web/src/features/query/dataModel.tsindex d5dddded35..3b4ec5b553 100644--- a/web/src/features/query/dataModel.ts+++ b/web/src/features/query/dataModel.ts@@ -305,7 +305,6 @@ export const eventsTracesView: ViewDeclarationType = {},segments: [],timeDimension: "start_time",- timeDimensionAggregation: "min",rootEventCondition: {column: "trace_id",condition: "parent_span_id = ''",diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex 695d171313..3ee289272e 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -194,6 +194,18 @@ export class QueryBuilder {return view.baseCte.split(" ")[0];}+ private tableAlias(view: ViewDeclarationType): string {+ // Return the alias from baseCte if present, otherwise the table name.+ // e.g., "events_core events_traces" -> "events_traces"+ // "traces FINAL" -> "traces" (FINAL is a modifier, not an alias)+ const parts = view.baseCte.split(/\s+/);+ const clickhouseModifiers = new Set(["FINAL", "SAMPLE", "PREWHERE"]);+ if (parts.length >= 2 && !clickhouseModifiers.has(parts[1].toUpperCase())) {+ return parts[1];+ }+ return parts[0];+ }+private mapFilters(filters: z.infer<typeof queryModel>["filters"],view: ViewDeclarationType,@@ -570,11 +582,20 @@ export class QueryBuilder {granularity,);- // Optionally wrap in aggregation function (e.g., "any" for two-level inner SELECT)- const agg = wrapInAgg- ? (view.timeDimensionAggregation ?? wrapInAgg)- : undefined;- const wrappedSql = agg ? `${agg}(${timeDimensionSql})` : timeDimensionSql;+ // Optionally wrap in aggregation function (e.g., "any" for two-level inner SELECT).+ // When the view has a rootEventCondition, use anyIf with that condition so that+ // only the root event's timestamp is used for time bucketing (not observations).+ // The condition column is prefixed with the table alias to avoid ambiguity in+ // future views that may involve JOINs.+ let wrappedSql: string;+ if (wrapInAgg && view.rootEventCondition) {+ const alias = this.tableAlias(view);+ wrappedSql = `anyIf(${timeDimensionSql}, ${alias}.${view.rootEventCondition.condition})`;+ } else if (wrapInAgg) {+ wrappedSql = `${wrapInAgg}(${timeDimensionSql})`;+ } else {+ wrappedSql = timeDimensionSql;+ }return `${wrappedSql} as time_dimension`;}diff --git a/web/src/features/query/types.ts b/web/src/features/query/types.tsindex abef1f04de..a4522082d9 100644--- a/web/src/features/query/types.ts+++ b/web/src/features/query/types.ts@@ -48,7 +48,6 @@ export const viewDeclaration = z.object({// Segments are used to apply "constant" filters to the query. For example, if we only want one type of observations.segments: z.array(singleFilter),timeDimension: z.string(),- timeDimensionAggregation: z.string().optional(),// When set, adds a subquery filter to restrict rows to those whose "root event"// (matching the condition) has timeDimension in the query window.rootEventCondition: z