🪢 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(experiments): sum item cost across full observation subtree (#15189)
Tobias Wochingeracc1ae54784e
diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex ebf80677b0..5846197fce 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -390,7 +390,14 @@ export const eventsExperimentsAggregation = (params: {.whereRaw("e.experiment_id != ''");};-export const eventsExperimentsRootSpans = (params: {+/**+ * Scopes events to a project/experiment/item-id set, without narrowing to+ * root-span rows. Use this (instead of eventsExperimentsRootSpans) when a+ * query needs to see every observation for an item - e.g. to aggregate cost+ * across an item's full subtree - and will pick the root row itself via+ * ORDER BY / LIMIT BY rather than WHERE, so aggregates see sibling rows too.+ */+export const eventsExperimentsForItems = (params: {projectId: string;experimentIds?: string[];experimentItemIds?: string[];@@ -398,18 +405,25 @@ export const eventsExperimentsRootSpans = (params: {eventsExperiments({projectId: params.projectId,experimentIds: params.experimentIds,- })- .whereRaw("e.experiment_item_root_span_id = e.span_id")- .when(- Boolean(params.experimentItemIds && params.experimentItemIds.length > 0),- (b) =>- b.whereRaw(- "e.experiment_item_id IN ({experimentItemIds: Array(String)})",- {- experimentItemIds: params.experimentItemIds,- },- ),- );+ }).when(+ Boolean(params.experimentItemIds && params.experimentItemIds.length > 0),+ (b) =>+ b.whereRaw(+ "e.experiment_item_id IN ({experimentItemIds: Array(String)})",+ {+ experimentItemIds: params.experimentItemIds,+ },+ ),+ );++export const eventsExperimentsRootSpans = (params: {+ projectId: string;+ experimentIds?: string[];+ experimentItemIds?: string[];+}): EventsQueryBuilder =>+ eventsExperimentsForItems(params).whereRaw(+ "e.experiment_item_root_span_id = e.span_id",+ );/*** Session-level scores aggregation CTE.diff --git a/packages/shared/src/server/repositories/experiments.ts b/packages/shared/src/server/repositories/experiments.tsindex 35a95833a3..d9879fd280 100644--- a/packages/shared/src/server/repositories/experiments.ts+++ b/packages/shared/src/server/repositories/experiments.ts@@ -2,6 +2,7 @@ import { env } from "../../env";import { type ScoreSourceType } from "../../domain";import { type OrderByState } from "../../interfaces/orderBy";import { type FilterState } from "../../types";+import { convertDateToClickhouseDateTime } from "../clickhouse/client";import { measureAndReturn } from "../clickhouse/measureAndReturn";import {FilterList,@@ -18,6 +19,7 @@ import {buildScoreRowsCTE,buildScoresCTE,eventsExperimentsRootSpans,+ eventsExperimentsForItems,eventsExperiments,eventsExperimentsAggregation,eventsScoresAggregation,@@ -975,7 +977,10 @@ const getExperimentItemsFromEventsGeneric = (params: {const queryBuilder = new EventsAggQueryBuilder({projectId,groupByColumn: "e.experiment_item_id",- selectExpression: "e.experiment_item_id as item_id",+ // min(start_time) is the item's root start_time (WHERE below restricts+ // to root rows), used as a coarse partition-prune lower bound for Query 2.+ selectExpression:+ "e.experiment_item_id as item_id, min(e.start_time) as start_time",}).whereRaw("e.span_id = e.experiment_item_root_span_id").when(hasScoreFilters, (b) =>@@ -1054,7 +1059,10 @@ export const getExperimentItemsFromEvents = async (offset,});- const itemIdsResult = await queryClickhouse<{ item_id: string }>({+ const itemIdsResult = await queryClickhouse<{+ item_id: string;+ start_time: string;+ }>({query: itemIdsQuery,params: itemIdsParams,tags: { projectId },@@ -1072,24 +1080,53 @@ export const getExperimentItemsFromEvents = async (...compExperimentIds,];+ // Earliest root start_time among the qualified items - a coarse partition+ // prune for Query 2. Children always start at or after their own root, so+ // this bound can't exclude a legitimate descendant.+ const minStartTime = new Date(+ Math.min(+ ...itemIdsResult.map((r) =>+ parseClickhouseUTCDateTimeFormat(r.start_time).getTime(),+ ),+ ),+ );+// ========== QUERY 2: Fetch data for ALL experiments ==========- const queryBuilderData = eventsExperimentsRootSpans({+ // total_cost is summed across the item's full observation subtree via a+ // window function - the root span itself usually carries no cost of its+ // own, so reading e.total_cost directly would just return 0. WHERE only+ // scopes to project/experiment/item; root-row selection happens in+ // ORDER BY/LIMIT BY below, so the window function still sees sibling rows.+ // The partition includes trace_id so items with multiple repetitions+ // (until we model them properly, LFE-8965) sum only the selected+ // iteration's own subtree, not every repetition's cost combined.+ const queryBuilderData = eventsExperimentsForItems({projectId,experimentItemIds: itemIds,experimentIds: allExperimentIds,})+ .whereRaw("e.start_time >= {itemsMinStartTime: DateTime64(3)}", {+ itemsMinStartTime: convertDateToClickhouseDateTime(minStartTime),+ }).selectRaw("e.experiment_item_id as item_id","e.experiment_id as experiment_id","e.level as level","e.start_time as start_time",- "e.total_cost as total_cost",+ "sum(e.total_cost) OVER (PARTITION BY e.experiment_item_id, e.experiment_id, e.trace_id) as total_cost","if(isNull(e.end_time), NULL, date_diff('millisecond', e.start_time, e.end_time)) as latency_ms","e.span_id as observation_id","e.trace_id as trace_id",)- // We must deterministically return the latest row for each experiment_item_id, experiment_id pair until we model repetitions (LFE-8965)- .orderByColumns([{ column: "e.start_time", direction: "DESC" }])+ // We must deterministically return the latest row for each experiment_item_id, experiment_id pair until we model repetitions (LFE-8965).+ // Uses raw orderBy() rather than orderByColumns(), which auto-prepends a+ // toStartOfMinute(start_time) primary-key-read-order prefix whenever a+ // start_time entry is present - that prefix would outrank the root-flag+ // tiebreak below whenever a child observation starts in a later minute+ // bucket than its root, causing LIMIT BY to keep the child row instead.+ .orderBy(+ "ORDER BY (e.span_id = e.experiment_item_root_span_id) DESC, e.start_time DESC",+ ).limitBy("e.experiment_item_id, e.experiment_id");const { query: dataQuery, params: dataParams } =diff --git a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.tsindex 29327489f7..e71d31cc54 100644--- a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts@@ -5,6 +5,7 @@ import {getExperimentItemsFromEvents,getExperimentItemsCountFromEvents,getExperimentItemsBatchIO,+ getExperimentMetricsFromEvents,createTraceScore,type EventRecordInsertType,} from "@langfuse/shared/src/server";@@ -1161,6 +1162,203 @@ describe("Clickhouse Experiment Items Repository Test", () => {});});+ maybe("getExperimentItemsFromEvents - Cost Aggregation", () => {+ it("should sum cost across each item's full observation subtree, matching the independently-computed experiment-level aggregate", async () => {+ // GIVEN: 3 items with different cost distributions across their trees -+ // cost only on a child (the common v4-events bug shape: wrapper/root+ // spans are cost-free, cost lives on nested generations), cost split+ // root/child, and cost only on the root (no children). Root/child start+ // times straddle a clock-minute boundary so this also covers the+ // orderByColumns() primary-key-prefix pitfall (a child starting in a+ // later minute bucket than its root must not outrank the root).+ const expId = randomUUID();+ const datasetId = randomUUID();+ const minuteBoundaryMs =+ Math.ceil(Date.now() / 60_000) * 60_000 + 5 * 60_000; // a future, clean minute boundary+ const now = (minuteBoundaryMs - 500) * 1000; // root: just before the boundary (microseconds)+ const childOffsetMicros = 2_500_000; // child: 2.5s later, in the next minute bucket++ const makeItemEvents = (rootCost: number, childCost: number | null) => {+ const itemId = randomUUID();+ const traceId = randomUUID();+ const rootId = randomUUID();++ const events = [+ createExperimentEvent({+ project_id: projectId,+ trace_id: traceId,+ span_id: rootId,+ parent_span_id: null,+ experimentId: expId,+ experimentName: "cost-consistency-exp",+ datasetId,+ itemId,+ experimentItemRootSpanId: rootId,+ start_time: now,+ cost_details: { input: 0, output: 0, total: rootCost },+ provided_cost_details: { input: 0, output: 0, total: rootCost },+ }),+ ];++ if (childCost !== null) {+ events.push(+ createExperimentEvent({+ project_id: projectId,+ trace_id: traceId,+ span_id: randomUUID(),+ parent_span_id: rootId,+ experimentId: expId,+ experimentName: "cost-consistency-exp",+ datasetId,+ itemId,+ experimentItemRootSpanId: rootId,+ start_time: now + childOffsetMicros,+ cost_details: { input: 0, output: 0, total: childCost },+ provided_cost_details: { input: 0, output: 0, total: childCost },+ }),+ );+ }++ return { itemId, traceId, rootId, events };+ };++ const bugShapeItem = makeItemEvents(0, 300); // cost only on child+ const splitItem = makeItemEvents(50, 100); // cost split across root and child+ const rootOnlyItem = makeItemEvents(75, null); // no children, cost on root only++ await createEventsCh([+ ...bugShapeItem.events,+ ...splitItem.events,+ ...rootOnlyItem.events,+ ]);++ // WHEN+ const items = await getExperimentItemsFromEvents({+ projectId,+ baseExperimentId: expId,+ compExperimentIds: [],+ filterByExperiment: [],+ limit: 10,+ offset: 0,+ });++ // getExperimentMetricsFromEvents computes the experiment total via a+ // plain SUM(e.total_cost) over every row (event-query-builder.ts:1922)+ // - unrelated to the per-item root-span selection logic under test, so+ // it's a good independent cross-check.+ const [experimentMetrics] = await getExperimentMetricsFromEvents({+ projectId,+ experimentIds: [expId],+ });++ // THEN: the bug-shape item's cost is the sum of root (0) + child (300),+ // still returned as the root span's own identity (observationId,+ // traceId) despite the child starting in a later minute bucket; and the+ // sum of all per-item costs equals the independently-computed+ // experiment total.+ expect(items).toHaveLength(3);++ const bugShapeResult = items.find(+ (item) => item.itemId === bugShapeItem.itemId,+ );+ expect(bugShapeResult?.experiments).toHaveLength(1);+ expect(bugShapeResult?.experiments[0].totalCost).toBe(300);+ expect(bugShapeResult?.experiments[0].observationId).toBe(+ bugShapeItem.rootId,+ );+ expect(bugShapeResult?.experiments[0].traceId).toBe(bugShapeItem.traceId);++ const summedItemCost = items.reduce(+ (sum, item) => sum + (item.experiments[0]?.totalCost ?? 0),+ 0,+ );++ expect(experimentMetrics.totalCost).toBe(525);+ expect(summedItemCost).toBeCloseTo(experimentMetrics.totalCost!, 6);+ });++ it("should scope cost to the selected (latest) iteration, not sum across an item's repetitions", async () => {+ // GIVEN: one item run 3 times (repetitions/iterations aren't modeled+ // yet - LFE-8965 - so each iteration is its own trace sharing the same+ // experiment_item_id/experiment_id). Each iteration costs a different+ // amount so a wrong (unscoped) sum is easy to distinguish from the+ // correct, iteration-scoped one.+ const baselineExpId = randomUUID();+ const datasetId = randomUUID();+ const itemId = randomUUID();+ const now = Date.now() * 1000;++ const makeIteration = (cost: number, startOffsetMs: number) => {+ const traceId = randomUUID();+ const rootId = randomUUID();+ const childId = randomUUID();++ return {+ traceId,+ rootId,+ events: [+ createExperimentEvent({+ project_id: projectId,+ trace_id: traceId,+ span_id: rootId,+ parent_span_id: null,+ experimentId: baselineExpId,+ experimentName: "baseline-exp",+ datasetId,+ itemId,+ experimentItemRootSpanId: rootId,+ start_time: now + startOffsetMs * 1000,+ cost_details: { input: 0, output: 0, total: 0 },+ provided_cost_details: { input: 0, output: 0, total: 0 },+ }),+ createExperimentEvent({+ project_id: projectId,+ trace_id: traceId,+ span_id: childId,+ parent_span_id: rootId,+ experimentId: baselineExpId,+ experimentName: "baseline-exp",+ datasetId,+ itemId,+ experimentItemRootSpanId: rootId,+ start_time: now + startOffsetMs * 1000 + 500,+ cost_details: { input: 0, output: 0, total: cost },+ provided_cost_details: { input: 0, output: 0, total: cost },+ }),+ ],+ };+ };++ const iteration1 = makeIteration(10, 0); // oldest+ const iteration2 = makeIteration(20, 1000);+ const iteration3 = makeIteration(30, 2000); // latest++ await createEventsCh([+ ...iteration1.events,+ ...iteration2.events,+ ...iteration3.events,+ ]);++ // WHEN+ const result = await getExperimentItemsFromEvents({+ projectId,+ baseExperimentId: baselineExpId,+ compExperimentIds: [],+ filterByExperiment: [],+ limit: 10,+ offset: 0,+ });++ // THEN: still a single row (latest iteration), and its cost is that+ // iteration's own (30), not the sum across all iterations (60).+ expect(result).toHaveLength(1);+ expect(result[0].experiments).toHaveLength(1);+ expect(result[0].experiments[0].traceId).toBe(iteration3.traceId);+ expect(result[0].experiments[0].observationId).toBe(iteration3.rootId);+ expect(result[0].experiments[0].totalCost).toBe(30);+ });+ });+maybe("getExperimentItemsFromEvents - Item Visibility", () => {it("should respect requireBaselinePresence config", async () => {// GIVEN: Two items