Skip to content

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

perf: start to experimentally shift reads to new aggregatingmergetrees (#7631)

Steffen Schmitzd42c4e5e2fa6
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index eb408906de..4a72a40a25 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -107,6 +107,30 @@ const EnvSchema = z.object({
LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS: z.coerce.number().default(240_000), // 4 minutes
LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS: z.coerce.number().default(3), // Maximum attempts for socket hang up errors
LANGFUSE_SKIP_S3_LIST_FOR_OBSERVATIONS_PROJECT_IDS: z.string().optional(),
+
+ LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES: z
+ .enum(["true", "false"])
+ .default("false"),
+ LANGFUSE_EXPERIMENT_ADD_QUERY_RESULT_TO_SPAN_PROJECT_IDS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
+ ),
+ LANGFUSE_EXPERIMENT_SAMPLING_RATE: z.coerce
+ .number()
+ .min(0)
+ .max(1)
+ .default(0.1),
+ LANGFUSE_EXPERIMENT_WHITELISTED_PROJECT_IDS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
+ ),
+ LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z
+ .enum(["true", "false"])
+ .default("false"),
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/server/clickhouse/measureAndReturn.ts b/packages/shared/src/server/clickhouse/measureAndReturn.ts
new file mode 100644
index 0000000000..7076e5cd57
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/measureAndReturn.ts
@@ -0,0 +1,92 @@
+import { instrumentAsync } from "../instrumentation";
+import * as opentelemetry from "@opentelemetry/api";
+import { env } from "../../env";
+import { logger } from "../logger";
+
+const executionWrapper = async <T, Y>(
+ input: T,
+ fn: (input: T) => Promise<Y>, // eslint-disable-line no-unused-vars
+ span?: opentelemetry.Span,
+ attributePrefix?: string,
+): Promise<[Y, number]> => {
+ const startTime = Date.now();
+ const res = await fn(input);
+ const duration = Date.now() - startTime;
+ span?.setAttribute(`${attributePrefix}-duration`, duration);
+ return [res, duration];
+};
+
+export const measureAndReturn = async <T, Y>(args: {
+ operationName: string;
+ projectId: string;
+ input: T;
+ existingExecution: (input: T) => Promise<Y>; // eslint-disable-line no-unused-vars
+ newExecution: (input: T) => Promise<Y>; // eslint-disable-line no-unused-vars
+}): Promise<Y> => {
+ return instrumentAsync(
+ {
+ name: `experiment-${args.operationName}`,
+ spanKind: opentelemetry.SpanKind.CLIENT,
+ },
+ async (currentSpan) => {
+ const { input, existingExecution, newExecution } = args;
+
+ if (
+ env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES !==
+ "true"
+ ) {
+ currentSpan.setAttribute(`run-experiment`, "disabled");
+ return existingExecution(input);
+ }
+
+ // If not whitelisted, apply sampling logic
+ if (
+ !env.LANGFUSE_EXPERIMENT_WHITELISTED_PROJECT_IDS.includes(
+ args.projectId,
+ ) &&
+ Math.random() > env.LANGFUSE_EXPERIMENT_SAMPLING_RATE
+ ) {
+ currentSpan.setAttribute(`run-experiment`, "sampled-out");
+ return existingExecution(input);
+ }
+
+ currentSpan.setAttribute(`run-experiment`, "true");
+
+ try {
+ const [[existingResult, existingDuration], [newResult, newDuration]] =
+ await Promise.all([
+ executionWrapper(input, existingExecution, currentSpan, "existing"),
+ executionWrapper(input, newExecution, currentSpan, "new"),
+ ]);
+ // Positive duration difference means new is faster
+ const durationDifference = existingDuration - newDuration;
+ currentSpan?.setAttribute(
+ "execution-time-difference",
+ durationDifference,
+ );
+
+ if (
+ env.LANGFUSE_EXPERIMENT_ADD_QUERY_RESULT_TO_SPAN_PROJECT_IDS.some(
+ (p) => p === args.projectId,
+ )
+ ) {
+ currentSpan?.setAttribute(
+ "existing-result",
+ JSON.stringify(existingResult),
+ );
+ currentSpan?.setAttribute("new-result", JSON.stringify(newResult));
+ }
+
+ return env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"
+ ? newResult
+ : existingResult;
+ } catch (e) {
+ logger.error(
+ "Failed to run experiment wrapper. Retrying existing query",
+ e,
+ );
+ return existingExecution(input);
+ }
+ },
+ );
+};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index fc15597160..615f62ddb2 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -59,6 +59,7 @@ export * from "./services/datasets-ui-table-service";
export * from "./services/DashboardService";
export * from "./services/TableViewService";
export * from "./services/DefaultEvaluationModelService";
+export * from "./clickhouse/measureAndReturn";
export * from "./data-deletion/ingestionFileDeletion";
export * from "./s3";
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index fe28136dfd..07c1aba465 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -128,12 +128,12 @@ export const traceMtRecordInsertSchema = z.object({
id: z.string(),
start_time: z.number(),
end_time: z.number().nullish(),
- name: z.string(),
+ name: z.string().nullish(),
// Metadata properties
metadata: z.record(z.string(), z.string()),
- user_id: z.string(),
- session_id: z.string(),
+ user_id: z.string().nullish(),
+ session_id: z.string().nullish(),
environment: z.string(),
tags: z.array(z.string()),
version: z.string().nullish(),
@@ -411,3 +411,128 @@ export const convertPostgresScoreToInsert = (
is_deleted: 0,
};
};
+
+export const convertTraceToTraceMt = (
+ traceRecord: TraceRecordInsertType,
+): TraceMtRecordInsertType => {
+ return {
+ // Identifiers
+ project_id: traceRecord.project_id,
+ id: traceRecord.id,
+ start_time: traceRecord.timestamp,
+ end_time: null, // traces don't have end_time, will be null
+ name: traceRecord.name || null,
+
+ // Metadata properties
+ metadata: traceRecord.metadata,
+ user_id: traceRecord.user_id || null,
+ session_id: traceRecord.session_id || null,
+ environment: traceRecord.environment,
+ tags: traceRecord.tags,
+ version: traceRecord.version || null,
+ release: traceRecord.release || null,
+
+ // UI properties - nullable to prevent absent values being interpreted as overwrites
+ bookmarked: traceRecord.bookmarked ?? null,
+ public: traceRecord.public ?? null,
+
+ // Aggregations - empty for now, will be populated by aggregation processes
+ observation_ids: [],
+ score_ids: [],
+ cost_details: {},
+ usage_details: {},
+
+ // Input/Output
+ input: traceRecord.input || "",
+ output: traceRecord.output || "",
+
+ created_at: traceRecord.created_at,
+ updated_at: traceRecord.updated_at,
+ event_ts: traceRecord.event_ts,
+ };
+};
+
+export const convertObservationToTraceMt = (
+ observationRecord: ObservationRecordInsertType,
+): TraceMtRecordInsertType => {
+ return {
+ // Identifiers
+ project_id: observationRecord.project_id,
+ // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
+ id: observationRecord.trace_id || "",
+ start_time: observationRecord.start_time,
+ end_time: observationRecord.end_time || null,
+ name: null,
+
+ // Metadata properties
+ metadata: {},
+ user_id: null,
+ session_id: null,
+ environment: observationRecord.environment,
+ tags: [],
+ version: null,
+ release: null,
+
+ // UI properties - nullable to prevent absent values being interpreted as overwrites
+ bookmarked: null,
+ public: null,
+
+ // Aggregations - include this observation ID
+ observation_ids: [observationRecord.id],
+ score_ids: [],
+ // We can fill the cost details here, but we shouldn't trust them.
+ // Only used for verification to estimate how big the double-counting is.
+ // Actually, we don't as this will make backfills challenging.
+ cost_details: {}, // observationRecord.cost_details || {},
+ usage_details: {}, // observationRecord.usage_details || {},
+
+ // Input/Output
+ input: "",
+ output: "",
+
+ created_at: observationRecord.created_at,
+ updated_at: observationRecord.updated_at,
+ event_ts: observationRecord.event_ts,
+ };
+};
+
+export const convertScoreToTraceMt = (
+ scoreRecord: ScoreRecordInsertType,
+): TraceMtRecordInsertType => {
+ return {
+ // Identifiers
+ project_id: scoreRecord.project_id,
+ // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
+ id: scoreRecord.trace_id || "",
+ start_time: scoreRecord.timestamp,
+ end_time: null, // scores don't have end_time
+ name: null,
+
+ // Metadata properties
+ metadata: {},
+ user_id: null,
+ session_id: null,
+ environment: scoreRecord.environment,
+ tags: [], // scores don't have tags
+ version: null, // scores don't have version
+ release: null, // scores don't have release
+
+ // UI properties - nullable to prevent absent values being interpreted as overwrites
+ bookmarked: null,
+ public: null,
+
+ // Aggregations - include this score ID
+ observation_ids: [],
+ score_ids: [scoreRecord.id],
+ cost_details: {},
+ usage_details: {},
+
+ // Input/Output
+ input: "", // scores don't have input
+ output: "", // scores don't have output
+
+ created_at: scoreRecord.created_at,
+ updated_at: scoreRecord.updated_at,
+ event_ts: scoreRecord.event_ts,
+ };
+};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 3b37d598aa..3c3fc88a64 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -28,6 +28,40 @@ import {
import { env } from "../../env";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
+import { measureAndReturn } from "../clickhouse/measureAndReturn";
+
+enum TracesAMTs { // eslint-disable-line no-unused-vars
+ Traces7dAMT = "traces_7d_amt", // eslint-disable-line no-unused-vars
+ Traces30dAMT = "traces_30d_amt", // eslint-disable-line no-unused-vars
+ TracesAllAMT = "traces_all_amt", // eslint-disable-line no-unused-vars
+}
+
+/**
+ * Returns which AMT table to use given the timestamp.
+ * For <= 6 days, we use traces_7d_amt,
+ * for <= 29 days, we use traces_30d_amt,
+ * for all other cases we use traces_all_amt.
+ *
+ * @param fromTimestamp
+ */
+export const getTimeframesTracesAMT = (
+ fromTimestamp: Date | undefined,
+): TracesAMTs => {
+ if (!fromTimestamp) {
+ return TracesAMTs.TracesAllAMT;
+ }
+
+ const now = new Date();
+ const diffInDays = Math.floor(
+ (now.getTime() - fromTimestamp.getTime()) / (1000 * 60 * 60 * 24),
+ );
+ if (diffInDays <= 6) {
+ return TracesAMTs.Traces7dAMT;
+ } else if (diffInDays <= 29) {
+ return TracesAMTs.Traces30dAMT;
+ }
+ return TracesAMTs.TracesAllAMT;
+};
/**
* Checks if trace exists in clickhouse.
@@ -82,66 +116,103 @@ export const checkTraceExists = async ({
const tracesFilterRes = tracesFilter.apply();
const observationFilterRes = observationFilter?.apply();
- const query = `
+ const observations_cte = `
WITH observations_agg AS (
- SELECT
- multiIf(
- arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',
- arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',
- arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',
- 'DEBUG'
- ) AS aggregated_level,
- countIf(level = 'ERROR') as error_count,
- countIf(level = 'WARNING') as warning_count,
- countIf(level = 'DEFAULT') as default_count,
- countIf(level = 'DEBUG') as debug_count,
- trace_id,
- project_id
- FROM observations o FINAL
- WHERE o.project_id = {projectId: String}
+ SELECT
+ multiIf(
+ arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',
+ arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',
+ arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',
+ 'DEBUG'
+ ) AS aggregated_level,
+ countIf(level = 'ERROR') as error_count,
+ countIf(level = 'WARNING') as warning_count,
+ countIf(level = 'DEFAULT') as default_count,
+ countIf(level = 'DEBUG') as debug_count,
+ trace_id,
+ project_id
+ FROM observations o FINAL
+ WHERE o.project_id = {projectId: String}
${timeStampFilter ? `AND o.start_time >= {traceTimestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
AND o.start_time >= {timestamp: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}
- GROUP BY trace_id, project_id
- )
- SELECT
- t.id as id,
- t.project_id as project_id
- FROM traces t FINAL
- ${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}
- WHERE ${tracesFilterRes.query}
- AND t.project_id = {projectId: String}
- AND timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}
- ${maxTimeStamp ? `AND timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}
- ${!maxTimeStamp ? `AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}
- ${exactTimestamp ? `AND timestamp = {exactTimestamp: DateTime64(3)}` : ""}
- GROUP BY t.id, t.project_id
+ GROUP BY trace_id, project_id
+ )
`;
- const rows = await queryClickhouse<{ id: string; project_id: string }>({
- query,
- params: {
- projectId,
- ...tracesFilterRes.params,
- ...(observationFilterRes ? observationFilterRes.params : {}),
- ...(timestamp
- ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
- : {}),
- ...(maxTimeStamp
- ? { maxTimeStamp: convertDateToClickhouseDateTime(maxTimeStamp) }
- : {}),
- ...(exactTimestamp
- ? { exactTimestamp: convertDateToClickhouseDateTime(exactTimestamp) }
- : {}),
+ return measureAndReturn({
+ operationName: "checkTraceExists",
+ projectId,
+ input: {
+ params: {
+ projectId,
+ ...tracesFilterRes.params,
+ ...(observationFilterRes ? observationFilterRes.params : {}),
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ ...(maxTimeStamp
+ ? { maxTimeStamp: convertDateToClickhouseDateTime(maxTimeStamp) }
+ : {}),
+ ...(exactTimestamp
+ ? { exactTimestamp: convertDateToClickhouseDateTime(exactTimestamp) }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "exists",
+ projectId,
+ },
+ timestamp: timestamp ?? exactTimestamp,
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "exists",
- projectId,
+ existingExecution: async (input) => {
+ const query = `
+ ${observations_cte}
+ SELECT
+ t.id as id,
+ t.project_id as project_id
+ FROM traces t FINAL
+ ${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}
+ WHERE ${tracesFilterRes.query}
+ AND t.project_id = {projectId: String}
+ AND timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}
+ ${maxTimeStamp ? `AND timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}
+ ${!maxTimeStamp ? `AND timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}
+ ${exactTimestamp ? `AND timestamp = {exactTimestamp: DateTime64(3)}` : ""}
+ GROUP BY t.id, t.project_id
+ `;
+
+ const rows = await queryClickhouse<{ id: string; project_id: string }>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
+
+ return rows.length > 0;
+ },
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(input.timestamp);
+ const query = `
+ ${observations_cte}
+ SELECT
+ t.id as id,
+ t.project_id as project_id
+ FROM ${traceAmt} t
+ ${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}
+ WHERE ${tracesFilterRes.query}
+ AND t.project_id = {projectId: String}
+ GROUP BY t.id, t.project_id
+ `;
+
+ const rows = await queryClickhouse<{ id: string; project_id: string }>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
+
+ return rows.length > 0;
},
});
-
- return rows.length > 0;
};
/**
@@ -171,28 +242,77 @@ export const getTracesByIds = async (
timestamp?: Date,
clickhouseConfigs?: ClickHouseClientConfigOptions | undefined,
) => {
- const query = `
- SELECT *
- FROM traces
- WHERE id IN ({traceIds: Array(String)})
- AND project_id = {projectId: String}
- ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}
- ORDER BY event_ts DESC
- LIMIT 1 by id, project_id;`;
- const records = await queryClickhouse<TraceRecordReadType>({
- query,
- params: {
- traceIds,
- projectId,
- timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
+ const records = await measureAndReturn({
+ operationName: "getTracesByIds",
+ projectId,
+ input: {
+ params: {
+ traceIds,
+ projectId,
+ timestamp: timestamp
+ ? convertDateToClickhouseDateTime(timestamp)
+ : null,
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "byId",
+ projectId,
+ },
+ clickhouseConfigs,
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "byId",
- projectId,
+ existingExecution: (input) => {
+ const query = `
+ SELECT *
+ FROM traces
+ WHERE id IN ({traceIds: Array(String)})
+ AND project_id = {projectId: String}
+ ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}
+ ORDER BY event_ts DESC
+ LIMIT 1 by id, project_id;
+ `;
+ return queryClickhouse<TraceRecordReadType>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs: input.clickhouseConfigs,
+ });
+ },
+ newExecution: (input) => {
+ const query = `
+ SELECT
+ id,
+ name as name,
+ user_id as user_id,
+ metadata as metadata,
+ release as release,
+ version as version,
+ project_id,
+ environment,
+ finalizeAggregation(public) as public,
+ finalizeAggregation(bookmarked) as bookmarked,
+ tags,
+ finalizeAggregation(input) as input,
+ finalizeAggregation(output) as output,
+ session_id as session_id,
+ 0 as is_deleted,
+ start_time as timestamp,
+ created_at,
+ updated_at,
+ updated_at as event_ts
+ FROM traces_all_amt
+ WHERE id IN ({traceIds: Array(String)})
+ AND project_id = {projectId: String}
+ LIMIT 1 BY project_id, id
+ `;
+
+ return queryClickhouse<TraceRecordReadType>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs: input.clickhouseConfigs,
+ });
},
- clickhouseConfigs,
});
return records.map(convertClickhouseToDomain);
@@ -239,27 +359,55 @@ export const getTracesBySessionId = async (
};
export const hasAnyTrace = async (projectId: string) => {
- const query = `
- SELECT 1
- FROM traces
- WHERE project_id = {projectId: String}
- LIMIT 1
- `;
-
- const rows = await queryClickhouse<{ 1: number }>({
- query,
- params: {
+ return measureAndReturn({
+ operationName: "hasAnyTrace",
+ projectId,
+ input: {
projectId,
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "hasAny",
+ projectId,
+ },
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "hasAny",
- projectId,
+ existingExecution: async (input) => {
+ const query = `
+ SELECT 1
+ FROM traces
+ WHERE project_id = {projectId: String}
+ LIMIT 1
+ `;
+
+ const rows = await queryClickhouse<{ 1: number }>({
+ query,
+ params: {
+ projectId: input.projectId,
+ },
+ tags: input.tags,
+ });
+
+ return rows.length > 0;
+ },
+ newExecution: async (input) => {
+ const query = `
+ SELECT 1
+ FROM traces_all_amt
+ WHERE project_id = {projectId: String}
+ LIMIT 1
+ `;
+
+ const rows = await queryClickhouse<{ 1: number }>({
+ query,
+ params: {
+ projectId: input.projectId,
+ },
+ tags: input.tags,
+ });
+
+ return rows.length > 0;
},
});
-
- return rows.length > 0;
};
export const getTraceCountsByProjectInCreationInterval = async ({
@@ -347,34 +495,78 @@ export const getTraceById = async ({
timestamp?: Date;
fromTimestamp?: Date;
}) => {
- const query = `
- SELECT *
- FROM traces
- WHERE id = {traceId: String}
- AND project_id = {projectId: String}
- ${timestamp ? `AND toDate(timestamp) = toDate({timestamp: DateTime64(3)})` : ""}
- ${fromTimestamp ? `AND timestamp >= {fromTimestamp: DateTime64(3)}` : ""}
- ORDER BY event_ts DESC
- LIMIT 1
- `;
-
- const records = await queryClickhouse<TraceRecordReadType>({
- query,
- params: {
- traceId,
- projectId,
- ...(timestamp
- ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
- : {}),
- ...(fromTimestamp
- ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
- : {}),
+ const records = await measureAndReturn({
+ operationName: "getTraceById",
+ projectId,
+ input: {
+ params: {
+ traceId,
+ projectId,
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ ...(fromTimestamp
+ ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "trace",
+ kind: "byId",
+ projectId,
+ },
},
- tags: {
- feature: "tracing",
- type: "trace",
- kind: "byId",
- projectId,
+ existingExecution: (input) => {
+ const query = `
+ SELECT *
+ FROM traces
+ WHERE id = {traceId: String}
+ AND project_id = {projectId: String}
+ ${timestamp ? `AND toDate(timestamp) = toDate({timestamp: DateTime64(3)})` : ""}
+ ${fromTimestamp ? `AND timestamp >= {fromTimestamp: DateTime64(3)}` : ""}
+ ORDER BY event_ts DESC
+ LIMIT 1
+ `;
+
+ return queryClickhouse<TraceRecordReadType>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
+ },
+ newExecution: (input) => {
+ const query = `
+ SELECT
+ id,
+ name as name,
+ user_id as user_id,
+ metadata as metadata,
+ release as release,
+ version as version,
+ project_id,
+ environment,
+ finalizeAggregation(public) as public,
+ finalizeAggregation(bookmarked) as bookmarked,
+ tags,
+ finalizeAggregation(input) as input,
+ finalizeAggregation(output) as output,
+ session_id as session_id,
+ 0 as is_deleted,
+ start_time as timestamp,
+ created_at,
+ updated_at,
+ updated_at as event_ts
+ FROM traces_all_amt
+ WHERE id = {traceId: String}
+ AND project_id = {projectId: String}
+ LIMIT 1
+ `;
+
+ return queryClickhouse<TraceRecordReadType>({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
},
});
diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
index 0184f21a67..728f5fe101 100644
--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts
+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts
@@ -3,9 +3,20 @@ import {
TraceRecordInsertType,
ObservationRecordInsertType,
ScoreRecordInsertType,
+ convertTraceToTraceMt,
} from "../repositories/definitions";
+import { env } from "../../env";
export const createTracesCh = async (trace: TraceRecordInsertType[]) => {
+ if (
+ env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES === "true"
+ ) {
+ return await clickhouseClient().insert({
+ table: "traces_mt",
+ format: "JSONEachRow",
+ values: trace.map(convertTraceToTraceMt),
+ });
+ }
return await clickhouseClient().insert({
table: "traces",
format: "JSONEachRow",
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index eb72ca786c..6ff1d17829 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -7,6 +7,8 @@ import {
type DateTimeFilter,
convertClickhouseToDomain,
type TraceRecordReadType,
+ getTimeframesTracesAMT,
+ measureAndReturn,
} from "@langfuse/shared/src/server";
import { type OrderByState } from "@langfuse/shared";
import { snakeCase } from "lodash";
@@ -121,67 +123,138 @@ export const generateTracesForPublicApi = async ({
const withClause = ctes.length > 0 ? `WITH ${ctes.join(", ")}` : "";
- const query = `
- ${withClause}
+ const result = await measureAndReturn({
+ operationName: "getTracesForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedEnvironmentFilter.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: "public-api",
+ projectId: props.projectId,
+ },
+ fromTimestamp: timeFilter?.value ?? undefined,
+ },
+ existingExecution: (input) => {
+ const query = `
+ ${withClause}
+
+ SELECT
+ -- Core fields (always included)
+ t.id as id,
+ CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
+ t.project_id as project_id,
+ t.timestamp as timestamp,
+ t.name as name,
+ t.environment as environment,
+ t.session_id as session_id,
+ t.user_id as user_id,
+ t.release as release,
+ t.version as version,
+ t.bookmarked as bookmarked,
+ t.public as public,
+ t.tags as tags,
+ t.created_at as created_at,
+ t.updated_at as updated_at
+ -- IO fields (conditional)
+ ${includeIO ? ", t.input as input, t.output as output, t.metadata as metadata" : ""}
+ -- Scores (conditional)
+ ${includeScores ? ", s.score_ids as scores" : ""}
+ -- Observations (conditional)
+ ${includeObservations ? ", o.observation_ids as observations" : ""}
+ -- Metrics (conditional)
+ ${includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
+ FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
+ ${includeObservations || includeMetrics ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${includeScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
+ WHERE t.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ ${chOrderBy}
+ ${shouldUseSkipIndexes ? "LIMIT 1 by t.id, t.project_id" : ""}
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
- SELECT
- -- Core fields (always included)
- t.id as id,
- CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
- t.project_id as project_id,
- t.timestamp as timestamp,
- t.name as name,
- t.environment as environment,
- t.session_id as session_id,
- t.user_id as user_id,
- t.release as release,
- t.version as version,
- t.bookmarked as bookmarked,
- t.public as public,
- t.tags as tags,
- t.created_at as created_at,
- t.updated_at as updated_at
- -- IO fields (conditional)
- ${includeIO ? ", t.input as input, t.output as output, t.metadata as metadata" : ""}
- -- Scores (conditional)
- ${includeScores ? ", s.score_ids as scores" : ""}
- -- Observations (conditional)
- ${includeObservations ? ", o.observation_ids as observations" : ""}
- -- Metrics (conditional)
- ${includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
- FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
- ${includeObservations || includeMetrics ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
- ${includeScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
- WHERE t.project_id = {projectId: String}
- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
- ${chOrderBy}
- ${shouldUseSkipIndexes ? "LIMIT 1 by t.id, t.project_id" : ""}
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
+ return queryClickhouse<
+ TraceRecordReadType & {
+ observations?: string[];
+ scores?: string[];
+ totalCost?: number;
+ latency?: number;
+ htmlPath: string;
+ }
+ >({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
+ },
+ newExecution: (input) => {
+ const tracesAmt = getTimeframesTracesAMT(input.fromTimestamp);
- const result = await queryClickhouse<
- TraceRecordReadType & {
- observations?: string[];
- scores?: string[];
- totalCost?: number;
- latency?: number;
- htmlPath: string;
- }
- >({
- query,
- params: {
- ...appliedEnvironmentFilter.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 query = `
+ ${withClause}
+
+ SELECT
+ -- Core fields (always included)
+ t.id as id,
+ CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
+ t.project_id as project_id,
+ t.start_time as timestamp,
+ t.name as name,
+ t.environment as environment,
+ t.session_id as session_id,
+ t.user_id as user_id,
+ t.release as release,
+ t.version as version,
+ finalizeAggregation(t.bookmarked) as bookmarked,
+ finalizeAggregation(t.public) as public,
+ t.tags as tags,
+ t.created_at as created_at,
+ t.updated_at as updated_at
+ -- IO fields (conditional)
+ ${includeIO ? ", finalizeAggregation(t.input) as input, finalizeAggregation(t.output) as output, t.metadata as metadata" : ""}
+ -- Scores (conditional)
+ ${includeScores ? ", s.score_ids as scores" : ""}
+ -- Observations (conditional)
+ ${includeObservations ? ", o.observation_ids as observations" : ""}
+ -- Metrics (conditional)
+ ${includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
+ FROM ${tracesAmt} t
+ ${includeObservations || includeMetrics ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${includeScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
+ WHERE t.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ ${chOrderBy}
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ return queryClickhouse<
+ TraceRecordReadType & {
+ observations?: string[];
+ scores?: string[];
+ totalCost?: number;
+ latency?: number;
+ htmlPath: string;
+ }
+ >({
+ query,
+ params: input.params,
+ tags: input.tags,
+ });
},
});
diff --git a/worker/src/services/IngestionService/README.md b/worker/src/services/IngestionService/README.md
index f91c80c87c..b9c17848d7 100644
--- a/worker/src/services/IngestionService/README.md
+++ b/worker/src/services/IngestionService/README.md
@@ -26,12 +26,12 @@ CREATE TABLE traces_mt
`id` String,
`start_time` DateTime64(3),
`end_time` Nullable(DateTime64(3)),
- `name` String,
+ `name` Nullable(String),
-- Metadata properties
`metadata` Map(LowCardinality(String), String),
- `user_id` String,
- `session_id` String,
+ `user_id` Nullable(String),
+ `session_id` Nullable(String),
`environment` String,
`tags` Array(String),
`version` Nullable(String),
@@ -61,30 +61,22 @@ CREATE TABLE traces_mt
-- Create the all AMT
CREATE TABLE traces_all_amt
-(
+(
-- Identifiers
`project_id` String,
`id` String,
`start_time` SimpleAggregateFunction(min, DateTime64(3)),
`end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
- `name_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `name` SimpleAggregateFunction(anyLast, String),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- -- Metadata takes the last seen value in this form.
- -- If we spread it across multiple rows (keys + values) we might be able to allow updates/overwrites.
- -- Indexing speed in this case is unclear though.
- `metadata_argmax` AggregateFunction(argMax, Map(LowCardinality(String), String), DateTime64(3)),
- `metadata` SimpleAggregateFunction(anyLast, Map(String, String)),
- `user_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `session_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `environment_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `user_id` SimpleAggregateFunction(anyLast, String),
- `session_id` SimpleAggregateFunction(anyLast, String),
+ `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
`tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
- `version` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
- `release` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
-- UI properties
`bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
@@ -96,19 +88,20 @@ CREATE TABLE traces_all_amt
`cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
`usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
- -- Input/Output
- `input_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `output_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `input` SimpleAggregateFunction(anyLast, String),
- `output` SimpleAggregateFunction(anyLast, String),
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
`created_at` SimpleAggregateFunction(min, DateTime64(3)),
`updated_at` SimpleAggregateFunction(max, DateTime64(3)),
-- Indexes
- INDEX idx_environment environment TYPE bloom_filter(0.001) GRANULARITY 1,
INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
- INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
) Engine = AggregatingMergeTree()
ORDER BY (project_id, id);
@@ -121,21 +114,16 @@ SELECT
t0.id as id,
min(t0.start_time) as start_time,
max(coalesce(t0.end_time, t0.start_time)) as end_time,
- argMaxState(t0.name, if(t0.name <> '', t0.event_ts, toDateTime64(0, 3))) as name_argmax,
anyLast(t0.name) as name,
-- Metadata properties
- argMaxState(t0.metadata, if(t0.metadata <> '{}', t0.event_ts, toDateTime64(0,3))) as metadata_argmax,
- anyLastMap(t0.metadata) as metadata,
- argMaxState(t0.user_id, if(t0.user_id <> '', t0.event_ts, toDateTime64(0, 3))) as user_id_argmax,
- argMaxState(t0.session_id, if(t0.session_id <> '', t0.event_ts, toDateTime64(0, 3))) as session_id_argmax,
- argMaxState(t0.environment, if(t0.environment <> '', t0.event_ts, toDateTime64(0, 3))) as environment_argmax,
+ minMap(t0.metadata) as metadata,
anyLast(t0.user_id) as user_id,
anyLast(t0.session_id) as session_id,
anyLast(t0.environment) as environment,
groupUniqArrayArray(t0.tags) as tags,
- argMaxState(t0.version, if(t0.version <> '', t0.event_ts, toDateTime64(0, 3))) as version,
- argMaxState(t0.release, if(t0.release <> '', t0.event_ts, toDateTime64(0, 3))) as release,
+ anyLast(t0.version) as version,
+ anyLast(t0.release) as release,
-- UI properties
argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
@@ -148,10 +136,8 @@ SELECT
sumMap(t0.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input_argmax,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output_argmax,
- anyLast(input) as input,
- anyLast(output) as output,
+ argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
min(t0.created_at) as created_at,
max(t0.updated_at) as updated_at
@@ -166,21 +152,16 @@ CREATE TABLE traces_7d_amt
`id` String,
`start_time` SimpleAggregateFunction(min, DateTime64(3)),
`end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
- `name_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `name` SimpleAggregateFunction(anyLast, String),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- `metadata_argmax` AggregateFunction(argMax, Map(LowCardinality(String), String), DateTime64(3)),
- `metadata` SimpleAggregateFunction(anyLast, Map(String, String)),
- `user_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `session_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `environment_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `user_id` SimpleAggregateFunction(anyLast, String),
- `session_id` SimpleAggregateFunction(anyLast, String),
+ `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
`tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
- `version` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
- `release` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
-- UI properties
`bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
@@ -192,19 +173,20 @@ CREATE TABLE traces_7d_amt
`cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
`usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
- -- Input/Output
- `input_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `output_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `input` SimpleAggregateFunction(anyLast, String),
- `output` SimpleAggregateFunction(anyLast, String),
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
`created_at` SimpleAggregateFunction(min, DateTime64(3)),
`updated_at` SimpleAggregateFunction(max, DateTime64(3)),
-- Indexes
- INDEX idx_environment environment TYPE bloom_filter(0.001) GRANULARITY 1,
INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
- INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
) Engine = AggregatingMergeTree()
ORDER BY (project_id, id)
TTL toDate(start_time) + INTERVAL 7 DAY;
@@ -217,21 +199,16 @@ SELECT
t0.id as id,
min(t0.start_time) as start_time,
max(coalesce(t0.end_time, t0.start_time)) as end_time,
- argMaxState(t0.name, if(t0.name <> '', t0.event_ts, toDateTime64(0, 3))) as name_argmax,
anyLast(t0.name) as name,
-- Metadata properties
- argMaxState(t0.metadata, if(t0.metadata <> '{}', t0.event_ts, toDateTime64(0,3))) as metadata_argmax,
- anyLastMap(t0.metadata) as metadata,
- argMaxState(t0.user_id, if(t0.user_id <> '', t0.event_ts, toDateTime64(0, 3))) as user_id_argmax,
- argMaxState(t0.session_id, if(t0.session_id <> '', t0.event_ts, toDateTime64(0, 3))) as session_id_argmax,
- argMaxState(t0.environment, if(t0.environment <> '', t0.event_ts, toDateTime64(0, 3))) as environment_argmax,
+ minMap(t0.metadata) as metadata,
anyLast(t0.user_id) as user_id,
anyLast(t0.session_id) as session_id,
anyLast(t0.environment) as environment,
groupUniqArrayArray(t0.tags) as tags,
- argMaxState(t0.version, if(t0.version <> '', t0.event_ts, toDateTime64(0, 3))) as version,
- argMaxState(t0.release, if(t0.release <> '', t0.event_ts, toDateTime64(0, 3))) as release,
+ anyLast(t0.version) as version,
+ anyLast(t0.release) as release,
-- UI properties
argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
@@ -244,10 +221,8 @@ SELECT
sumMap(t0.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input_argmax,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output_argmax,
- anyLast(input) as input,
- anyLast(output) as output,
+ argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
min(t0.created_at) as created_at,
max(t0.updated_at) as updated_at
@@ -262,21 +237,16 @@ CREATE TABLE traces_30d_amt
`id` String,
`start_time` SimpleAggregateFunction(min, DateTime64(3)),
`end_time` SimpleAggregateFunction(max, Nullable(DateTime64(3))),
- `name_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `name` SimpleAggregateFunction(anyLast, String),
+ `name` SimpleAggregateFunction(anyLast, Nullable(String)),
-- Metadata properties
- `metadata_argmax` AggregateFunction(argMax, Map(LowCardinality(String), String), DateTime64(3)),
- `metadata` SimpleAggregateFunction(anyLast, Map(String, String)),
- `user_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `session_id_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `environment_argmax` AggregateFunction(argMax, String, DateTime64(3)),
- `user_id` SimpleAggregateFunction(anyLast, String),
- `session_id` SimpleAggregateFunction(anyLast, String),
+ `metadata` SimpleAggregateFunction(minMap, Map(String, String)),
+ `user_id` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `session_id` SimpleAggregateFunction(anyLast, Nullable(String)),
`environment` SimpleAggregateFunction(anyLast, String),
`tags` SimpleAggregateFunction(groupUniqArrayArray, Array(String)),
- `version` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
- `release` AggregateFunction(argMax, Nullable(String), DateTime64(3)),
+ `version` SimpleAggregateFunction(anyLast, Nullable(String)),
+ `release` SimpleAggregateFunction(anyLast, Nullable(String)),
-- UI properties
`bookmarked` AggregateFunction(argMax, Nullable(Bool), DateTime64(3)),
@@ -288,19 +258,20 @@ CREATE TABLE traces_30d_amt
`cost_details` SimpleAggregateFunction(sumMap, Map(String, Decimal(38, 12))),
`usage_details` SimpleAggregateFunction(sumMap, Map(String, UInt64)),
- -- Input/Output
- `input_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `output_argmax` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
- `input` SimpleAggregateFunction(anyLast, String),
- `output` SimpleAggregateFunction(anyLast, String),
+ -- Input/Output -> prefer correctness via argMax
+ `input` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
+ `output` AggregateFunction(argMax, String, DateTime64(3)) CODEC (ZSTD(3)),
`created_at` SimpleAggregateFunction(min, DateTime64(3)),
`updated_at` SimpleAggregateFunction(max, DateTime64(3)),
-- Indexes
- INDEX idx_environment environment TYPE bloom_filter(0.001) GRANULARITY 1,
INDEX idx_user_id user_id TYPE bloom_filter(0.001) GRANULARITY 1,
- INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1
+ INDEX idx_session_id session_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_name name TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_version version TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_release release TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_tags tags TYPE bloom_filter(0.001) GRANULARITY 1
) Engine = AggregatingMergeTree()
ORDER BY (project_id, id)
TTL toDate(start_time) + INTERVAL 30 DAY;
@@ -313,21 +284,16 @@ SELECT
t0.id as id,
min(t0.start_time) as start_time,
max(coalesce(t0.end_time, t0.start_time)) as end_time,
- argMaxState(t0.name, if(t0.name <> '', t0.event_ts, toDateTime64(0, 3))) as name_argmax,
anyLast(t0.name) as name,
-- Metadata properties
- argMaxState(t0.metadata, if(t0.metadata <> '{}', t0.event_ts, toDateTime64(0,3))) as metadata_argmax,
- anyLastMap(t0.metadata) as metadata,
- argMaxState(t0.user_id, if(t0.user_id <> '', t0.event_ts, toDateTime64(0, 3))) as user_id_argmax,
- argMaxState(t0.session_id, if(t0.session_id <> '', t0.event_ts, toDateTime64(0, 3))) as session_id_argmax,
- argMaxState(t0.environment, if(t0.environment <> '', t0.event_ts, toDateTime64(0, 3))) as environment_argmax,
+ minMap(t0.metadata) as metadata,
anyLast(t0.user_id) as user_id,
anyLast(t0.session_id) as session_id,
anyLast(t0.environment) as environment,
groupUniqArrayArray(t0.tags) as tags,
- argMaxState(t0.version, if(t0.version <> '', t0.event_ts, toDateTime64(0, 3))) as version,
- argMaxState(t0.release, if(t0.release <> '', t0.event_ts, toDateTime64(0, 3))) as release,
+ anyLast(t0.version) as version,
+ anyLast(t0.release) as release,
-- UI properties
argMaxState(t0.bookmarked, if(t0.bookmarked is not null, t0.event_ts, toDateTime64(0, 3))) as bookmarked,
@@ -340,10 +306,8 @@ SELECT
sumMap(t0.usage_details) as usage_details,
-- Input/Output
- argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input_argmax,
- argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output_argmax,
- anyLast(input) as input,
- anyLast(output) as output,
+ argMaxState(t0.input, if(t0.input <> '', t0.event_ts, toDateTime64(0, 3))) as input,
+ argMaxState(t0.output, if(t0.output <> '', t0.event_ts, toDateTime64(0, 3))) as output,
min(t0.created_at) as created_at,
max(t0.updated_at) as updated_at
@@ -356,44 +320,38 @@ GROUP BY project_id, id;
We can query the properties of the resulting AggregatingMergeTree via (make sure to pick the right timeframe:
```sql
SELECT
- -- Identifiers
- project_id,
- id,
- start_time,
- end_time,
- finalizeAggregation(name_argmax) AS name_argmax_value,
- name,
-
- -- Metadata properties
- finalizeAggregation(metadata) AS metadata_value,
- finalizeAggregation(user_id_argmax) AS user_id_argmax_value,
- finalizeAggregation(session_id_argmax) AS session_id_argmax_value,
- finalizeAggregation(environment_argmax) AS environment_argmax_value,
- user_id,
- session_id,
- environment,
- tags,
- finalizeAggregation(version) AS version_value,
- finalizeAggregation(release) AS release_value,
-
- -- UI properties
- finalizeAggregation(bookmarked) AS bookmarked_value,
- finalizeAggregation(public) AS public_value,
-
- -- Aggregations
- observation_ids,
- score_ids,
- cost_details,
- usage_details,
-
- -- Input/Output
- finalizeAggregation(input_argmax) AS input_argmax_value,
- finalizeAggregation(output_argmax) AS output_argmax_value,
- input,
- output,
-
- created_at,
- updated_at
+ -- Identifiers
+ project_id,
+ id,
+ start_time,
+ end_time,
+ name,
+
+ -- Metadata properties
+ metadata,
+ user_id,
+ session_id,
+ environment,
+ tags,
+ version,
+ release,
+
+ -- UI properties
+ finalizeAggregation(bookmarked) AS bookmarked_value,
+ finalizeAggregation(public) AS public_value,
+
+ -- Aggregations
+ observation_ids,
+ score_ids,
+ cost_details,
+ usage_details,
+
+ -- Input/Output
+ finalizeAggregation(input) AS input_value,
+ finalizeAggregation(output) AS output_value,
+
+ created_at,
+ updated_at
FROM traces_all_amt
LIMIT 100;
```
@@ -405,36 +363,29 @@ We can identify discrepancies in the original and the new data using
-- Query to compare traces_all_amt with traces table and identify discrepancies
WITH amt_data AS (
-- First get the finalized values from the AMT table
- SELECT project_id,
- id,
- start_time,
- end_time,
- finalizeAggregation(name_argmax) AS name_argmax_value,
- name AS name_anylast_value,
-
- finalizeAggregation(metadata_argmax) AS metadata_argmax_value,
- metadata AS metadata_anylast_value,
- finalizeAggregation(user_id_argmax) AS user_id_argmax_value,
- user_id AS user_id_anylast_value,
- finalizeAggregation(session_id_argmax) AS session_id_argmax_value,
- session_id AS session_id_anylast_value,
- finalizeAggregation(environment_argmax) AS environment_argmax_value,
- environment AS environment_anylast_value,
- tags,
- finalizeAggregation(version) AS version_value,
- finalizeAggregation(release) AS release_value,
-
- finalizeAggregation(bookmarked) AS bookmarked_value,
- finalizeAggregation(public) AS public_value,
-
- finalizeAggregation(input_argmax) AS input_argmax_value,
- input AS input_anylast_value,
- finalizeAggregation(output_argmax) AS output_argmax_value,
- output AS output_anylast_value,
-
- created_at,
- updated_at
- FROM traces_all_amt
+ SELECT project_id,
+ id,
+ start_time,
+ end_time,
+ name,
+
+ metadata,
+ user_id,
+ session_id,
+ environment,
+ tags,
+ version,
+ release,
+
+ finalizeAggregation(bookmarked) AS bookmarked_value,
+ finalizeAggregation(public) AS public_value,
+
+ finalizeAggregation(input) AS input_value,
+ finalizeAggregation(output) AS output_value,
+
+ created_at,
+ updated_at
+ FROM traces_all_amt
)
-- Main query to compare AMT with original traces table
@@ -442,45 +393,33 @@ SELECT t.project_id,
t.id,
-- Identify differences between tables
t.timestamp != a.start_time AS timestamp_diff,
- t.name != a.name_anylast_value AS name_diff,
- t.user_id != a.user_id_anylast_value AS user_id_diff,
- t.session_id != a.session_id_anylast_value AS session_id_diff,
- t.release != a.release_value AS release_diff,
- t.version != a.version_value AS version_diff,
+ t.name != a.name AS name_diff,
+ t.user_id != a.user_id AS user_id_diff,
+ t.session_id != a.session_id AS session_id_diff,
+ t.release != a.release AS release_diff,
+ t.version != a.version AS version_diff,
t.public != a.public_value AS public_diff,
t.bookmarked != a.bookmarked_value AS bookmarked_diff,
arraySort(t.tags) != arraySort(a.tags) AS tags_diff,
- t.input != a.input_anylast_value AS input_diff,
- t.output != a.output_anylast_value AS output_diff,
- t.metadata != a.metadata_anylast_value AS metadata_diff,
-
- a.name_argmax_value != a.name_anylast_value AS amt_name_diff,
- a.user_id_argmax_value != a.user_id_anylast_value AS amt_user_id_diff,
- a.session_id_argmax_value != a.session_id_anylast_value AS amt_session_id_diff,
- a.environment_argmax_value != a.environment_anylast_value AS amt_environment_diff,
- a.input_argmax_value != a.input_anylast_value AS amt_input_diff,
- a.output_argmax_value != a.output_anylast_value AS amt_output_diff,
- a.metadata_argmax_value != a.metadata_anylast_value AS amt_metadata_diff,
+ t.input != a.input_value AS input_diff,
+ t.output != a.output_value AS output_diff,
+ t.metadata != a.metadata AS metadata_diff,
+ t.environment != a.environment AS environment_diff,
-- Include original values for comparison
t.timestamp AS traces_timestamp,
a.start_time AS amt_start_time,
t.name AS traces_name,
- a.name_anylast_value AS amt_name_anylast,
- a.name_argmax_value AS amt_name_argmax,
+ a.name AS amt_name,
t.user_id AS traces_user_id,
- a.user_id_anylast_value AS amt_user_id_anylast,
- a.user_id_argmax_value AS amt_user_id_argmax,
+ a.user_id AS amt_user_id,
t.session_id AS traces_session_id,
- a.session_id_anylast_value AS amt_session_id_anylast,
- a.session_id_argmax_value AS amt_session_id_argmax,
+ a.session_id AS amt_session_id,
t.environment AS traces_environment,
- a.environment_anylast_value AS amt_environment_anylast,
- a.environment_argmax_value AS amt_environment_argmax,
+ a.environment AS amt_environment,
t.metadata AS traces_metadata,
- a.metadata_anylast_value AS amt_metadata_anylast,
- a.metadata_argmax_value AS amt_metadata_argmax,
+ a.metadata AS amt_metadata,
arraySort(t.tags) AS traces_tags,
arraySort(a.tags) AS amt_tags,
t.bookmarked AS traces_bookmarked,
@@ -488,16 +427,14 @@ SELECT t.project_id,
t.public AS traces_public,
a.public_value AS amt_public,
t.release AS traces_release,
- a.release_value AS amt_release,
+ a.release AS amt_release,
t.version AS traces_version,
- a.version_value AS amt_version,
+ a.version AS amt_version,
t.input AS traces_input,
- a.input_anylast_value AS amt_input_anylast,
- a.input_argmax_value AS amt_input_argmax,
+ a.input_value AS amt_input,
t.output AS traces_output,
- a.output_anylast_value AS amt_output_anylast,
- a.output_argmax_value AS amt_output_argmax,
+ a.output_value AS amt_output,
timestamp_diff +
name_diff +
@@ -510,16 +447,57 @@ SELECT t.project_id,
tags_diff +
input_diff +
output_diff +
- metadata_diff
- AS total_diff
+ metadata_diff +
+ environment_diff
+ AS total_diff
FROM traces t FINAL
LEFT JOIN amt_data a ON t.project_id = a.project_id AND t.id = a.id
-where (t.timestamp >= '2025-07-01'
-or a.start_time >= '2025-07-01')
-and t.project_id in (
+WHERE (t.timestamp >= '2025-07-01' OR a.start_time >= '2025-07-01')
+AND t.project_id IN (
'some-project-id'
)
-ORDER BY total_diff desc
+ORDER BY total_diff DESC
LIMIT 1000;
-```
\ No newline at end of file
+```
+
+## Traces Table Access Pattern Checklist
+
+This checklist documents all references and invocations to the `traces` table grouped by their access pattern. Use this as a baseline to perform transformations like the one in `@/packages/shared/src/server/repositories/traces.ts` with the `measureAndReturn` utility.
+
+### 1. Single Record Lookups (by ID)
+- [ ] **IngestionService.getClickhouseRecord()** - `worker/src/services/IngestionService/index.ts:1047-1065`
+ - Can probably be skipped as read for updates won't be a thing in the new flow.
+- [x] **getTraceById()** - `packages/shared/src/server/repositories/traces.ts:443-486`
+- [x] **getTracesByIds()** - `packages/shared/src/server/repositories/traces.ts:233-264`
+
+### 2. Session-Based Queries
+- [ ] **getTracesBySessionId()** - `packages/shared/src/server/repositories/traces.ts:266-304`
+- [ ] **getTracesIdentifierForSession()** - `packages/shared/src/server/repositories/traces.ts:642-688`
+- [ ] **traceWithSessionIdExists()** - `packages/shared/src/server/repositories/traces.ts:1143-1170`
+
+### 3. Existence Checks
+- [x] **checkTraceExists()** - `packages/shared/src/server/repositories/traces.ts:73-210`
+- [x] **hasAnyTrace()** - `packages/shared/src/server/repositories/traces.ts:306-356`
+- [ ] **hasAnyUser()** - `packages/shared/src/server/repositories/traces.ts:763-787`
+
+### 4. Aggregation and Analytics Queries
+- [ ] **getTracesGroupedByName()** - `packages/shared/src/server/repositories/traces.ts:489-535`
+- [ ] **getTracesGroupedByUsers()** - `packages/shared/src/server/repositories/traces.ts:537-597`
+- [ ] **getTracesGroupedByTags()** - `packages/shared/src/server/repositories/traces.ts:605-640`
+- [ ] **getTotalUserCount()** - `packages/shared/src/server/repositories/traces.ts:789-827`
+- [ ] **getUserMetrics()** - `packages/shared/src/server/repositories/traces.ts:829-978`
+- [ ] **getTracesTableGeneric()** - `packages/shared/src/server/services/traces-ui-table-service.ts:207++`
+- [ ] **getSessionsTableGeneric()** - `packages/shared/src/server/services/sessions-ui-table-service.ts:121++`)
+- [x] **generateTracesForPublicApi()** - `web/src/features/public-api/server/traces.ts:36++`
+
+### 5. Data Export and Migration
+- [ ] **getTracesForPostHog()** - `packages/shared/src/server/repositories/traces.ts:1026-1113`
+- [ ] **getTracesForBlobStorageExport()** - `packages/shared/src/server/repositories/traces.ts:980-1024`
+
+### 6. Count and Statistics Queries
+- [ ] **getTraceCountsByProjectInCreationInterval()** - `packages/shared/src/server/repositories/traces.ts:358-392`
+- [ ] **getTraceCountOfProjectsSinceCreationDate()** - `packages/shared/src/server/repositories/traces.ts:394-423`
+
+### 7. Cross-Project Queries
+- [ ] **getTracesByIdsForAnyProject()** - `packages/shared/src/server/repositories/traces.ts:1115-1141`
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 6ce77f7ada..8e72e2196c 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -33,11 +33,13 @@ import {
TraceEventType,
traceRecordInsertSchema,
TraceRecordInsertType,
- TraceMtRecordInsertType,
traceRecordReadSchema,
TraceUpsertQueue,
UsageCostType,
validateAndInflateScore,
+ convertObservationToTraceMt,
+ convertTraceToTraceMt,
+ convertScoreToTraceMt,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
@@ -225,7 +227,7 @@ export class IngestionService {
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
finalScoreRecord.trace_id
) {
- const traceMtRecord = this.convertScoreToTraceMt(finalScoreRecord);
+ const traceMtRecord = convertScoreToTraceMt(finalScoreRecord);
this.clickHouseWriter.addToQueue(TableName.TracesMt, traceMtRecord);
}
}
@@ -331,7 +333,7 @@ export class IngestionService {
if (
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true"
) {
- const traceMtRecord = this.convertTraceToTraceMt(finalTraceRecord);
+ const traceMtRecord = convertTraceToTraceMt(finalTraceRecord);
this.clickHouseWriter.addToQueue(TableName.TracesMt, traceMtRecord);
}
@@ -466,7 +468,7 @@ export class IngestionService {
env.LANGFUSE_EXPERIMENT_INSERT_INTO_AGGREGATING_MERGE_TREES === "true" &&
finalObservationRecord.trace_id
) {
- const traceMtRecord = this.convertObservationToTraceMt(finalObservationRecord);
+ const traceMtRecord = convertObservationToTraceMt(finalObservationRecord);
this.clickHouseWriter.addToQueue(TableName.TracesMt, traceMtRecord);
}
}
@@ -519,130 +521,6 @@ export class IngestionService {
return traceRecordInsertSchema.parse(mergedRecord);
}
- private convertTraceToTraceMt(
- traceRecord: TraceRecordInsertType,
- ): TraceMtRecordInsertType {
- return {
- // Identifiers
- project_id: traceRecord.project_id,
- id: traceRecord.id,
- start_time: traceRecord.timestamp,
- end_time: null, // traces don't have end_time, will be null
- name: traceRecord.name || "",
-
- // Metadata properties
- metadata: traceRecord.metadata,
- user_id: traceRecord.user_id || "",
- session_id: traceRecord.session_id || "",
- environment: traceRecord.environment,
- tags: traceRecord.tags,
- version: traceRecord.version,
- release: traceRecord.release,
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: traceRecord.bookmarked,
- public: traceRecord.public,
-
- // Aggregations - empty for now, will be populated by aggregation processes
- observation_ids: [],
- score_ids: [],
- cost_details: {},
- usage_details: {},
-
- // Input/Output
- input: traceRecord.input || "",
- output: traceRecord.output || "",
-
- created_at: traceRecord.created_at,
- updated_at: traceRecord.updated_at,
- event_ts: traceRecord.event_ts,
- };
- }
-
- private convertObservationToTraceMt(
- observationRecord: ObservationRecordInsertType,
- ): TraceMtRecordInsertType {
- return {
- // Identifiers
- project_id: observationRecord.project_id,
- // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
- id: observationRecord.trace_id || "",
- start_time: observationRecord.start_time,
- end_time: observationRecord.end_time || null,
- name: "",
-
- // Metadata properties
- metadata: {},
- user_id: '',
- session_id: '',
- environment: observationRecord.environment,
- tags: [],
- version: null,
- release: null,
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: null,
- public: null,
-
- // Aggregations - include this observation ID
- observation_ids: [observationRecord.id],
- score_ids: [],
- // We can fill the cost details here, but we shouldn't trust them.
- // Only used for verification to estimate how big the double-counting is.
- cost_details: observationRecord.cost_details || {},
- usage_details: observationRecord.usage_details || {},
-
- // Input/Output
- input: "",
- output: "",
-
- created_at: observationRecord.created_at,
- updated_at: observationRecord.updated_at,
- event_ts: observationRecord.event_ts,
- };
- }
-
- private convertScoreToTraceMt(
- scoreRecord: ScoreRecordInsertType,
- ): TraceMtRecordInsertType {
- return {
- // Identifiers
- project_id: scoreRecord.project_id,
- // Use trace_id as the id in traces_mt. Always set given the conditions around calling the function
- id: scoreRecord.trace_id || "",
- start_time: scoreRecord.timestamp,
- end_time: null, // scores don't have end_time
- name: "",
-
- // Metadata properties
- metadata: {},
- user_id: '',
- session_id: '',
- environment: scoreRecord.environment,
- tags: [], // scores don't have tags
- version: null, // scores don't have version
- release: null, // scores don't have release
-
- // UI properties - nullable to prevent absent values being interpreted as overwrites
- bookmarked: null,
- public: null,
-
- // Aggregations - include this score ID
- observation_ids: [],
- score_ids: [scoreRecord.id],
- cost_details: {},
- usage_details: {},
-
- // Input/Output
- input: "", // scores don't have input
- output: "", // scores don't have output
-
- created_at: scoreRecord.created_at,
- updated_at: scoreRecord.updated_at,
- event_ts: scoreRecord.event_ts,
- };
- }
-
private async mergeObservationRecords(params: {
projectId: string;
observationRecords: ObservationRecordInsertType[];
@@ -982,7 +860,8 @@ export class IngestionService {
return result;
}
- private async getClickhouseRecord(params: { // eslint-disable-line no-unused-vars
+ // eslint-disable-next-line no-unused-vars
+ private async getClickhouseRecord(params: {
projectId: string;
entityId: string;
table: TableName.Traces;
@@ -991,7 +870,8 @@ export class IngestionService {
params: Record<string, unknown>;
};
}): Promise<TraceRecordInsertType | null>;
- private async getClickhouseRecord(params: { // eslint-disable-line no-unused-vars, no-dupe-class-members
+ // eslint-disable-next-line no-unused-vars, no-dupe-class-members
+ private async getClickhouseRecord(params: {
projectId: string;
entityId: string;
table: TableName.Scores;
@@ -1000,7 +880,8 @@ export class IngestionService {
params: Record<string, unknown>;
};
}): Promise<ScoreRecordInsertType | null>;
- private async getClickhouseRecord(params: { // eslint-disable-line no-unused-vars, no-dupe-class-members
+ // eslint-disable-next-line no-unused-vars, no-dupe-class-members
+ private async getClickhouseRecord(params: {
projectId: string;
entityId: string;
table: TableName.Observations;
@@ -1009,7 +890,8 @@ export class IngestionService {
params: Record<string, unknown>;
};
}): Promise<ObservationRecordInsertType | null>;
- private async getClickhouseRecord(params: { // eslint-disable-line no-dupe-class-members
+ // eslint-disable-next-line no-dupe-class-members
+ private async getClickhouseRecord(params: {
projectId: string;
entityId: string;
table: TableName;