Skip to content

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

chore: migrate remaining analytics and export queries to traces AMTs (#8451)

Steffen Schmitz1d69cbd41bc6
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 6ea184e80d..17daccedc8 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1508,6 +1508,15 @@ export const getGenerationsForPostHog = async function* (
minTimestamp: Date,
maxTimestamp: Date,
) {
+ // Determine which trace table to use based on experiment flag
+ const useAMT = env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true";
+ // Subtract 7d from minTimestamp to account for shift in query
+ const traceTable = useAMT
+ ? getTimeframesTracesAMT(
+ new Date(minTimestamp.getTime() - 7 * 24 * 60 * 60 * 1000),
+ )
+ : "traces";
+
const query = `
SELECT
o.name as name,
@@ -1532,7 +1541,7 @@ export const getGenerationsForPostHog = async function* (
t.tags as trace_tags,
t.metadata['$posthog_session_id'] as posthog_session_id
FROM observations o FINAL
- LEFT JOIN traces t FINAL ON o.trace_id = t.id AND o.project_id = t.project_id
+ LEFT JOIN ${traceTable} t FINAL ON o.trace_id = t.id AND o.project_id = t.project_id
WHERE o.project_id = {projectId: String}
AND t.project_id = {projectId: String}
AND o.start_time >= {minTimestamp: DateTime64(3)}
@@ -1554,6 +1563,7 @@ export const getGenerationsForPostHog = async function* (
type: "observation",
kind: "analytic",
projectId,
+ experiment_amt: useAMT ? "new" : "original",
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 3e4a1c4041..68ffec3635 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -33,6 +33,7 @@ import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
import { prisma } from "../../db";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
+import { getTimeframesTracesAMT } from "./traces";
export const searchExistingAnnotationScore = async (
projectId: string,
@@ -1152,7 +1153,7 @@ export const getNumericScoreHistogram = async (
const query = `
select s.value
from scores s
- ${traceFilter ? `LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id` : ""}
+ ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND t.project_id = s.project_id` : ""}
WHERE s.project_id = {projectId: String}
${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
@@ -1161,18 +1162,45 @@ export const getNumericScoreHistogram = async (
${limit !== undefined ? `limit {limit: Int32}` : ""}
`;
- return queryClickhouse<{ value: number }>({
- query,
- params: {
- projectId,
- limit,
- ...(chFilterRes ? chFilterRes.params : {}),
+ // Extract timestamp from filter for AMT table selection
+ const timestampFilter = chFilter.find(
+ (f) => f.clickhouseTable === "traces" && f.field === "timestamp",
+ ) as TimeFilter | undefined;
+ const timestamp = timestampFilter?.value;
+
+ return measureAndReturn({
+ operationName: "getNumericScoreHistogram",
+ projectId,
+ minStartTime: timestamp,
+ input: {
+ params: {
+ projectId,
+ limit,
+ ...(chFilterRes ? chFilterRes.params : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "score",
+ kind: "analytic",
+ projectId,
+ operation_name: "getNumericScoreHistogram",
+ },
+ timestamp,
},
- tags: {
- feature: "tracing",
- type: "score",
- kind: "analytic",
- projectId,
+ existingExecution: async (input) => {
+ return queryClickhouse<{ value: number }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "original" },
+ });
+ },
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(input.timestamp);
+ return queryClickhouse<{ value: number }>({
+ query: query.replace("__TRACE_TABLE__", traceAmt),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "new" },
+ });
},
});
};
@@ -1399,6 +1427,15 @@ export const getScoresForPostHog = async function* (
minTimestamp: Date,
maxTimestamp: Date,
) {
+ // Determine which trace table to use based on experiment flag
+ const useAMT = env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true";
+ // Subtract 7d from minTimestamp to account for shift in query
+ const traceTable = useAMT
+ ? getTimeframesTracesAMT(
+ new Date(minTimestamp.getTime() - 7 * 24 * 60 * 60 * 1000),
+ )
+ : "traces";
+
const query = ` SELECT
s.id as id,
s.timestamp as timestamp,
@@ -1417,7 +1454,7 @@ export const getScoresForPostHog = async function* (
s.metadata as metadata,
t.metadata['$posthog_session_id'] as posthog_session_id
FROM scores s FINAL
- LEFT JOIN traces t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id
+ LEFT JOIN ${traceTable} t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id
WHERE s.project_id = {projectId: String}
AND t.project_id = {projectId: String}
AND s.timestamp >= {minTimestamp: DateTime64(3)}
@@ -1438,6 +1475,7 @@ export const getScoresForPostHog = async function* (
type: "score",
kind: "analytic",
projectId,
+ experiment_amt: useAMT ? "new" : "original",
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index bd1d1fd845..0c44d02fd5 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1736,6 +1736,10 @@ export const getTracesForBlobStorageExport = function (
minTimestamp: Date,
maxTimestamp: Date,
) {
+ // Determine which trace table to use based on experiment flag
+ const useAMT = env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true";
+ const traceTable = useAMT ? getTimeframesTracesAMT(minTimestamp) : "traces";
+
const query = `
SELECT
id,
@@ -1748,12 +1752,12 @@ export const getTracesForBlobStorageExport = function (
session_id,
release,
version,
- public,
- bookmarked,
+ ${useAMT ? "finalizeAggregation(public)" : "public"} as public,
+ ${useAMT ? "finalizeAggregation(bookmarked)" : "bookmarked"} as bookmarked,
tags,
- input,
- output
- FROM traces FINAL
+ ${useAMT ? "finalizeAggregation(input)" : "input"} as input,
+ ${useAMT ? "finalizeAggregation(output)" : "output"} as output
+ FROM ${traceTable} FINAL
WHERE project_id = {projectId: String}
AND timestamp >= {minTimestamp: DateTime64(3)}
AND timestamp <= {maxTimestamp: DateTime64(3)}
@@ -1771,6 +1775,7 @@ export const getTracesForBlobStorageExport = function (
type: "trace",
kind: "analytic",
projectId,
+ experiment_amt: useAMT ? "new" : "original",
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
@@ -1783,6 +1788,10 @@ export const getTracesForPostHog = async function* (
minTimestamp: Date,
maxTimestamp: Date,
) {
+ // Determine which trace table to use based on experiment flag
+ const useAMT = env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true";
+ const traceTable = useAMT ? getTimeframesTracesAMT(minTimestamp) : "traces";
+
const query = `
WITH observations_agg AS (
SELECT o.project_id,
@@ -1810,7 +1819,7 @@ export const getTracesForPostHog = async function* (
o.total_cost as total_cost,
o.latency_milliseconds / 1000 as latency,
o.observation_count as observation_count
- FROM traces t FINAL
+ FROM ${traceTable} t FINAL
LEFT JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id
WHERE t.project_id = {projectId: String}
AND t.timestamp >= {minTimestamp: DateTime64(3)}
@@ -1829,6 +1838,7 @@ export const getTracesForPostHog = async function* (
type: "trace",
kind: "analytic",
projectId,
+ experiment_amt: useAMT ? "new" : "original",
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.ts
index 81f1a937f1..473237e232 100644
--- a/web/src/features/public-api/server/dailyMetrics.ts
+++ b/web/src/features/public-api/server/dailyMetrics.ts
@@ -4,6 +4,8 @@ import {
queryClickhouse,
TRACE_TO_OBSERVATIONS_INTERVAL,
type DateTimeFilter,
+ getTimeframesTracesAMT,
+ measureAndReturn,
} from "@langfuse/shared/src/server";
type QueryType = {
@@ -45,7 +47,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
sum(arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, o.usage_details)))) as outputUsage,
sumMap(o.usage_details)['total'] as totalUsage,
sum(coalesce(o.total_cost, 0)) as totalCost
- FROM traces t FINAL
+ FROM __TRACE_TABLE__ t FINAL
LEFT JOIN observations o FINAL on o.trace_id = t.id AND o.project_id = t.project_id
WHERE o.project_id = {projectId: String}
AND t.project_id = {projectId: String}
@@ -72,7 +74,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
SELECT
toDate(t.timestamp) as date,
count(t.id) as countTraces
- FROM traces t FINAL
+ FROM __TRACE_TABLE__ t FINAL
WHERE t.project_id = {projectId: String}
${hasTracesFilter ? `AND ${appliedTracesFilter.query}` : ""}
GROUP BY date
@@ -90,48 +92,104 @@ export const generateDailyMetrics = async (props: QueryType) => {
${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
`;
- const result = await queryClickhouse<{
- date: string;
- countTraces: number;
- countObservations: number;
- totalCost: number;
- usage: (string | null)[][];
- }>({
- query,
- params: {
- ...appliedTracesFilter.params,
- ...appliedFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- ...(timeFilter
- ? {
- cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
- }
- : {}),
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : timeFilter?.value;
+
+ return measureAndReturn({
+ operationName: "generateDailyMetrics",
+ projectId: props.projectId,
+ minStartTime: timestamp,
+ input: {
+ params: {
+ ...appliedTracesFilter.params,
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ ...(timeFilter
+ ? {
+ cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),
+ }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "daily_metrics",
+ projectId: props.projectId,
+ operation_name: "generateDailyMetrics",
+ },
+ timestamp,
},
- clickhouseConfigs: {
- request_timeout: 60_000, // Use 1 minute timeout for daily metrics
+ existingExecution: async (input) => {
+ const result = await queryClickhouse<{
+ date: string;
+ countTraces: number;
+ countObservations: number;
+ totalCost: number;
+ usage: (string | null)[][];
+ }>({
+ query: query.replaceAll("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "original" },
+ clickhouseConfigs: {
+ request_timeout: 60_000, // Use 1 minute timeout for daily metrics
+ },
+ });
+
+ return result.map((record) => ({
+ date: record.date,
+ countTraces: Number(record.countTraces),
+ countObservations: Number(record.countObservations),
+ totalCost: Number(record.totalCost),
+ usage: record.usage.map((u) => ({
+ model: u[0],
+ inputUsage: Number(u[1]),
+ outputUsage: Number(u[2]),
+ totalUsage: Number(u[3]),
+ totalCost: Number(u[4]),
+ countObservations: Number(u[5]),
+ countTraces: Number(u[6]),
+ })),
+ }));
},
- });
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(input.timestamp);
+ const result = await queryClickhouse<{
+ date: string;
+ countTraces: number;
+ countObservations: number;
+ totalCost: number;
+ usage: (string | null)[][];
+ }>({
+ query: query.replaceAll("__TRACE_TABLE__", traceAmt),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "new" },
+ clickhouseConfigs: {
+ request_timeout: 60_000, // Use 1 minute timeout for daily metrics
+ },
+ });
- return result.map((record) => ({
- date: record.date,
- countTraces: Number(record.countTraces),
- countObservations: Number(record.countObservations),
- totalCost: Number(record.totalCost),
- usage: record.usage.map((u) => ({
- model: u[0],
- inputUsage: Number(u[1]),
- outputUsage: Number(u[2]),
- totalUsage: Number(u[3]),
- totalCost: Number(u[4]),
- countObservations: Number(u[5]),
- countTraces: Number(u[6]),
- })),
- }));
+ return result.map((record) => ({
+ date: record.date,
+ countTraces: Number(record.countTraces),
+ countObservations: Number(record.countObservations),
+ totalCost: Number(record.totalCost),
+ usage: record.usage.map((u) => ({
+ model: u[0],
+ inputUsage: Number(u[1]),
+ outputUsage: Number(u[2]),
+ totalUsage: Number(u[3]),
+ totalCost: Number(u[4]),
+ countObservations: Number(u[5]),
+ countTraces: Number(u[6]),
+ })),
+ }));
+ },
+ });
};
export const getDailyMetricsCount = async (props: QueryType) => {
@@ -145,16 +203,48 @@ export const getDailyMetricsCount = async (props: QueryType) => {
const query = `
SELECT count(distinct toDate(timestamp)) as count
- FROM traces t
+ FROM __TRACE_TABLE__ t
WHERE project_id = {projectId: String}
${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
`;
- const records = await queryClickhouse<{ count: string }>({
- query,
- params: { ...appliedFilter.params, projectId: props.projectId },
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : undefined;
+
+ return measureAndReturn({
+ operationName: "getDailyMetricsCount",
+ projectId: props.projectId,
+ minStartTime: timestamp,
+ input: {
+ params: { ...appliedFilter.params, projectId: props.projectId },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "daily_metrics_count",
+ projectId: props.projectId,
+ operation_name: "getDailyMetricsCount",
+ },
+ timestamp,
+ },
+ existingExecution: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "original" },
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(input.timestamp);
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", traceAmt),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "new" },
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
});
- return records.map((record) => Number(record.count)).shift();
};
const filterParams = [
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index ecb373326d..47ed372a7a 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -294,16 +294,48 @@ export const getTracesCountForPublicApi = async ({
const query = `
SELECT count() as count
- FROM traces t
+ FROM __TRACE_TABLE__ t
WHERE project_id = {projectId: String}
${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
`;
- const records = await queryClickhouse<{ count: string }>({
- query,
- params: { ...appliedFilter.params, projectId: props.projectId },
+ const timestamp = props.fromTimestamp
+ ? new Date(props.fromTimestamp)
+ : undefined;
+
+ return measureAndReturn({
+ operationName: "getTracesCountForPublicApi",
+ projectId: props.projectId,
+ minStartTime: timestamp,
+ input: {
+ params: { ...appliedFilter.params, projectId: props.projectId },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "count",
+ projectId: props.projectId,
+ operation_name: "getTracesCountForPublicApi",
+ },
+ timestamp,
+ },
+ existingExecution: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "original" },
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(input.timestamp);
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", traceAmt),
+ params: input.params,
+ tags: { ...input.tags, experiment_amt: "new" },
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
});
- return records.map((record) => Number(record.count)).shift();
};
const orderByColumns = [
diff --git a/worker/src/services/IngestionService/README.md b/worker/src/services/IngestionService/README.md
index 3482349a6a..95f3789d23 100644
--- a/worker/src/services/IngestionService/README.md
+++ b/worker/src/services/IngestionService/README.md
@@ -502,16 +502,16 @@ This checklist documents all references and invocations to the `traces` table gr
### 4. Aggregation and Analytics Queries
-- [ ] **getTracesCountForPublicApi()** - `web/src/features/public-api/server/traces.ts:299`
-- [ ] **generateDailyMetrics()** - `web/src/features/public-api/server/dailyMetrics.ts:93`
-- [ ] **getDailyMetricsCount()** - `web/src/features/public-api/server/dailyMetrics.ts:153`
+- [x] **getTracesCountForPublicApi()** - `web/src/features/public-api/server/traces.ts:299`
+- [x] **generateDailyMetrics()** - `web/src/features/public-api/server/dailyMetrics.ts:93`
+- [x] **getDailyMetricsCount()** - `web/src/features/public-api/server/dailyMetrics.ts:153`
- [x] **generateObservationsForPublicApi()** - `web/src/features/public-api/server/observations.ts:80`
- [x] **getObservationsCountForPublicApi()** - `web/src/features/public-api/server/observations.ts:108`
- [x] **getObservationsTableInternal()** - `packages/shared/src/server/repositories/observations.ts:565`
- [x] **_handleGenerateScoresForPublicApi()** - `web/src/features/public-api/server/scores.ts:101`
- [x] **_handleGetScoresCountForPublicApi()** - `web/src/features/public-api/server/scores.ts:181`
- [x] **getScoresUiGeneric()** - `packages/shared/src/server/repositories/scores.ts:825`
-- [ ] **getNumericScoreHistogram()** - `packages/shared/src/server/repositories/scores.ts:1074`
+- [x] **getNumericScoreHistogram()** - `packages/shared/src/server/repositories/scores.ts:1074`
- [x] **getTracesGroupedByName()** - `packages/shared/src/server/repositories/traces.ts:489-535`
- [x] **getTracesGroupedByUsers()** - `packages/shared/src/server/repositories/traces.ts:537-597`
- [x] **getTracesGroupedByTags()** - `packages/shared/src/server/repositories/traces.ts:605-640`
@@ -527,10 +527,10 @@ Note: The measureAndReturn utility does not handle query streams well as it prom
We need to cover these queries manually and cannot run a comparison.
We could use an opt-in on a projectId basis.
-- [ ] **getTracesForPostHog()** - `packages/shared/src/server/repositories/traces.ts:1026-1113`
-- [ ] **getScoresForPostHog()** - `packages/shared/src/server/repositories/scores.ts:1328`
-- [ ] **getGenerationsForPosthog()** - `packages/shared/src/server/repositories/observations.ts:1481`
-- [ ] **getTracesForBlobStorageExport()** - `packages/shared/src/server/repositories/traces.ts:980-1024`
+- [x] **getTracesForPostHog()** - `packages/shared/src/server/repositories/traces.ts:1026-1113`
+- [x] **getScoresForPostHog()** - `packages/shared/src/server/repositories/scores.ts:1328`
+- [x] **getGenerationsForPosthog()** - `packages/shared/src/server/repositories/observations.ts:1481`
+- [x] **getTracesForBlobStorageExport()** - `packages/shared/src/server/repositories/traces.ts:980-1024`
### 6. Count and Statistics Queries