Skip to content

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

chore: remove Experimental Traces AMT Table Configuration. (#9607)

Valery Meleshkinc32da046def1
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index eb2de9fa26..71139b638f 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -131,38 +131,6 @@ const EnvSchema = z.object({
LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS: z.coerce.number().default(600_000), // 10 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"),
- LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT_SHORT_TERM: z
- .enum(["true", "false"])
- .default("false"),
- LANGFUSE_EXPERIMENT_WHITELISTED_AMT_TABLES: z
- .string()
- .optional()
- .transform((s) =>
- s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
- ),
LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS: z
.string()
.optional()
diff --git a/packages/shared/src/server/clickhouse/measureAndReturn.ts b/packages/shared/src/server/clickhouse/measureAndReturn.ts
index 509f2ad377..ea03cd0e8f 100644
--- a/packages/shared/src/server/clickhouse/measureAndReturn.ts
+++ b/packages/shared/src/server/clickhouse/measureAndReturn.ts
@@ -1,7 +1,5 @@
-import { instrumentAsync, recordDistribution } from "../instrumentation";
import * as opentelemetry from "@opentelemetry/api";
-import { env } from "../../env";
-import { logger } from "../logger";
+import { instrumentAsync } from "../instrumentation";
const executionWrapper = async <T, Y>(
input: T,
@@ -20,16 +18,15 @@ const executionWrapper = async <T, Y>(
};
/**
- * Measures the execution time of two functions and returns the result based on the experiment configuration.
- * This is used to compare the execution of AggregatingMergeTrees with the existing ReplacingMergeTree execution.
+ * Measures the execution time of a query functions and returns the result based on the experiment configuration.
+ * Presently this is but a simple wrapper around single execution, but it is designed to be
+ * extended for A/B testing or canary releases.
*/
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
- minStartTime?: Date;
+ fn: (input: T) => Promise<Y>; // eslint-disable-line no-unused-vars
}): Promise<Y> => {
return instrumentAsync(
{
@@ -37,112 +34,17 @@ export const measureAndReturn = async <T, Y>(args: {
spanKind: opentelemetry.SpanKind.CLIENT,
},
async (currentSpan) => {
- const { input, existingExecution, newExecution, minStartTime } = args;
+ const { input, fn } = args;
- if (
- env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES !==
- "true"
- ) {
- currentSpan.setAttribute(`langfuse.experiment.amts.run`, "disabled");
+ // When we want do to multiple executions for A/B testing or canary releases,
+ // or some other form of a more complex wrapper we used to try-catch
+ // using the wrapper function and fallback to a simple f(input) when it failed.
+ const [[existingResult, _existingDuration]] = // eslint-disable-line no-unused-vars
+ await Promise.all([
+ executionWrapper(input, fn, currentSpan, "existing"),
+ ]);
- // Check for short-term new result experiment
- if (
- env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT_SHORT_TERM === "true" &&
- minStartTime
- ) {
- const thirtyDaysAgo = new Date();
- thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
-
- if (minStartTime >= thirtyDaysAgo) {
- currentSpan.setAttribute(
- `langfuse.experiment.amts.short-term`,
- "true",
- );
- return newExecution(input);
- }
- }
-
- return env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"
- ? newExecution(input)
- : 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(`langfuse.experiment.amts.run`, "sampled-out");
- return existingExecution(input);
- }
-
- currentSpan.setAttribute(`langfuse.experiment.amts.run`, "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(
- "langfuse.experiment.amts.execution-time-difference",
- durationDifference,
- );
-
- recordDistribution(
- "langfuse.experiment.amts.duration_difference_distribution",
- durationDifference,
- {
- operation: args.operationName,
- },
- );
-
- if (
- env.LANGFUSE_EXPERIMENT_ADD_QUERY_RESULT_TO_SPAN_PROJECT_IDS.some(
- (p) => p === args.projectId,
- )
- ) {
- currentSpan?.setAttribute(
- "langfuse.experiment.amts.existing-result",
- JSON.stringify(existingResult),
- );
- currentSpan?.setAttribute(
- "langfuse.experiment.amts.new-result",
- JSON.stringify(newResult),
- );
- }
-
- // Check for short-term new result experiment
- if (
- env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT_SHORT_TERM === "true" &&
- minStartTime
- ) {
- const thirtyDaysAgo = new Date();
- thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
-
- if (minStartTime >= thirtyDaysAgo) {
- currentSpan.setAttribute(
- `langfuse.experiment.amts.short-term`,
- "true",
- );
- return 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);
- }
+ return existingResult;
},
);
};
diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.ts
index 410eb6efbb..0aebf2b37c 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts
@@ -6,7 +6,6 @@ export const clickhouseSearchCondition = (
query?: string,
searchType?: TracingSearchType[],
tablePrefix?: string,
- useTracesAmtCompatMode: boolean = false,
) => {
const prefix = tablePrefix ? `${tablePrefix}.` : "";
@@ -15,11 +14,9 @@ export const clickhouseSearchCondition = (
!searchType || searchType.includes("id")
? `${prefix}id ILIKE {searchString: String} OR t.user_id ILIKE {searchString: String} OR ${prefix}name ILIKE {searchString: String}`
: null,
- searchType && searchType.includes("content") && !useTracesAmtCompatMode
+ searchType && searchType.includes("content")
? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`
- : searchType && searchType.includes("content") && useTracesAmtCompatMode
- ? `finalizeAggregation(${prefix}input) ILIKE {searchString: String} OR finalizeAggregation(${prefix}output) ILIKE {searchString: String}`
- : null,
+ : null,
].filter(Boolean);
return {
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index a499dba31e..a54a7bc48d 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -23,7 +23,7 @@ import {
observationsTableUiColumnDefinitions,
} from "../tableMappings";
import { OrderByState } from "../../interfaces/orderBy";
-import { getTimeframesTracesAMT, getTracesByIds } from "./traces";
+import { getTracesByIds } from "./traces";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import {
convertDateToClickhouseDateTime,
@@ -167,7 +167,7 @@ export const getObservationsForTrace = async <IncludeIO extends boolean>(
created_at,
updated_at,
event_ts
- FROM observations
+ FROM observations
WHERE trace_id = {traceId: String}
AND project_id = {projectId: String}
${timestamp ? `AND start_time >= {traceTimestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
@@ -282,7 +282,7 @@ export const getObservationForTraceIdByName = async ({
created_at,
updated_at,
event_ts
- FROM observations
+ FROM observations
WHERE trace_id = {traceId: String}
AND project_id = {projectId: String}
AND name = {name: String}
@@ -753,7 +753,7 @@ const getObservationsTableInternal = async <T>(
trace_id
) tmp
GROUP BY
- trace_id,
+ trace_id,
observation_id
)`;
@@ -781,11 +781,11 @@ const getObservationsTableInternal = async <T>(
${scoresCte}
SELECT
${selectString}
- FROM observations o
+ FROM observations o
${traceTableFilter.length > 0 || orderByTraces || search.query ? "LEFT JOIN __TRACE_TABLE__ t FINAL ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
${hasScoresFilter ? `LEFT JOIN scores_agg AS s ON s.trace_id = o.trace_id and s.observation_id = o.id` : ""}
WHERE ${appliedObservationsFilter.query}
-
+
${timeFilter && (traceTableFilter.length > 0 || orderByTraces) ? `AND t.timestamp > {tracesTimestampFilter: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
${search.query}
${chOrderBy}
@@ -795,7 +795,6 @@ const getObservationsTableInternal = async <T>(
return measureAndReturn({
operationName: "getObservationsTableInternal",
projectId,
- minStartTime: (timeFilter?.value as Date) || undefined,
input: {
params: {
...appliedScoresFilter.params,
@@ -818,22 +817,11 @@ const getObservationsTableInternal = async <T>(
operation_name: "getObservationsTableInternal",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
return queryClickhouse<T>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- clickhouseConfigs,
- });
- },
- newExecution: async (input) => {
- const traceAmt = getTimeframesTracesAMT(
- (timeFilter?.value as Date) || undefined,
- );
- return queryClickhouse<T>({
- query: query.replace("__TRACE_TABLE__", traceAmt),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
clickhouseConfigs,
});
},
@@ -1225,9 +1213,9 @@ export const getObservationMetricsForPrompts = async (
dateDiff('millisecond', start_time, end_time) AS latency_ms
FROM observations
FINAL
- WHERE (type = 'GENERATION')
- AND (prompt_name IS NOT NULL)
- AND project_id={projectId: String}
+ WHERE (type = 'GENERATION')
+ AND (prompt_name IS NOT NULL)
+ AND project_id={projectId: String}
AND prompt_id IN ({promptIds: Array(String)})
)
SELECT
@@ -1293,9 +1281,9 @@ export const getLatencyAndTotalCostForObservations = async (
id,
cost_details['total'] AS total_cost,
dateDiff('millisecond', start_time, end_time) AS latency_ms
- FROM observations FINAL
- WHERE project_id = {projectId: String}
- AND id IN ({observationIds: Array(String)})
+ FROM observations FINAL
+ WHERE project_id = {projectId: String}
+ AND id IN ({observationIds: Array(String)})
${timestamp ? `AND start_time >= {timestamp: DateTime64(3)}` : ""}
`;
const rows = await queryClickhouse<{
@@ -1337,7 +1325,7 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (
sumMap(cost_details)['total'] AS total_cost,
dateDiff('millisecond', min(start_time), max(end_time)) AS latency_ms
FROM observations FINAL
- WHERE project_id = {projectId: String}
+ WHERE project_id = {projectId: String}
AND trace_id IN ({traceIds: Array(String)})
${timestamp ? `AND start_time >= {timestamp: DateTime64(3)}` : ""}
GROUP BY trace_id
@@ -1378,7 +1366,7 @@ export const getObservationCountsByProjectInCreationInterval = async ({
end: Date;
}) => {
const query = `
- SELECT
+ SELECT
project_id,
count(*) as count
FROM observations
@@ -1414,7 +1402,7 @@ export const getObservationCountOfProjectsSinceCreationDate = async ({
start: Date;
}) => {
const query = `
- SELECT
+ SELECT
count(*) as count
FROM observations
WHERE project_id IN ({projectIds: Array(String)})
@@ -1442,7 +1430,7 @@ export const getTraceIdsForObservations = async (
observationIds: string[],
) => {
const query = `
- SELECT
+ SELECT
trace_id,
id
FROM observations
@@ -1531,14 +1519,7 @@ 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 traceTable = "traces";
const query = `
SELECT
@@ -1586,7 +1567,6 @@ 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 496dd3cea6..9e3e924dfd 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -36,7 +36,6 @@ import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
import { prisma } from "../../db";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
-import { getTimeframesTracesAMT } from "./traces";
import { scoresColumnsTableUiColumnDefinitions } from "../tableMappings/mapScoresColumnsTable";
export const searchExistingAnnotationScore = async (
@@ -217,11 +216,11 @@ export const getScoresForSessions = async <
const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);
const query = `
- select
+ select
${select}
from scores s
WHERE s.project_id = {projectId: String}
- AND s.session_id IN ({sessionIds: Array(String)})
+ AND s.session_id IN ({sessionIds: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -266,11 +265,11 @@ export const getScoresForDatasetRuns = async <
const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);
const query = `
- select
+ select
${select}
from scores s
WHERE s.project_id = {projectId: String}
- AND s.dataset_run_id IN ({runIds: Array(String)})
+ AND s.dataset_run_id IN ({runIds: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -303,7 +302,7 @@ export const getTraceScoresForDatasetRuns = async (
if (datasetRunIds.length === 0) return [];
const query = `
- SELECT
+ SELECT
s.id as id,
s.timestamp as timestamp,
s.project_id as project_id,
@@ -324,11 +323,11 @@ export const getTraceScoresForDatasetRuns = async (
s.created_at as created_at,
s.updated_at as updated_at,
s.event_ts as event_ts,
- s.is_deleted as is_deleted,
+ s.is_deleted as is_deleted,
length(mapKeys(s.metadata)) > 0 AS has_metadata,
dri.dataset_run_id as run_id
- FROM dataset_run_items_rmt dri
- JOIN scores s FINAL ON dri.trace_id = s.trace_id
+ FROM dataset_run_items_rmt dri
+ JOIN scores s FINAL ON dri.trace_id = s.trace_id
AND dri.project_id = s.project_id
WHERE dri.project_id = {projectId: String}
AND dri.dataset_run_id IN {datasetRunIds: Array(String)}
@@ -389,7 +388,7 @@ export const getScoresForTraces = async <
${select}
from scores s
WHERE s.project_id = {projectId: String}
- AND s.trace_id IN ({traceIds: Array(String)})
+ AND s.trace_id IN ({traceIds: Array(String)})
${timestamp ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
@@ -487,7 +486,7 @@ export const getScoresForObservations = async <
.join(", ");
const query = `
- select
+ select
${select}
from scores s
WHERE s.project_id = {projectId: String}
@@ -562,7 +561,7 @@ export const getScoresGroupedByNameSourceType = async ({
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
- select
+ select
s.name as name,
s.source as source,
s.data_type as data_type
@@ -630,7 +629,7 @@ export const getNumericScoresGroupedByName = async (
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
- select
+ select
name as name
from scores s
WHERE s.project_id = {projectId: String}
@@ -949,10 +948,10 @@ const getScoresUiGeneric = async <T>(props: {
scoresFilter.some((f) => f.clickhouseTable === "traces");
const query = `
- SELECT
+ SELECT
${select}
FROM scores s final
- ${performTracesJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
+ ${performTracesJoin ? "LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
WHERE s.project_id = {projectId: String}
${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitions)}
@@ -978,19 +977,11 @@ const getScoresUiGeneric = async <T>(props: {
operation_name: "getScoresUiGeneric",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
return queryClickhouse<T>({
- query: query.replace("__TRACE_TABLE__", "traces"),
+ query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- clickhouseConfigs,
- });
- },
- newExecution: async (input) => {
- return queryClickhouse<T>({
- query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
clickhouseConfigs,
});
},
@@ -1012,7 +1003,7 @@ export const getScoreNames = async (
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
- select
+ select
name,
count(*) as count
from scores s
@@ -1161,7 +1152,7 @@ export const getNumericScoreHistogram = async (
const query = `
select s.value
from scores s
- ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND t.project_id = s.project_id` : ""}
+ ${traceFilter ? `LEFT JOIN traces 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}` : ""}
@@ -1170,16 +1161,9 @@ export const getNumericScoreHistogram = async (
${limit !== undefined ? `limit {limit: Int32}` : ""}
`;
- // 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,
@@ -1193,21 +1177,12 @@ export const getNumericScoreHistogram = async (
projectId,
operation_name: "getNumericScoreHistogram",
},
- timestamp,
- },
- 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);
+ fn: async (input) => {
return queryClickhouse<{ value: number }>({
- query: query.replace("__TRACE_TABLE__", traceAmt),
+ query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1219,7 +1194,7 @@ export const getAggregatedScoresForPrompts = async (
fetchScoreRelation: "observation" | "trace",
) => {
const query = `
- SELECT
+ SELECT
prompt_id,
s.id,
s.name,
@@ -1229,9 +1204,9 @@ export const getAggregatedScoresForPrompts = async (
s.data_type,
s.comment,
length(mapKeys(s.metadata)) > 0 AS has_metadata
- FROM scores s FINAL LEFT JOIN observations o FINAL
- ON o.trace_id = s.trace_id
- AND o.project_id = s.project_id
+ FROM scores s FINAL LEFT JOIN observations o FINAL
+ ON o.trace_id = s.trace_id
+ AND o.project_id = s.project_id
${fetchScoreRelation === "observation" ? "AND o.id = s.observation_id" : ""}
WHERE o.project_id = {projectId: String}
AND s.project_id = {projectId: String}
@@ -1276,7 +1251,7 @@ export const getScoreCountsByProjectInCreationInterval = async ({
end: Date;
}) => {
const query = `
- SELECT
+ SELECT
project_id,
count(*) as count
FROM scores
@@ -1312,7 +1287,7 @@ export const getScoreCountOfProjectsSinceCreationDate = async ({
start: Date;
}) => {
const query = `
- SELECT
+ SELECT
count(*) as count
FROM scores
WHERE project_id IN ({projectIds: Array(String)})
@@ -1353,7 +1328,7 @@ export const getDistinctScoreNames = async (p: {
const query = ` SELECT DISTINCT
name
- FROM scores s
+ FROM scores s
WHERE s.project_id = {projectId: String}
AND s.created_at <= {cutoffCreatedAt: DateTime64(3)}
${scoreTimestampFilter ? `AND s.timestamp >= {filterTimestamp: DateTime64(3)}` : ""}
@@ -1435,14 +1410,8 @@ 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 traceTable = "traces";
const query = ` SELECT
s.id as id,
@@ -1470,8 +1439,8 @@ export const getScoresForPostHog = async function* (
AND s.timestamp >= {minTimestamp: DateTime64(3)}
AND s.timestamp <= {maxTimestamp: DateTime64(3)}
AND (
- s.trace_id IS NOT NULL
- OR s.session_id IS NOT NULL
+ s.trace_id IS NOT NULL
+ OR s.session_id IS NOT NULL
OR s.dataset_run_id IS NOT NULL
)
AND (
@@ -1496,7 +1465,6 @@ 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 1912440c8e..47b7ebca72 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -34,54 +34,6 @@ import { recordDistribution } from "../instrumentation";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";
-// eslint-disable-next-line no-unused-vars
-enum TracesAMTs {
- 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.
- *
- * If LANGFUSE_EXPERIMENT_WHITELISTED_AMT_TABLES is set, we only return timeframes
- * that are whitelisted or fallback to the traces_all_amt.
- *
- * @param fromTimestamp
- */
-export const getTimeframesTracesAMT = (
- fromTimestamp: Date | undefined,
-): TracesAMTs => {
- if (!fromTimestamp) {
- // The TracesAllAMT must always be returned if there is no timestamp.
- console.log("No timestamp provided, returning TracesAllAMT");
- return TracesAMTs.TracesAllAMT;
- }
-
- const now = new Date();
- const diffInDays = Math.floor(
- (now.getTime() - fromTimestamp.getTime()) / (1000 * 60 * 60 * 24),
- );
-
- let selectedTable: TracesAMTs;
- if (diffInDays <= 6) {
- selectedTable = TracesAMTs.Traces7dAMT;
- } else if (diffInDays <= 29) {
- selectedTable = TracesAMTs.Traces30dAMT;
- } else {
- selectedTable = TracesAMTs.TracesAllAMT;
- }
-
- // Check if the selected table is whitelisted, fallback to TracesAllAMT if not
- return env.LANGFUSE_EXPERIMENT_WHITELISTED_AMT_TABLES.length === 0 ||
- env.LANGFUSE_EXPERIMENT_WHITELISTED_AMT_TABLES.includes(selectedTable)
- ? selectedTable
- : TracesAMTs.TracesAllAMT;
-};
-
/**
* Checks if trace exists in clickhouse.
* Additionally, give back the timestamp of the trace as metadata.
@@ -164,7 +116,6 @@ export const checkTraceExistsAndGetTimestamp = async ({
return measureAndReturn({
operationName: "checkTraceExistsAndGetTimestamp",
projectId,
- minStartTime: timestamp ?? exactTimestamp,
input: {
params: {
projectId,
@@ -189,7 +140,7 @@ export const checkTraceExistsAndGetTimestamp = async ({
},
timestamp: timestamp ?? exactTimestamp,
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
${observations_cte}
SELECT
@@ -214,40 +165,7 @@ export const checkTraceExistsAndGetTimestamp = async ({
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- return {
- exists: rows.length > 0,
- timestamp:
- rows.length > 0
- ? parseClickhouseUTCDateTimeFormat(rows[0].timestamp)
- : undefined,
- };
- },
- newExecution: async (input) => {
- const traceAmt = getTimeframesTracesAMT(input.timestamp);
- const query = `
- ${observations_cte}
- SELECT
- t.id as id,
- t.project_id as project_id,
- -- Add a timestamp alias to ensure we can filter on it
- t.start_time as timestamp
- FROM ${traceAmt} 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}
- `;
-
- const rows = await queryClickhouse<{
- id: string;
- project_id: string;
- timestamp: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
return {
@@ -309,7 +227,7 @@ export const getTracesByIds = async (
},
clickhouseConfigs,
},
- existingExecution: (input) => {
+ fn: (input) => {
const query = `
SELECT *
FROM traces
@@ -322,42 +240,7 @@ export const getTracesByIds = async (
return queryClickhouse<TraceRecordReadType>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- 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, experiment_amt: "new" },
+ tags: input.tags,
clickhouseConfigs: input.clickhouseConfigs,
});
},
@@ -376,7 +259,6 @@ export const getTracesBySessionId = async (
const records = await measureAndReturn({
operationName: "getTracesBySessionId",
projectId,
- minStartTime: timestamp,
input: {
params: {
sessionIds,
@@ -394,7 +276,7 @@ export const getTracesBySessionId = async (
},
timestamp,
},
- existingExecution: (input) => {
+ fn: (input) => {
const query = `
SELECT *
FROM traces
@@ -407,38 +289,7 @@ export const getTracesBySessionId = async (
return queryClickhouse<TraceRecordReadType>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: (input) => {
- const traceAmt = getTimeframesTracesAMT(input.timestamp);
- 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,
- start_time as timestamp,
- created_at,
- updated_at
- FROM ${traceAmt} FINAL
- WHERE session_id IN ({sessionIds: Array(String)})
- AND project_id = {projectId: String}
- `;
- return queryClickhouse<TraceRecordReadType>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -471,7 +322,7 @@ export const hasAnyTrace = async (projectId: string) => {
operation_name: "hasAnyTrace",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT 1
FROM traces
@@ -484,25 +335,7 @@ export const hasAnyTrace = async (projectId: string) => {
params: {
projectId: input.projectId,
},
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- 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, experiment_amt: "new" },
+ tags: input.tags,
});
return rows.length > 0;
@@ -520,7 +353,6 @@ export const getTraceCountsByProjectInCreationInterval = async ({
return measureAndReturn({
operationName: "getTraceCountsByProjectInCreationInterval",
projectId: "__CROSS_PROJECT__",
- minStartTime: start,
input: {
params: {
start: convertDateToClickhouseDateTime(start),
@@ -534,7 +366,7 @@ export const getTraceCountsByProjectInCreationInterval = async ({
},
timestamp: start,
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT
project_id,
@@ -549,32 +381,7 @@ export const getTraceCountsByProjectInCreationInterval = async ({
{
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- },
- );
-
- return rows.map((row) => ({
- projectId: row.project_id,
- count: Number(row.count),
- }));
- },
- newExecution: async (input) => {
- const traceAmt = getTimeframesTracesAMT(input.timestamp);
- const query = `
- SELECT
- project_id,
- count(*) as count
- FROM ${traceAmt}
- WHERE created_at >= {start: DateTime64(3)}
- AND created_at < {end: DateTime64(3)}
- GROUP BY project_id
- `;
-
- const rows = await queryClickhouse<{ project_id: string; count: string }>(
- {
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
},
);
@@ -596,7 +403,6 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({
return measureAndReturn({
operationName: "getTraceCountOfProjectsSinceCreationDate",
projectId: "__CROSS_PROJECT__",
- minStartTime: start,
input: {
params: {
projectIds,
@@ -610,7 +416,7 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({
},
timestamp: start,
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT
count(*) as count
@@ -622,25 +428,7 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({
const rows = await queryClickhouse<{ count: string }>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- return Number(rows[0]?.count ?? 0);
- },
- newExecution: async (input) => {
- const traceAmt = getTimeframesTracesAMT(input.timestamp);
- const query = `
- SELECT
- count(*) as count
- FROM ${traceAmt}
- WHERE project_id IN ({projectIds: Array(String)})
- AND created_at >= {start: DateTime64(3)}
- `;
-
- const rows = await queryClickhouse<{ count: string }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
return Number(rows[0]?.count ?? 0);
@@ -675,7 +463,6 @@ export const getTraceById = async ({
const records = await measureAndReturn({
operationName: "getTraceById",
projectId,
- minStartTime: fromTimestamp ?? timestamp,
input: {
params: {
traceId,
@@ -695,7 +482,7 @@ export const getTraceById = async ({
operation_name: "getTraceById",
},
},
- existingExecution: (input) => {
+ fn: (input) => {
const query = `
SELECT
id,
@@ -728,43 +515,7 @@ export const getTraceById = async ({
return queryClickhouse<TraceRecordReadType>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService,
- });
- },
- newExecution: (input) => {
- const query = `
- SELECT
- id,
- anyLast(name) as name,
- anyLast(user_id) as user_id,
- maxMap(metadata) as metadata,
- anyLast(release) as release,
- anyLast(version) as version,
- project_id,
- anyLast(environment) as environment,
- argMaxMerge(public) as public,
- argMaxMerge(bookmarked) as bookmarked,
- groupUniqArrayArray(tags) as tags,
- ${renderingProps.truncated ? `leftUTF8(argMaxMerge(input), ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})` : "argMaxMerge(input)"} as input,
- ${renderingProps.truncated ? `leftUTF8(argMaxMerge(output), ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})` : "argMaxMerge(output)"} as output,
- anyLast(session_id) as session_id,
- 0 as is_deleted,
- min(start_time) as timestamp,
- min(start_time) as created_at,
- max(t.updated_at) as updated_at,
- max(t.updated_at) as event_ts
- FROM traces_all_amt t
- WHERE id = {traceId: String}
- AND project_id = {projectId: String}
- GROUP BY project_id, id
- LIMIT 1
- `;
-
- return queryClickhouse<TraceRecordReadType>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService,
});
},
@@ -803,10 +554,6 @@ export const getTracesGroupedByName = async (
return measureAndReturn({
operationName: "getTracesGroupedByName",
projectId,
- minStartTime: timestampFilter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
projectId,
@@ -820,7 +567,7 @@ export const getTracesGroupedByName = async (
operation_name: "getTracesGroupedByName",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
@@ -842,36 +589,7 @@ export const getTracesGroupedByName = async (
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = timestampFilter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const query = `
- select
- name as name,
- count(*) as count
- from ${traceAmt} t
- WHERE t.project_id = {projectId: String}
- AND t.name IS NOT NULL
- GROUP BY name
- ORDER BY count(*) desc
- LIMIT 1000;
- `;
-
- return queryClickhouse<{
- name: string;
- count: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -902,10 +620,6 @@ export const getTracesGroupedBySessionId = async (
return measureAndReturn({
operationName: "getTracesGroupedBySessionId",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
limit,
@@ -922,7 +636,7 @@ export const getTracesGroupedBySessionId = async (
operation_name: "getTracesGroupedBySessionId",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
@@ -946,38 +660,7 @@ export const getTracesGroupedBySessionId = async (
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const query = `
- select
- session_id as session_id,
- count(*) as count
- from ${traceAmt} t
- WHERE t.project_id = {projectId: String}
- AND t.session_id IS NOT NULL
- AND t.session_id != ''
- ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}
- ${search.query}
- GROUP BY session_id
- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- return queryClickhouse<{
- session_id: string;
- count: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1008,10 +691,6 @@ export const getTracesGroupedByUsers = async (
return measureAndReturn({
operationName: "getTracesGroupedByUsers",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
limit,
@@ -1028,7 +707,7 @@ export const getTracesGroupedByUsers = async (
operation_name: "getTracesGroupedByUsers",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
// We mainly use queries like this to retrieve filter options.
// Therefore, we can skip final as some inaccuracy in count is acceptable.
const query = `
@@ -1052,39 +731,7 @@ export const getTracesGroupedByUsers = async (
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const query = `
- select
- user_id as user,
- count(*) as count
- from ${traceAmt} t
- WHERE t.project_id = {projectId: String}
- AND t.user_id IS NOT NULL
- AND t.user_id != ''
- ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}
- ${search.query}
- GROUP BY user
- ORDER BY count desc
- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- return queryClickhouse<{
- user: string;
- count: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1109,10 +756,6 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
return measureAndReturn({
operationName: "getTracesGroupedByTags",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
projectId,
@@ -1126,7 +769,7 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
operation_name: "getTracesGroupedByTags",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
select distinct(arrayJoin(tags)) as value
from traces t
@@ -1140,31 +783,7 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const query = `
- select distinct(arrayJoin(tags)) as value
- from ${traceAmt} t
- WHERE t.project_id = {projectId: String}
- ${filterRes?.query ? `AND ${filterRes.query}` : ""}
- LIMIT 1000;
- `;
-
- return queryClickhouse<{
- value: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1190,7 +809,7 @@ export const getTracesIdentifierForSession = async (
operation_name: "getTracesIdentifierForSession",
},
},
- existingExecution: (input) => {
+ fn: (input) => {
const query = `
SELECT
id,
@@ -1215,35 +834,7 @@ export const getTracesIdentifierForSession = async (
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: (input) => {
- const query = `
- SELECT
- id,
- user_id,
- name,
- start_time as timestamp,
- project_id,
- environment
- FROM traces_all_amt
- WHERE (project_id = {projectId: String})
- AND (session_id = {sessionId: String})
- ORDER BY start_time ASC
- LIMIT 1 BY id, project_id;
- `;
-
- return queryClickhouse<{
- id: string;
- user_id: string;
- name: string;
- timestamp: string;
- environment: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1273,7 +864,7 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {
projectId,
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
DELETE FROM traces
WHERE project_id = {projectId: String}
@@ -1288,62 +879,6 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {
tags: input.tags,
});
},
- newExecution: async (input) => {
- await Promise.all([
- // Delete from traces
- await commandClickhouse({
- query: `
- DELETE FROM traces
- WHERE project_id = {projectId: String}
- AND id IN ({traceIds: Array(String)});
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_all_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_all_amt
- WHERE project_id = {projectId: String}
- AND id IN ({traceIds: Array(String)});
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_7d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_7d_amt
- WHERE project_id = {projectId: String}
- AND id IN ({traceIds: Array(String)});
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_30d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_30d_amt
- WHERE project_id = {projectId: String}
- AND id IN ({traceIds: Array(String)});
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- ]);
- },
});
};
@@ -1366,7 +901,7 @@ export const deleteTracesOlderThanDays = async (
projectId,
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
DELETE FROM traces
WHERE project_id = {projectId: String}
@@ -1381,62 +916,6 @@ export const deleteTracesOlderThanDays = async (
tags: input.tags,
});
},
- newExecution: async (input) => {
- await Promise.all([
- // Delete from traces
- await commandClickhouse({
- query: `
- DELETE FROM traces
- WHERE project_id = {projectId: String}
- AND timestamp < {cutoffDate: DateTime64(3)};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_all_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_all_amt
- WHERE project_id = {projectId: String}
- AND start_time < {cutoffDate: DateTime64(3)};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_7d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_7d_amt
- WHERE project_id = {projectId: String}
- AND start_time < {cutoffDate: DateTime64(3)};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_30d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_30d_amt
- WHERE project_id = {projectId: String}
- AND start_time < {cutoffDate: DateTime64(3)};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- ]);
- },
});
};
@@ -1455,7 +934,7 @@ export const deleteTracesByProjectId = async (projectId: string) => {
projectId,
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
DELETE FROM traces
WHERE project_id = {projectId: String};
@@ -1469,58 +948,6 @@ export const deleteTracesByProjectId = async (projectId: string) => {
tags: input.tags,
});
},
- newExecution: async (input) => {
- await Promise.all([
- // Delete from traces
- await commandClickhouse({
- query: `
- DELETE FROM traces
- WHERE project_id = {projectId: String};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_all_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_all_amt
- WHERE project_id = {projectId: String};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_7d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_7d_amt
- WHERE project_id = {projectId: String};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- // Delete from traces_30d_amt
- commandClickhouse({
- query: `
- DELETE FROM traces_30d_amt
- WHERE project_id = {projectId: String};
- `,
- params: input.params,
- clickhouseConfigs: {
- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
- },
- tags: input.tags,
- }),
- ]);
- },
});
};
@@ -1538,7 +965,7 @@ export const hasAnyUser = async (projectId: string) => {
operation_name: "hasAnyUser",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT 1
FROM traces
@@ -1553,27 +980,7 @@ export const hasAnyUser = async (projectId: string) => {
params: {
projectId: input.projectId,
},
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- return rows.length > 0;
- },
- newExecution: async (input) => {
- const query = `
- SELECT 1
- FROM traces_all_amt
- WHERE project_id = {projectId: String}
- AND user_id IS NOT NULL
- AND user_id != ''
- LIMIT 1
- `;
-
- const rows = await queryClickhouse<{ 1: number }>({
- query,
- params: {
- projectId: input.projectId,
- },
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
return rows.length > 0;
@@ -1600,10 +1007,6 @@ export const getTotalUserCount = async (
return measureAndReturn({
operationName: "getTotalUserCount",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
...tracesFilterRes.params,
@@ -1617,7 +1020,7 @@ export const getTotalUserCount = async (
operation_name: "getTotalUserCount",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT COUNT(DISTINCT t.user_id) AS totalCount
FROM traces t
@@ -1630,30 +1033,7 @@ export const getTotalUserCount = async (
return queryClickhouse({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const query = `
- SELECT COUNT(DISTINCT t.user_id) AS totalCount
- FROM ${traceAmt} t
- WHERE ${tracesFilterRes.query}
- ${search.query}
- AND t.user_id IS NOT NULL
- AND t.user_id != ''
- `;
-
- return queryClickhouse({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
@@ -1752,10 +1132,6 @@ export const getUserMetrics = async (
return measureAndReturn({
operationName: "getUserMetrics",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "timestamp" && (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
projectId,
@@ -1777,7 +1153,7 @@ export const getUserMetrics = async (
operation_name: "getUserMetrics",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const rows = await queryClickhouse<{
user_id: string;
environment: string;
@@ -1792,45 +1168,7 @@ export const getUserMetrics = async (
}>({
query: query.replaceAll("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- return rows.map((row) => ({
- userId: row.user_id,
- environment: row.environment,
- maxTimestamp: parseClickhouseUTCDateTimeFormat(row.max_timestamp),
- minTimestamp: parseClickhouseUTCDateTimeFormat(row.min_timestamp),
- inputUsage: Number(row.input_usage),
- outputUsage: Number(row.output_usage),
- totalUsage: Number(row.total_usage),
- observationCount: Number(row.obs_count),
- traceCount: Number(row.trace_count),
- totalCost: Number(row.sum_total_cost),
- }));
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- const rows = await queryClickhouse<{
- user_id: string;
- environment: string;
- max_timestamp: string;
- min_timestamp: string;
- input_usage: string;
- output_usage: string;
- total_usage: string;
- obs_count: string;
- trace_count: string;
- sum_total_cost: string;
- }>({
- query: query.replaceAll("__TRACE_TABLE__", traceAmt),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
return rows.map((row) => ({
@@ -1854,9 +1192,7 @@ 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 traceTable = "traces";
const query = `
SELECT
@@ -1870,11 +1206,11 @@ export const getTracesForBlobStorageExport = function (
session_id,
release,
version,
- ${useAMT ? "finalizeAggregation(public)" : "public"} as public,
- ${useAMT ? "finalizeAggregation(bookmarked)" : "bookmarked"} as bookmarked,
+ public as public,
+ bookmarked as bookmarked,
tags,
- ${useAMT ? "finalizeAggregation(input)" : "input"} as input,
- ${useAMT ? "finalizeAggregation(output)" : "output"} as output
+ input as input,
+ output as output
FROM ${traceTable} FINAL
WHERE project_id = {projectId: String}
AND timestamp >= {minTimestamp: DateTime64(3)}
@@ -1893,7 +1229,6 @@ 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,
@@ -1907,8 +1242,7 @@ export const getTracesForPostHog = async function* (
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 traceTable = "traces";
const query = `
WITH observations_agg AS (
@@ -1956,7 +1290,6 @@ 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,
@@ -2020,7 +1353,7 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {
operation_name: "getTracesByIdsForAnyProject",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const query = `
SELECT id, project_id
FROM traces
@@ -2033,28 +1366,7 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {
}>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- });
-
- return records.map((record) => ({
- id: record.id,
- projectId: record.project_id,
- }));
- },
- newExecution: async (input) => {
- // For this query, we need to query all AMT tables as we don't have a specific timestamp
- // We'll use the all AMT table as it contains all data
- const query = `
- SELECT DISTINCT id, project_id
- FROM traces_all_amt
- WHERE id IN ({traceIds: Array(String)})`;
- const records = await queryClickhouse<{
- id: string;
- project_id: string;
- }>({
- query,
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
return records.map((record) => ({
diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.ts
index 985f12437c..aa82595d8b 100644
--- a/packages/shared/src/server/services/sessions-ui-table-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts
@@ -12,7 +12,6 @@ import {
import {
TRACE_TO_OBSERVATIONS_INTERVAL,
queryClickhouse,
- getTimeframesTracesAMT,
} from "../repositories";
export type SessionDataReturnType = {
@@ -133,23 +132,23 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
break;
case "rows":
sqlSelect = `
- session_id,
- max_timestamp,
- min_timestamp,
- trace_ids,
- user_ids,
- trace_count,
+ session_id,
+ max_timestamp,
+ min_timestamp,
+ trace_ids,
+ user_ids,
+ trace_count,
trace_tags,
trace_environment`;
break;
case "metrics":
sqlSelect = `
- session_id,
- max_timestamp,
- min_timestamp,
- trace_ids,
- user_ids,
- trace_count,
+ session_id,
+ max_timestamp,
+ min_timestamp,
+ trace_ids,
+ user_ids,
+ trace_count,
trace_tags,
trace_environment,
total_observations,
@@ -270,7 +269,7 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
string_value,
avg(value) avg_value
FROM scores s FINAL
- WHERE
+ WHERE
project_id = {projectId: String}
${scoresFilterRes ? `AND ${scoresFilterRes.query}` : ""}
GROUP BY
@@ -290,13 +289,13 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
deduplicated_traces AS (
SELECT * EXCEPT input, output, metadata
FROM __TRACE_TABLE__ t
- WHERE t.session_id IS NOT NULL
+ WHERE t.session_id IS NOT NULL
AND t.project_id = {projectId: String}
${singleTraceFilter?.query ? ` AND ${singleTraceFilter.query}` : ""}
LIMIT 1 BY id, project_id
),
deduplicated_observations AS (
- SELECT *
+ SELECT *
FROM observations o
WHERE o.project_id = {projectId: String}
${traceTimestampFilter ? `AND o.start_time >= {observationsStartTime: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
@@ -349,7 +348,7 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
}
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_cost_details)))) as session_input_cost,
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sumMap(o.sum_cost_details)))) as session_output_cost,
- sumMap(o.sum_cost_details)['total'] as session_total_cost,
+ sumMap(o.sum_cost_details)['total'] as session_total_cost,
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_usage_details)))) as session_input_usage,
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sumMap(o.sum_usage_details)))) as session_output_usage,
sumMap(o.sum_usage_details)['total'] as session_total_usage`
@@ -378,11 +377,6 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
return measureAndReturn({
operationName: "getSessionsTableGeneric",
projectId,
- minStartTime: filter?.find(
- (f) =>
- f.column === "min_timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined,
input: {
params: {
projectId,
@@ -407,26 +401,11 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
operation_name: `getSessionsTableGeneric-${select}`,
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
return queryClickhouse<T>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- clickhouseConfigs,
- });
- },
- newExecution: async (input) => {
- // Extract the timestamp from filter for AMT table selection
- const fromTimestamp = filter?.find(
- (f) =>
- f.column === "min_timestamp" &&
- (f.operator === ">=" || f.operator === ">"),
- )?.value as Date | undefined;
- const traceAmt = getTimeframesTracesAMT(fromTimestamp);
- return queryClickhouse<T>({
- query: query.replace("__TRACE_TABLE__", traceAmt),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
clickhouseConfigs,
});
},
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index 47f54f142b..e75ae44cf1 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -21,7 +21,6 @@ import {
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
reduceUsageOrCostDetails,
- getTimeframesTracesAMT,
} from "../repositories";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { TracingSearchType } from "../../interfaces/search";
@@ -350,9 +349,8 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
return measureAndReturn({
operationName: "getTracesTableGeneric",
projectId: props.projectId,
- minStartTime: select !== "metrics" ? timeStampFilter?.value : undefined,
input: props,
- existingExecution: async (props) => {
+ fn: async (props) => {
let sqlSelect: string;
switch (select) {
case "count":
@@ -445,7 +443,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
// In this case, CH is able to read the data only from the latest date from disk and filtering them in memory. No need to read all data e.g. for 1 month from disk.
const query = `
- ${observationsAndScoresCTE}
+ ${observationsAndScoresCTE}
SELECT ${sqlSelect}
-- FINAL is used for non default ordering.
@@ -481,121 +479,11 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
feature: "tracing",
type: "traces-table",
projectId,
- experiment_amt: "original",
operation_name: "getTracesTableGeneric",
},
clickhouseConfigs,
});
- return res;
- },
- newExecution: async () => {
- let sqlSelect: string;
- switch (select) {
- case "count":
- sqlSelect = "uniq(t.id) as count";
- break;
- case "metrics":
- sqlSelect = `
- t.id as id,
- t.project_id as project_id,
- min(t.timestamp) as timestamp,
- max(o.latency_milliseconds) / 1000 as latency,
- anyLast(o.cost_details) as cost_details,
- anyLast(o.usage_details) as usage_details,
- anyLast(o.aggregated_level) as level,
- anyLast(o.error_count) as error_count,
- anyLast(o.warning_count) as warning_count,
- anyLast(o.default_count) as default_count,
- anyLast(o.debug_count) as debug_count,
- anyLast(o.observation_count) as observation_count,
- anyLast(s.scores_avg) as scores_avg,
- anyLast(s.score_categories) as score_categories,
- argMaxMerge(t.public) as public`;
- break;
- case "rows":
- sqlSelect = `
- t.id as id,
- t.project_id as project_id,
- min(t.timestamp) as timestamp,
- groupUniqArrayArray(t.tags) as tags,
- argMaxMerge(t.bookmarked) as bookmarked,
- anyLast(t.name) as name,
- anyLast(t.release) as release,
- anyLast(t.version) as version,
- anyLast(t.user_id) as user_id,
- anyLast(t.environment) as environment,
- anyLast(t.session_id) as session_id,
- argMaxMerge(t.public) as public`;
- break;
- case "identifiers":
- sqlSelect = `
- t.id as id,
- t.project_id as projectId,
- min(t.timestamp) as timestamp`;
- break;
- default:
- throw new Error(`Unknown select type: ${select}`);
- }
-
- const search = clickhouseSearchCondition(
- searchQuery,
- searchType,
- "t",
- true,
- );
-
- const chOrderBy = orderByToClickhouseSql(
- [orderBy ?? null].flat(),
- tracesTableUiColumnDefinitions,
- true,
- );
-
- const tracesAmt =
- select === "metrics"
- ? "traces_all_amt"
- : getTimeframesTracesAMT(timeStampFilter?.value);
-
- const query = `
- ${observationsAndScoresCTE}
-
- SELECT ${sqlSelect}
- FROM ${tracesAmt} t
- ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}
- ${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}
- WHERE t.project_id = {projectId: String}
- ${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}
- ${search.query}
- ${select !== "count" ? "GROUP BY project_id, id" : ""}
- ${chOrderBy}
- ${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- const res = await queryClickhouse<
- SelectReturnTypeMap[keyof SelectReturnTypeMap]
- >({
- query: query,
- params: {
- limit: limit,
- offset: limit && page ? limit * page : 0,
- traceTimestamp: timeStampFilter?.value.getTime(),
- projectId: projectId,
- ...tracesFilterRes.params,
- ...observationFilterRes.params,
- ...scoresFilterRes.params,
- ...search.params,
- },
- tags: {
- ...(props.tags ?? {}),
- feature: "tracing",
- type: "traces-table",
- projectId,
- experiment_amt: "new",
- operation_name: `getTracesTableGeneric-${select}`,
- },
- clickhouseConfigs,
- });
-
return res;
},
});
diff --git a/packages/shared/src/server/tableMappings/mapTracesTable.ts b/packages/shared/src/server/tableMappings/mapTracesTable.ts
index 4e4bbae4e2..7f7e3f4013 100644
--- a/packages/shared/src/server/tableMappings/mapTracesTable.ts
+++ b/packages/shared/src/server/tableMappings/mapTracesTable.ts
@@ -1,15 +1,11 @@
import { UiColumnMappings } from "../../tableDefinitions";
-import { env } from "../../env";
export const tracesTableUiColumnDefinitions: UiColumnMappings = [
{
uiTableName: "⭐️",
uiTableId: "bookmarked",
clickhouseTableName: "traces",
- clickhouseSelect:
- env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"
- ? "finalizeAggregation(t.bookmarked)"
- : "t.bookmarked",
+ clickhouseSelect: "t.bookmarked",
},
{
uiTableName: "Level",
diff --git a/web/src/features/public-api/server/dailyMetrics.ts b/web/src/features/public-api/server/dailyMetrics.ts
index 04e467a1f1..eb7325d779 100644
--- a/web/src/features/public-api/server/dailyMetrics.ts
+++ b/web/src/features/public-api/server/dailyMetrics.ts
@@ -4,7 +4,6 @@ import {
queryClickhouse,
TRACE_TO_OBSERVATIONS_INTERVAL,
type DateTimeFilter,
- getTimeframesTracesAMT,
measureAndReturn,
} from "@langfuse/shared/src/server";
@@ -52,7 +51,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
sumMap(o.usage_details)['total'] as totalUsage,
sum(coalesce(o.total_cost, 0)) as totalCost
FROM observations o FINAL ${hasNonTimestampsFilter ? " LEFT JOIN __TRACE_TABLE__ t FINAL on o.trace_id = t.id AND o.project_id = t.project_id" : ""}
- WHERE o.project_id = {projectId: String}
+ WHERE o.project_id = {projectId: String}
${hasNonTimestampsFilter ? `AND t.project_id = {projectId: String} AND ${appliedFilter.query}` : ""}
${timeFilter ? `AND start_time >= {cteTimeFilter: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
GROUP BY date, model
@@ -81,14 +80,14 @@ export const generateDailyMetrics = async (props: QueryType) => {
${hasTracesFilter ? `AND ${appliedTracesFilter.query}` : ""}
GROUP BY date
)
-
+
SELECT
COALESCE(dmu.date, tu.date) as date,
COALESCE(tu.countTraces, 0) as countTraces,
COALESCE(dmu.countObservations, 0) as countObservations,
COALESCE(dmu.totalCost, 0) as totalCost,
- dmu.daily_usage_tuple as usage
- FROM daily_model_usage dmu
+ dmu.daily_usage_tuple as usage
+ FROM daily_model_usage dmu
FULL OUTER JOIN trace_usage tu ON dmu.date = tu.date
ORDER BY date DESC
${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
@@ -101,7 +100,6 @@ export const generateDailyMetrics = async (props: QueryType) => {
return measureAndReturn({
operationName: "generateDailyMetrics",
projectId: props.projectId,
- minStartTime: timestamp,
input: {
params: {
...appliedTracesFilter.params,
@@ -126,7 +124,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
},
timestamp,
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const result = await queryClickhouse<{
date: string;
countTraces: number;
@@ -136,40 +134,7 @@ export const generateDailyMetrics = async (props: QueryType) => {
}>({
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" },
+ tags: input.tags,
clickhouseConfigs: {
request_timeout: 60_000, // Use 1 minute timeout for daily metrics
},
@@ -217,7 +182,6 @@ export const getDailyMetricsCount = async (props: QueryType) => {
return measureAndReturn({
operationName: "getDailyMetricsCount",
projectId: props.projectId,
- minStartTime: timestamp,
input: {
params: { ...appliedFilter.params, projectId: props.projectId },
tags: {
@@ -229,20 +193,11 @@ export const getDailyMetricsCount = async (props: QueryType) => {
},
timestamp,
},
- existingExecution: async (input) => {
+ fn: 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" },
+ tags: input.tags,
});
return records.map((record) => Number(record.count)).shift();
},
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index 695e86159a..ef1656642a 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -97,20 +97,11 @@ export const generateObservationsForPublicApi = async (props: QueryType) => {
operation_name: "generateObservationsForPublicApi",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const result = await queryClickhouse<ObservationRecordReadType>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
- return result.map((r) => convertObservation(r));
- },
- newExecution: async (input) => {
- const result = await queryClickhouse<ObservationRecordReadType>({
- query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
return result.map((r) => convertObservation(r));
@@ -144,20 +135,11 @@ export const getObservationsCountForPublicApi = async (props: QueryType) => {
operation_name: "getObservationsCountForPublicApi",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const records = await queryClickhouse<{ count: string }>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
- return records.map((record) => Number(record.count)).shift();
- },
- newExecution: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
return records.map((record) => Number(record.count)).shift();
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index c45f2beaa6..bb41048333 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -70,7 +70,7 @@ export const _handleGenerateScoresForPublicApi = async ({
s.session_id as session_id,
s.dataset_run_id as dataset_run_id
FROM
- scores s
+ scores s
LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id
AND s.project_id = t.project_id
WHERE
@@ -124,7 +124,7 @@ export const _handleGenerateScoresForPublicApi = async ({
operation_name: "_handleGenerateScoresForPublicApi",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const records = await queryClickhouse<
ScoreRecordReadType & {
tags: string[];
@@ -134,33 +134,7 @@ export const _handleGenerateScoresForPublicApi = async ({
>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
-
- return records.map((record) => ({
- ...convertToScore(record),
- trace:
- record.trace_id !== null
- ? {
- userId: record.user_id,
- tags: record.tags,
- environment: record.trace_environment,
- }
- : null,
- }));
- },
- newExecution: async (input) => {
- const records = await queryClickhouse<
- ScoreRecordReadType & {
- tags: string[];
- user_id: string;
- trace_environment: string;
- }
- >({
- query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
@@ -200,7 +174,7 @@ export const _handleGetScoresCountForPublicApi = async ({
SELECT
count() as count
FROM
- scores s
+ scores s
LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id
AND s.project_id = t.project_id
WHERE
@@ -244,20 +218,11 @@ export const _handleGetScoresCountForPublicApi = async ({
operation_name: "_handleGetScoresCountForPublicApi",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const records = await queryClickhouse<{ count: string }>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
- return records.map((record) => Number(record.count)).shift();
- },
- newExecution: async (input) => {
- const records = await queryClickhouse<{ count: string }>({
- query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
- params: input.params,
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
return records.map((record) => Number(record.count)).shift();
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 474ee37808..b76681851e 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -8,7 +8,6 @@ import {
type DateTimeFilter,
convertClickhouseToDomain,
type TraceRecordReadType,
- getTimeframesTracesAMT,
measureAndReturn,
FilterList,
tracesTableUiColumnDefinitions,
@@ -155,7 +154,6 @@ export const generateTracesForPublicApi = async ({
const result = await measureAndReturn({
operationName: "getTracesForPublicApi",
projectId: props.projectId,
- minStartTime: timeFilter?.value,
input: {
params: {
...appliedEnvironmentFilter.params,
@@ -181,7 +179,7 @@ export const generateTracesForPublicApi = async ({
fromTimestamp: timeFilter?.value ?? undefined,
preferredClickhouseService: "ReadOnly",
},
- existingExecution: (input) => {
+ fn: (input) => {
// If user provides an order we prefer it or fallback to timestamp as the default.
// In both cases we append a t.event_ts desc order to pick the latest event in case of duplicates
// if we want to use a skip index.
@@ -241,68 +239,7 @@ export const generateTracesForPublicApi = async ({
>({
query,
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
- },
- newExecution: (input) => {
- const tracesAmt = getTimeframesTracesAMT(input.fromTimestamp);
-
- // If user provides an order we prefer it or fallback to timestamp as the default.
- const chOrderBy =
- orderByToClickhouseSql(orderBy || [], orderByColumns, true) ||
- "ORDER BY timestamp desc";
-
- 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,
- min(t.start_time) as timestamp,
- anyLast(t.name) as name,
- anyLast(t.environment) as environment,
- anyLast(t.session_id) as session_id,
- anyLast(t.user_id) as user_id,
- anyLast(t.release) as release,
- anyLast(t.version) as version,
- argMaxMerge(t.bookmarked) as bookmarked,
- argMaxMerge(t.public) as public,
- groupUniqArrayArray(t.tags) as tags,
- min(t.created_at) as created_at,
- max(t.updated_at) as updated_at
- -- IO fields (conditional)
- ${includeIO ? ", argMaxMerge(t.input) as input, argMaxMerge(t.output) as output, maxMap(t.metadata) as metadata" : ""}
- -- Scores (conditional)
- ${includeScores ? ", groupUniqArrayArray(s.score_ids) as scores" : ""}
- -- Observations (conditional)
- ${includeObservations ? ", groupUniqArrayArray(o.observation_ids) as observations" : ""}
- -- Metrics (conditional)
- ${includeMetrics ? ", COALESCE(anyLast(o.latency_milliseconds) / 1000, 0) as latency, COALESCE(anyLast(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}` : ""}
- GROUP BY project_id, id
- ${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, experiment_amt: "new" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
},
@@ -349,7 +286,6 @@ export const getTracesCountForPublicApi = async ({
return measureAndReturn({
operationName: "getTracesCountForPublicApi",
projectId: props.projectId,
- minStartTime: timestamp,
input: {
params: { ...appliedFilter.params, projectId: props.projectId },
tags: {
@@ -361,21 +297,11 @@ export const getTracesCountForPublicApi = async ({
},
timestamp,
},
- existingExecution: async (input) => {
+ fn: async (input) => {
const records = await queryClickhouse<{ count: string }>({
query: query.replace("__TRACE_TABLE__", "traces"),
params: input.params,
- tags: { ...input.tags, experiment_amt: "original" },
- preferredClickhouseService: "ReadOnly",
- });
- 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" },
+ tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
return records.map((record) => Number(record.count)).shift();
diff --git a/web/src/features/query/server/queryExecutor.ts b/web/src/features/query/server/queryExecutor.ts
index 07db0d284f..c76b78511d 100644
--- a/web/src/features/query/server/queryExecutor.ts
+++ b/web/src/features/query/server/queryExecutor.ts
@@ -1,8 +1,4 @@
-import {
- queryClickhouse,
- measureAndReturn,
- getTimeframesTracesAMT,
-} from "@langfuse/shared/src/server";
+import { queryClickhouse, measureAndReturn } from "@langfuse/shared/src/server";
import { QueryBuilder } from "@/src/features/query/server/queryBuilder";
import { type QueryType } from "@/src/features/query/types";
@@ -48,7 +44,6 @@ export async function executeQuery(
return measureAndReturn({
operationName: "executeQuery",
projectId,
- minStartTime: new Date(query.fromTimestamp),
input: {
query: compiledQuery,
params: parameters,
@@ -61,7 +56,7 @@ export async function executeQuery(
operation_name: "executeQuery",
},
},
- existingExecution: async (input) => {
+ fn: async (input) => {
return queryClickhouse<Record<string, unknown>>({
query: input.query,
params: input.params,
@@ -70,20 +65,7 @@ export async function executeQuery(
date_time_output_format: "iso",
},
},
- tags: { ...input.tags, experiment_amt: "original" },
- });
- },
- newExecution: async (input) => {
- const traceTable = getTimeframesTracesAMT(new Date(input.fromTimestamp));
- return queryClickhouse<Record<string, unknown>>({
- query: input.query.replaceAll("traces", traceTable),
- params: input.params,
- clickhouseConfigs: {
- clickhouse_settings: {
- date_time_output_format: "iso",
- },
- },
- tags: { ...input.tags, experiment_amt: "new" },
+ tags: input.tags,
});
},
});
diff --git a/web/src/pages/api/public/health.ts b/web/src/pages/api/public/health.ts
index a70fda7404..19cc5abc72 100644
--- a/web/src/pages/api/public/health.ts
+++ b/web/src/pages/api/public/health.ts
@@ -44,7 +44,7 @@ export default async function handler(
input: {
now: convertDateToClickhouseDateTime(now),
},
- existingExecution: async (input: { now: string }) => {
+ fn: async (input: { now: string }) => {
return queryClickhouse<{ id: string }>({
query: `
SELECT id
@@ -57,24 +57,6 @@ export default async function handler(
tags: {
feature: "health-check",
type: "trace",
- experiment_amt: "original",
- },
- });
- },
- newExecution: async (input: { now: string }) => {
- return queryClickhouse<{ id: string }>({
- query: `
- SELECT id
- FROM traces_7d_amt
- WHERE start_time <= {now: DateTime64(3)}
- AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE
- LIMIT 1
- `,
- params: input,
- tags: {
- feature: "health-check",
- type: "trace",
- experiment_amt: "new",
},
});
},
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 1a84f9fa40..3cbe1b7a6f 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -2293,11 +2293,11 @@ async function getClickhouseRecord<T extends TableName>(
version as version,
project_id,
environment,
- finalizeAggregation(public) as public,
- finalizeAggregation(bookmarked) as bookmarked,
+ public as public,
+ bookmarked as bookmarked,
tags,
- finalizeAggregation(input) as input,
- finalizeAggregation(output) as output,
+ input as input,
+ output as output,
session_id as session_id,
0 as is_deleted,
start_time as timestamp,