Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(experiment): support observation level total cost display for single experiment (#10073)

marliessophie3bb9329ae95d
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 17ea9c75fa..ae9c83c35e 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1356,6 +1356,73 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (
}));
};
+/**
+ * Tuple type for observation data from ClickHouse groupArray
+ */
+export type ObservationTuple = [
+ id: string,
+ parentObservationId: string | null,
+ totalCost: string,
+ inputCost: string,
+ outputCost: string,
+ latencyMs: number,
+];
+
+/**
+ * Get observations grouped by trace ID with cost and latency data
+ *
+ * This is a pure data-fetching function that returns observations organized by trace.
+ * For business logic like recursive cost calculations, use the utility functions
+ * in the utils layer.
+ */
+export const getObservationsGroupedByTraceId = async (
+ projectId: string,
+ traceIds: string[],
+ timestamp?: Date,
+): Promise<Map<string, ObservationTuple[]>> => {
+ if (traceIds.length === 0) return new Map();
+
+ const query = `
+ SELECT
+ trace_id,
+ groupArray((
+ id,
+ parent_observation_id,
+ cost_details['total'],
+ cost_details['input'],
+ cost_details['output'],
+ dateDiff('millisecond', start_time, end_time)
+ )) AS observations
+ FROM observations FINAL
+ WHERE project_id = {projectId: String}
+ AND trace_id IN ({traceIds: Array(String)})
+ ${timestamp ? `AND start_time >= {timestamp: DateTime64(3)}` : ""}
+ GROUP BY trace_id
+ `;
+
+ const groupedObservations = await queryClickhouse<{
+ trace_id: string;
+ observations: ObservationTuple[];
+ }>({
+ query,
+ params: {
+ projectId,
+ traceIds,
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ kind: "analytic",
+ projectId,
+ },
+ });
+
+ return new Map(groupedObservations.map((g) => [g.trace_id, g.observations]));
+};
+
export const getObservationCountsByProjectInCreationInterval = async ({
start,
end,
diff --git a/web/src/__tests__/async/dataset-service.servertest.ts b/web/src/__tests__/async/dataset-service.servertest.ts
index 27c6dbe0c9..d7474049c2 100644
--- a/web/src/__tests__/async/dataset-service.servertest.ts
+++ b/web/src/__tests__/async/dataset-service.servertest.ts
@@ -1383,16 +1383,45 @@ describe("Fetch datasets for UI presentation", () => {
await createTracesCh(traces);
// Create observations for some traces (mix of trace-level and observation-level linkage)
+ const parentObsId = v4();
+ const childObs1Id = v4();
+ const childObs2Id = v4();
+
const observations = [
- // First two traces have observations (observation-level linkage)
+ // First trace: parent observation with 2 children
createObservation({
+ id: parentObsId,
trace_id: traceIds[0],
project_id: projectId,
type: "GENERATION",
- name: "generation-1",
+ name: "parent-generation",
+ parent_observation_id: null,
start_time: new Date().getTime() - 3500,
end_time: new Date().getTime() - 2500,
metadata: { model: "gpt-4" },
+ cost_details: { total: 0 }, // Parent has no direct cost
+ }),
+ createObservation({
+ id: childObs1Id,
+ trace_id: traceIds[0],
+ project_id: projectId,
+ type: "GENERATION",
+ name: "child-generation-1",
+ parent_observation_id: parentObsId,
+ start_time: new Date().getTime() - 3400,
+ end_time: new Date().getTime() - 3000,
+ cost_details: { total: 0.005 }, // Child 1 cost
+ }),
+ createObservation({
+ id: childObs2Id,
+ trace_id: traceIds[0],
+ project_id: projectId,
+ type: "GENERATION",
+ name: "child-generation-2",
+ parent_observation_id: parentObsId,
+ start_time: new Date().getTime() - 3000,
+ end_time: new Date().getTime() - 2600,
+ cost_details: { total: 0.008765 }, // Child 2 cost (total = 0.013765)
}),
createObservation({
trace_id: traceIds[1],
@@ -1426,7 +1455,7 @@ describe("Fetch datasets for UI presentation", () => {
dataset_run_id: run1Id,
dataset_item_id: itemIds[0],
trace_id: traceIds[0],
- observation_id: observations[0].id, // Observation-level linkage
+ observation_id: parentObsId, // Link to parent observation (has children)
project_id: projectId,
dataset_id: datasetId,
dataset_run_name: "run-1",
@@ -1628,6 +1657,10 @@ describe("Fetch datasets for UI presentation", () => {
expect(item0Run1?.observation?.latency).toBeDefined();
expect(typeof item0Run1?.observation?.latency).toBe("number");
expect(item0Run1?.observation?.calculatedTotalCost).toBeDefined();
+ // Should calculate recursive cost (parent + 2 children: 0 + 0.005 + 0.008765 = 0.013765)
+ expect(
+ item0Run1?.observation?.calculatedTotalCost?.toNumber(),
+ ).toBeCloseTo(0.013765, 6);
// Should have trace data
expect(item0Run1?.trace).toBeDefined();
diff --git a/web/src/features/datasets/lib/costCalculations.ts b/web/src/features/datasets/lib/costCalculations.ts
new file mode 100644
index 0000000000..60614ea67f
--- /dev/null
+++ b/web/src/features/datasets/lib/costCalculations.ts
@@ -0,0 +1,110 @@
+import Decimal from "decimal.js";
+
+/**
+ * Shared cost calculation utilities
+ */
+
+export type ObservationCostData = {
+ id: string;
+ parentObservationId?: string | null;
+ totalCost?: number | string | Decimal | null;
+ inputCost?: number | string | Decimal | null;
+ outputCost?: number | string | Decimal | null;
+};
+
+/**
+ * Find all descendants of a root observation using BFS traversal
+ */
+export const findObservationDescendants = <T extends ObservationCostData>(
+ rootObsId: string,
+ allObservations: T[],
+): T[] => {
+ // Build lookup structures for efficient traversal
+ const childrenByParentId = new Map<string, T[]>();
+ const observationById = new Map<string, T>();
+
+ for (const obs of allObservations) {
+ observationById.set(obs.id, obs);
+ if (obs.parentObservationId) {
+ if (!childrenByParentId.has(obs.parentObservationId)) {
+ childrenByParentId.set(obs.parentObservationId, []);
+ }
+ childrenByParentId.get(obs.parentObservationId)!.push(obs);
+ }
+ }
+
+ // BFS traversal starting from root
+ const result: T[] = [];
+ const visited = new Set<string>();
+ const queue = [rootObsId];
+
+ while (queue.length > 0) {
+ const currentId = queue.shift()!;
+ if (visited.has(currentId)) continue;
+
+ visited.add(currentId);
+ const currentObs = observationById.get(currentId);
+ if (currentObs) {
+ result.push(currentObs);
+ }
+
+ // Add unvisited children to queue
+ const children = childrenByParentId.get(currentId) ?? [];
+ for (const child of children) {
+ if (!visited.has(child.id)) {
+ queue.push(child.id);
+ }
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Sum costs for a list of observations
+ */
+export const sumObservationCosts = (
+ observations: ObservationCostData[],
+): Decimal | undefined => {
+ return observations.reduce<Decimal | undefined>((prev, curr) => {
+ const totalCost = curr.totalCost ? new Decimal(curr.totalCost) : undefined;
+ const inputCost = curr.inputCost ? new Decimal(curr.inputCost) : undefined;
+ const outputCost = curr.outputCost
+ ? new Decimal(curr.outputCost)
+ : undefined;
+
+ // No cost data - skip
+ if (!totalCost && !inputCost && !outputCost) return prev;
+
+ // Prefer total cost
+ if (totalCost && !totalCost.isZero()) {
+ return prev ? prev.plus(totalCost) : totalCost;
+ }
+
+ // Fallback to input + output
+ if (inputCost || outputCost) {
+ const input = inputCost || new Decimal(0);
+ const output = outputCost || new Decimal(0);
+ const combinedCost = input.plus(output);
+
+ if (combinedCost.isZero()) {
+ return prev;
+ }
+
+ return prev ? prev.plus(combinedCost) : combinedCost;
+ }
+
+ return prev;
+ }, undefined);
+};
+
+/**
+ * Calculate recursive total cost for an observation and all its children
+ */
+export const calculateRecursiveCost = (
+ rootObsId: string,
+ allObservations: ObservationCostData[],
+): Decimal | undefined => {
+ const descendants = findObservationDescendants(rootObsId, allObservations);
+ return sumObservationCosts(descendants);
+};
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index e336f0e2c0..953f678ec2 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -13,8 +13,8 @@ import {
import { z } from "zod/v4";
import {
type EnrichedDatasetRunItem,
- getLatencyAndTotalCostForObservations,
getLatencyAndTotalCostForObservationsByTraces,
+ getObservationsGroupedByTraceId,
getScoresForTraces,
tableColumnsToSqlFilterAndPrefix,
traceException,
@@ -22,6 +22,7 @@ import {
import Decimal from "decimal.js";
import { groupBy } from "lodash";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
+import { calculateRecursiveMetricsForRunItems } from "./utils";
export const datasetRunsTableSchema = z.object({
projectId: z.string(),
@@ -204,29 +205,38 @@ export const getRunItemsByRunIdOrItemId = async <WithIO extends boolean = true>(
const filterTimestamp = minTimestamp
? new Date(minTimestamp.getTime() - 24 * 60 * 60 * 1000)
: undefined;
- const [traceScores, observationAggregates, traceAggregate] =
+ const traceIds = runItems.map((ri) => ri.traceId);
+ const observationLevelRunItems = runItems.filter(
+ (ri) => ri.observationId !== null,
+ );
+
+ const [traceScores, observationsByTraceId, traceAggregate] =
await Promise.all([
getScoresForTraces({
projectId,
- traceIds: runItems.map((ri) => ri.traceId),
+ traceIds,
timestamp: filterTimestamp,
includeHasMetadata: true,
excludeMetadata: true,
}),
- getLatencyAndTotalCostForObservations(
+ getObservationsGroupedByTraceId(
projectId,
- runItems
- .filter((ri) => ri.observationId !== null)
- .map((ri) => ri.observationId) as string[],
+ observationLevelRunItems.map((ri) => ri.traceId),
filterTimestamp,
),
getLatencyAndTotalCostForObservationsByTraces(
projectId,
- runItems.map((ri) => ri.traceId),
+ traceIds,
filterTimestamp,
),
]);
+ // Calculate recursive metrics for observation-level run items
+ const observationAggregates = calculateRecursiveMetricsForRunItems<WithIO>(
+ observationLevelRunItems,
+ observationsByTraceId,
+ );
+
const validatedTraceScores = filterAndValidateDbScoreList({
scores: traceScores,
includeHasMetadata: true,
diff --git a/web/src/features/datasets/server/utils.ts b/web/src/features/datasets/server/utils.ts
new file mode 100644
index 0000000000..b8d485208b
--- /dev/null
+++ b/web/src/features/datasets/server/utils.ts
@@ -0,0 +1,65 @@
+import { type DatasetRunItemDomain } from "@langfuse/shared";
+import { calculateRecursiveCost } from "../lib/costCalculations";
+import { type ObservationTuple } from "@langfuse/shared/src/server";
+
+// Helpers to extract fields from ObservationTuple
+const getObservationId = (obs: ObservationTuple) => obs[0];
+const getLatencyMs = (obs: ObservationTuple) => obs[5];
+const toCostInput = (obs: ObservationTuple) => ({
+ id: obs[0],
+ parentObservationId: obs[1],
+ totalCost: obs[2],
+ inputCost: obs[3],
+ outputCost: obs[4],
+});
+
+/**
+ * Calculate recursive metrics (cost and latency) for dataset run items
+ *
+ * This function processes observations grouped by trace and calculates:
+ * - Recursive total cost for each observation (includes children)
+ * - Latency for each observation
+ *
+ * @param runItems - Dataset run items to calculate metrics for
+ * @param observationsByTraceId - Map of trace IDs to their observations (from getObservationsGroupedByTraceId)
+ * @returns Array of metrics with id, totalCost, and latency for each run item
+ */
+export const calculateRecursiveMetricsForRunItems = <
+ WithIO extends boolean = true,
+>(
+ runItems: DatasetRunItemDomain<WithIO>[],
+ observationsByTraceId: Map<string, ObservationTuple[]>,
+): Array<{ id: string; totalCost: number; latency: number }> => {
+ const calculatedCosts = new Map<string, number>();
+ const latencies = new Map<string, number>();
+
+ const observationLevelRunItems = runItems.filter((ri) => !!ri.observationId);
+
+ for (const runItem of observationLevelRunItems) {
+ const observations = observationsByTraceId.get(runItem.traceId);
+ if (observations?.length) {
+ const observationId = runItem.observationId!;
+
+ // Find target observation and extract latency
+ const targetObs = observations.find(
+ (obs) => getObservationId(obs) === observationId,
+ );
+ if (targetObs) {
+ latencies.set(observationId, Number(getLatencyMs(targetObs)) / 1000);
+ }
+
+ // Calculate recursive cost
+ const cost = calculateRecursiveCost(
+ observationId,
+ observations.map(toCostInput),
+ );
+ calculatedCosts.set(observationId, cost?.toNumber() ?? 0);
+ }
+ }
+
+ return observationLevelRunItems.map((r) => ({
+ id: r.observationId!,
+ totalCost: calculatedCosts.get(r.observationId!) ?? 0,
+ latency: latencies.get(r.observationId!) ?? 0,
+ }));
+};