Skip to content

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

chore: reduce use of FINAL in clickhouse queries (#4233)

Steffen Schmitz8c2f8e6247ee
diff --git a/packages/shared/src/interfaces/filters.ts b/packages/shared/src/interfaces/filters.ts
index 056bad0dcb..9a136e900a 100644
--- a/packages/shared/src/interfaces/filters.ts
+++ b/packages/shared/src/interfaces/filters.ts
@@ -15,6 +15,7 @@ export const filterOperators = {
],
numberObject: ["=", ">", "<", ">=", "<="],
boolean: ["=", "<>"],
+ null: ["is null", "is not null"],
} as const;
export const timeFilter = z.object({
@@ -68,6 +69,12 @@ export const booleanFilter = z.object({
operator: z.enum(filterOperators.boolean),
value: z.boolean(),
});
+export const nullFilter = z.object({
+ type: z.literal("null"),
+ column: z.string(),
+ operator: z.enum(filterOperators.null),
+ value: z.literal(""),
+});
export const singleFilter = z.discriminatedUnion("type", [
timeFilter,
stringFilter,
@@ -77,4 +84,5 @@ export const singleFilter = z.discriminatedUnion("type", [
stringObjectFilter,
numberObjectFilter,
booleanFilter,
+ nullFilter,
]);
diff --git a/packages/shared/src/server/filterToPrisma.ts b/packages/shared/src/server/filterToPrisma.ts
index 826cb73ec2..ebe7a4359c 100644
--- a/packages/shared/src/server/filterToPrisma.ts
+++ b/packages/shared/src/server/filterToPrisma.ts
@@ -106,10 +106,12 @@ export function tableColumnsToSqlFilter(
", ",
)}] `;
break;
-
case "boolean":
valuePrisma = Prisma.sql`${filter.value}`;
break;
+ case "null":
+ valuePrisma = Prisma.sql``;
+ break;
}
const jsonKeyPrisma =
filter.type === "stringObject" || filter.type === "numberObject"
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.ts
index 4e09ddf894..ea5c923920 100644
--- a/packages/shared/src/server/repositories/dashboards.ts
+++ b/packages/shared/src/server/repositories/dashboards.ts
@@ -56,6 +56,7 @@ export const getObservationsCostGroupedByName = async (
const appliedFilter = chFilter.apply();
const hasTraceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+ // TODO: Validate whether we can filter traces on timestamp here.
const query = `
SELECT
@@ -100,6 +101,7 @@ export const getScoreAggregate = async (
const chFilterApplied = chFilter.apply();
const hasTraceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+ // TODO: Validate whether we can filter traces on timestamp here.
const query = `
SELECT
@@ -254,7 +256,8 @@ export const getDistinctModels = async (
) as DateTimeFilter | undefined)
: undefined;
- const query = `
+ // No need for final as duplicates are caught by distinct anyway.
+ const query = `
SELECT distinct(provided_model_name) as model
FROM observations o
${tracesFilter ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
@@ -289,6 +292,7 @@ export const getScoresAggregateOverTime = async (
const appliedFilter = chFilter.apply();
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+ // TODO: Validate whether we can filter traces on timestamp here.
const query = `
SELECT
@@ -398,11 +402,12 @@ export const getObservationLatencies = async (
const appliedFilter = chFilter.apply();
+ // Skipping FINAL here, as the quantiles are approximate to begin with.
const query = `
SELECT
- quantilesExactLow(0.5, 0.9, 0.95, 0.99)(date_diff('milliseconds', o.start_time, o.end_time)) as quantiles,
+ quantiles(0.5, 0.9, 0.95, 0.99)(date_diff('milliseconds', o.start_time, o.end_time)) as quantiles,
name
- FROM observations o FINAL
+ FROM observations o
${chFilter.find((f) => f.clickhouseTable === "traces") ? "LEFT JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
@@ -441,14 +446,15 @@ export const getTracesLatencies = async (
(f.operator === ">=" || f.operator === ">"),
) as DateTimeFilter | undefined;
+ // Skipping FINAL here, as the quantiles are approximate to begin with.
const query = `
WITH trace_latencies as (
select o.trace_id,
t.name,
o.project_id,
date_diff('milliseconds', min(o.start_time), coalesce(max(o.end_time), max(o.start_time))) as duration
- FROM traces t FINAL
- JOIN observations o FINAL
+ FROM traces t
+ JOIN observations o
ON o.trace_id = t.id AND o.project_id = t.project_id
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
@@ -457,7 +463,7 @@ export const getTracesLatencies = async (
)
SELECT
- quantilesExactLow(0.5, 0.9, 0.95, 0.99)(duration) as quantiles,
+ quantiles(0.5, 0.9, 0.95, 0.99)(duration) as quantiles,
name
FROM trace_latencies
GROUP BY name
@@ -497,12 +503,13 @@ export const getModelLatenciesOverTime = async (
const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");
+ // Skipping FINAL here, as the quantiles are approximate to begin with.
const query = `
SELECT
${selectTimeseriesColumn(groupBy, "o.start_time", "start_time_bucket")},
provided_model_name,
- quantilesExactLow(0.5, 0.75, 0.9, 0.95, 0.99)(date_diff('milliseconds', o.start_time, o.end_time)) as quantiles
- FROM observations o FINAL
+ quantiles(0.5, 0.75, 0.9, 0.95, 0.99)(date_diff('milliseconds', o.start_time, o.end_time)) as quantiles
+ FROM observations o
${traceFilter ? "JOIN traces t ON o.trace_id = t.id AND o.project_id = t.project_id" : ""}
WHERE project_id = {projectId: String}
AND ${appliedFilter.query}
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 2558a1fb69..fc559e7a96 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -26,11 +26,15 @@ import {
convertObservation,
} from "./observations_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
-import { OBSERVATIONS_TO_TRACE_INTERVAL } from "./constants";
+import {
+ OBSERVATIONS_TO_TRACE_INTERVAL,
+ TRACE_TO_OBSERVATIONS_INTERVAL,
+} from "./constants";
export const getObservationsViewForTrace = async (
traceId: string,
projectId: string,
+ timestamp?: Date,
fetchWithInputOutput: boolean = false,
) => {
const query = `
@@ -66,11 +70,18 @@ export const getObservationsViewForTrace = async (
FROM observations
WHERE trace_id = {traceId: String}
AND project_id = {projectId: String}
+ ${timestamp ? `AND start_time >= {traceTimestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
ORDER BY event_ts DESC
LIMIT 1 BY id, project_id`;
const records = await queryClickhouse<ObservationRecordReadType>({
query,
- params: { traceId, projectId },
+ params: {
+ traceId,
+ projectId,
+ ...(timestamp
+ ? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
+ },
});
return await Promise.all(
@@ -113,7 +124,11 @@ export const getObservationById = async (
created_at,
updated_at,
event_ts
- FROM observations WHERE id = {id: String} AND project_id = {projectId: String} ORDER BY event_ts desc LIMIT 1 by id, project_id`;
+ FROM observations
+ WHERE id = {id: String}
+ AND project_id = {projectId: String}
+ ORDER BY event_ts desc
+ LIMIT 1 by id, project_id`;
const records = await queryClickhouse<ObservationRecordReadType>({
query,
params: { id, projectId },
@@ -454,17 +469,17 @@ export const getObservationsGroupedByModel = async (
const appliedObservationsFilter = observationsFilter.apply();
+ // 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
- o.provided_model_name as name
- FROM observations o FINAL
+ SELECT o.provided_model_name as name
+ FROM observations o
WHERE ${appliedObservationsFilter.query}
AND o.type = 'GENERATION'
GROUP BY o.provided_model_name
ORDER BY count() DESC
LIMIT 1000;
- `;
+ `;
const res = await queryClickhouse<{ name: string }>({
query,
@@ -498,17 +513,17 @@ export const getObservationsGroupedByName = async (
const appliedObservationsFilter = observationsFilter.apply();
+ // 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
- o.name as name
- FROM observations o FINAL
+ SELECT o.name as name
+ FROM observations o
WHERE ${appliedObservationsFilter.query}
AND o.type = 'GENERATION'
GROUP BY o.name
ORDER BY count() DESC
LIMIT 1000;
- `;
+ `;
const res = await queryClickhouse<{ name: string }>({
query,
@@ -542,10 +557,11 @@ export const getObservationsGroupedByPromptName = async (
const appliedObservationsFilter = observationsFilter.apply();
+ // 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
- o.prompt_id as id
- FROM observations o FINAL
+ SELECT o.prompt_id as id
+ FROM observations o
WHERE ${appliedObservationsFilter.query}
AND o.type = 'GENERATION'
AND o.prompt_id IS NOT NULL
@@ -588,13 +604,20 @@ export const getCostForTraces = async (
projectId: string,
traceIds: string[],
) => {
+ // Wrapping the query in a CTE allows us to skip FINAL which allows Clickhouse to use skip indexes.
const query = `
- SELECT
- sum(o.total_cost) as total_cost
- FROM observations o FINAL
- WHERE o.project_id = {projectId: String}
- AND o.trace_id IN ({traceIds: Array(String)});
- `;
+ WITH selected_observations AS (
+ SELECT o.total_cost as total_cost
+ FROM observations o
+ WHERE o.project_id = {projectId: String}
+ AND o.trace_id IN ({traceIds: Array(String)})
+ ORDER BY o.event_ts DESC
+ LIMIT 1 BY o.id, o.project_id
+ )
+
+ SELECT sum(total_cost) as total_cost
+ FROM selected_observations
+ `;
const res = await queryClickhouse<{ total_cost: string }>({
query,
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 92cbb66768..418d7b6aa3 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -18,6 +18,8 @@ import {
} from "../../tableDefinitions";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { convertToScore } from "./scores_converters";
+import { SCORE_TO_TRACE_OBSERVATIONS_INTERVAL } from "./constants";
+import { convertDateToClickhouseDateTime } from "../clickhouse/client";
export type FetchScoresReturnType = {
id: string;
@@ -53,7 +55,7 @@ export const searchExistingAnnotationScore = async (
}
const query = `
SELECT *
- FROM scores s FINAL
+ FROM scores s
WHERE s.project_id = {projectId: String}
AND s.source = 'ANNOTATION'
AND s.trace_id = {traceId: String}
@@ -64,6 +66,7 @@ export const searchExistingAnnotationScore = async (
${configId ? `OR s.config_id = {configId: String}` : ""}
)
ORDER BY s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
LIMIT 1
`;
@@ -87,11 +90,12 @@ export const getScoreById = async (
) => {
const query = `
SELECT *
- FROM scores s FINAL
+ FROM scores s
WHERE s.project_id = {projectId: String}
AND s.id = {scoreId: String}
AND s.source = {source: String}
ORDER BY s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
LIMIT 1
`;
@@ -124,6 +128,7 @@ export const upsertScore = async (score: Partial<FetchScoresReturnType>) => {
export const getScoresForTraces = async (
projectId: string,
traceIds: string[],
+ timestamp?: Date,
limit?: number,
offset?: number,
) => {
@@ -132,19 +137,23 @@ export const getScoresForTraces = async (
*
from scores s
WHERE s.project_id = {projectId: String}
- AND s.trace_id IN ({traceIds: Array(String)})
- ORDER BY event_ts DESC
- LIMIT 1 BY id, project_id
+ 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
${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
`;
const rows = await queryClickhouse<FetchScoresReturnType>({
query: query,
params: {
- projectId: projectId,
- traceIds: traceIds,
- limit: limit,
- offset: offset,
+ projectId,
+ traceIds,
+ limit,
+ offset,
+ ...(timestamp
+ ? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
},
});
@@ -160,9 +169,11 @@ export const getScoresForObservations = async (
const query = `
select
*
- from scores s final
+ from scores s
WHERE s.project_id = {projectId: String}
AND s.observation_id IN ({observationIds: Array(String)})
+ ORDER BY s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
`;
@@ -180,12 +191,14 @@ export const getScoresForObservations = async (
};
export const getScoresGroupedByNameSourceType = async (projectId: string) => {
+ // 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
name,
source,
data_type
- from scores s final
+ from scores s
WHERE s.project_id = {projectId: String}
GROUP BY name, source, data_type
ORDER BY count() desc
@@ -229,10 +242,12 @@ export const getScoresGroupedByName = async (
? new FilterList(chFilter).apply()
: undefined;
+ // 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
name as name
- from scores s final
+ from scores s
WHERE s.project_id = {projectId: String}
AND has(['NUMERIC', 'BOOLEAN'], s.data_type)
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
@@ -378,11 +393,14 @@ export const getScoresUiGeneric = async <T>(props: {
const scoresFilterRes = scoresFilter.apply();
+ // TODO: Can we realistically apply a traces time filter here? Is an order by event_ts a risk?
const query = `
SELECT
${select}
FROM scores s final
- LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id
+ 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)}
@@ -414,11 +432,13 @@ export const getScoreNames = async (
);
const timestampFilterRes = chFilter.apply();
+ // 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
name,
count(*) as count
- from scores s final
+ from scores s
WHERE s.project_id = {projectId: String}
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
GROUP BY name
@@ -488,9 +508,11 @@ export const getNumericScoreHistogram = async (
const query = `
select s.value
- from scores s final
+ from scores s
WHERE s.project_id = {projectId: String}
${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
+ ORDER BY s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
${limit !== undefined ? `limit {limit: Int32}` : ""}
`;
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 4c04ca26b0..ccc0626d56 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -199,55 +199,52 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
const search = clickhouseSearchCondition(searchQuery);
const query = `
- WITH observations_stats AS (
- SELECT
- COUNT(*) AS observation_count,
- sumMap(usage_details) as usage_details,
- SUM(total_cost) AS total_cost,
- date_diff('milliseconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,
- multiIf(
- arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',
- arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',
- arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',
- 'DEBUG'
- ) AS level,
- sumMap(cost_details) as cost_details,
- trace_id,
- project_id
- FROM
- observations final
- WHERE ${observationFilterRes.query}
-
- group by trace_id, project_id
-),
-
- scores_avg AS (SELECT project_id,
- trace_id,
- groupArray(tuple(name, avg_value)) AS "scores_avg"
- FROM (
- SELECT project_id,
- trace_id,
- name,
- avg(value) avg_value
- FROM scores final
- WHERE ${scoresFilterRes.query}
- GROUP BY project_id,
- trace_id,
- name
- ) tmp
- GROUP BY project_id,
- trace_id)
- select
- ${select}
- from traces t final
- left join observations_stats os on os.project_id = t.project_id and os.trace_id = t.id
- left join scores_avg s on s.project_id = t.project_id and s.trace_id = t.id
-
- WHERE ${tracesFilterRes.query}
- ${search.query}
- ${orderByToClickhouseSql(orderBy ?? null, tracesTableUiColumnDefinitions)}
- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
+ WITH observations_stats AS (
+ SELECT
+ COUNT(*) AS observation_count,
+ sumMap(usage_details) as usage_details,
+ SUM(total_cost) AS total_cost,
+ date_diff('milliseconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds,
+ multiIf(
+ arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR',
+ arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING',
+ arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT',
+ 'DEBUG'
+ ) AS level,
+ sumMap(cost_details) as cost_details,
+ trace_id,
+ project_id
+ FROM observations FINAL
+ WHERE ${observationFilterRes.query}
+ GROUP BY trace_id, project_id
+ ),
+ scores_avg AS (
+ SELECT
+ project_id,
+ trace_id,
+ groupArray(tuple(name, avg_value)) AS "scores_avg"
+ FROM (
+ SELECT project_id,
+ trace_id,
+ name,
+ avg(value) avg_value
+ FROM scores final
+ WHERE ${scoresFilterRes.query}
+ GROUP BY project_id,
+ trace_id,
+ name
+ ) tmp
+ GROUP BY project_id, trace_id
+ )
+ SELECT ${select}
+ FROM traces t final
+ LEFT JOIN observations_stats os on os.project_id = t.project_id and os.trace_id = t.id
+ LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id
+ WHERE ${tracesFilterRes.query}
+ ${search.query}
+ ${orderByToClickhouseSql(orderBy ?? null, tracesTableUiColumnDefinitions)}
+ ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
const res = await queryClickhouse<T>({
query: query,
@@ -300,9 +297,10 @@ export const getTracesByIds = async (
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;`;
+ 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: {
@@ -326,7 +324,8 @@ export const getTraceByIdOrThrow = async (
WHERE id = {traceId: String}
AND project_id = {projectId: String}
${timestamp ? `AND timestamp = {timestamp: DateTime64(3)}` : ""}
- ORDER BY event_ts DESC LIMIT 1
+ ORDER BY event_ts DESC
+ LIMIT 1
`;
const records = await queryClickhouse<TraceRecordReadType>({
@@ -363,11 +362,13 @@ export const getTracesGroupedByName = async (
? new FilterList(chFilter).apply()
: undefined;
+ // 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
name as name,
count(*) as count
- from traces t final
+ from traces t
WHERE t.project_id = {projectId: String}
AND t.name IS NOT NULL
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
@@ -393,27 +394,38 @@ export const getTracesGroupedByName = async (
export const getTracesGroupedByUsers = async (
projectId: string,
filter: FilterState,
+ searchQuery?: string,
+ limit?: number,
+ offset?: number,
columns?: UiColumnMapping[],
) => {
- const chFilter = createFilterFromFilterState(
- filter,
- columns ?? tracesTableUiColumnDefinitions,
+ const { tracesFilter } = getProjectIdDefaultFilter(projectId, {
+ tracesPrefix: "t",
+ });
+
+ tracesFilter.push(
+ ...createFilterFromFilterState(filter, tracesTableUiColumnDefinitions),
);
- const filterRes = new FilterList(chFilter).apply();
+ const tracesFilterRes = tracesFilter.apply();
+ const search = clickhouseSearchCondition(searchQuery);
+ // 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
user_id as user,
count(*) as count
- from traces t final
+ from traces t
WHERE t.project_id = {projectId: String}
AND t.user_id IS NOT NULL
- ${filterRes?.query ? `AND ${filterRes.query}` : ""}
+ AND t.user_id != ''
+ ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}
+ ${search.query}
GROUP BY user
ORDER BY count desc
- LIMIT 1000;
- `;
+ ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
const rows = await queryClickhouse<{
user: string;
@@ -421,8 +433,11 @@ export const getTracesGroupedByUsers = async (
}>({
query: query,
params: {
- projectId: projectId,
- ...(filterRes ? filterRes.params : {}),
+ limit,
+ offset,
+ projectId,
+ ...(tracesFilterRes ? tracesFilterRes.params : {}),
+ ...(searchQuery ? search.params : {}),
},
});
@@ -432,12 +447,11 @@ export const getTracesGroupedByUsers = async (
export type GroupedTracesQueryProp = {
projectId: string;
filter: FilterState;
- sessionIdNullFilter?: boolean;
columns?: UiColumnMapping[];
};
export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
- const { projectId, filter, sessionIdNullFilter, columns } = props;
+ const { projectId, filter, columns } = props;
const chFilter = createFilterFromFilterState(
filter,
@@ -447,14 +461,12 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
const filterRes = new FilterList(chFilter).apply();
const query = `
- select
- distinct(arrayJoin(tags)) as value
- from traces t final
- WHERE t.project_id = {projectId: String}
- ${sessionIdNullFilter ? "AND t.session_id IS NOT NULL" : ""}
- ${filterRes?.query ? `AND ${filterRes.query}` : ""}
- LIMIT 1000;
- `;
+ select distinct(arrayJoin(tags)) as value
+ from traces t
+ WHERE t.project_id = {projectId: String}
+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}
+ LIMIT 1000;
+ `;
const rows = await queryClickhouse<{
value: string;
@@ -469,45 +481,6 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
return rows;
};
-export const getTracesGroupedByUserIds = async (
- props: GroupedTracesQueryProp,
-) => {
- const {
- projectId,
- filter,
- sessionIdNullFilter: sessionIdNotNullFilter,
- columns,
- } = props;
-
- const chFilter = createFilterFromFilterState(
- filter,
- columns ?? tracesTableUiColumnDefinitions,
- );
-
- const appliedFilter = new FilterList(chFilter).apply();
-
- const query = `
- select distinct user_id as user_id
- from traces t final
- WHERE t.project_id = {projectId: String}
- ${sessionIdNotNullFilter ? "AND t.session_id IS NOT NULL" : ""}
- ${appliedFilter?.query ? `AND ${appliedFilter.query}` : ""}
- LIMIT 1000;
- `;
-
- const rows = await queryClickhouse<{
- user_id: string;
- }>({
- query: query,
- params: {
- projectId: projectId,
- ...(appliedFilter ? appliedFilter.params : {}),
- },
- });
-
- return rows;
-};
-
export type SessionDataReturnType = {
session_id: string;
max_timestamp: string;
@@ -651,7 +624,8 @@ const getSessionsTableGeneric = async <T>(props: FetchTracesTableProps) => {
sumMap(o.sum_usage_details)['output'] as session_output_usage,
sumMap(o.sum_usage_details)['total'] as session_total_usage
FROM traces t FINAL
- LEFT JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id
+ LEFT JOIN observations_agg o
+ ON t.id = o.trace_id AND t.project_id = o.project_id
WHERE t.session_id IS NOT NULL
AND t.project_id = {projectId: String}
${singleTraceFilter?.query ? ` AND ${singleTraceFilter.query}` : ""}
@@ -698,12 +672,11 @@ export const getTracesForSession = async (
name,
timestamp,
project_id
- FROM traces
- WHERE (project_id = {projectId: String}) AND (session_id = {sessionId: String})
- ORDER BY timestamp ASC
- LIMIT 1 BY
- id,
- project_id;
+ FROM traces
+ WHERE (project_id = {projectId: String})
+ AND (session_id = {sessionId: String})
+ ORDER BY timestamp ASC
+ LIMIT 1 BY id, project_id;
`;
const rows = await queryClickhouse<{
@@ -742,49 +715,6 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {
});
};
-export const getUsersAndTraceCount = async (
- projectId: string,
- filter: FilterState,
- searchQuery?: string,
- limit?: number,
- offset?: number,
-): Promise<{ userId: string; totalTraces: bigint }[]> => {
- const { tracesFilter } = getProjectIdDefaultFilter(projectId, {
- tracesPrefix: "t",
- });
-
- tracesFilter.push(
- ...createFilterFromFilterState(filter, tracesTableUiColumnDefinitions),
- );
-
- const tracesFilterRes = tracesFilter.apply();
- const search = clickhouseSearchCondition(searchQuery);
-
- const query = `
- SELECT
- t.user_id AS userId,
- COUNT(t.id) AS totalTraces
- FROM traces t FINAL
- WHERE ${tracesFilterRes.query}
- ${search.query}
- AND t.user_id IS NOT NULL
- AND t.user_id != ''
- GROUP BY t.user_id
- ORDER BY totalTraces DESC
- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
- return queryClickhouse({
- query,
- params: {
- limit,
- offset,
- ...tracesFilterRes.params,
- ...search.params,
- },
- });
-};
-
export const getTotalUserCount = async (
projectId: string,
filter: FilterState,
@@ -803,7 +733,7 @@ export const getTotalUserCount = async (
const query = `
SELECT COUNT(DISTINCT t.user_id) AS totalCount
- FROM traces t FINAL
+ FROM traces t
WHERE ${tracesFilterRes.query}
${search.query}
AND t.user_id IS NOT NULL
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 2754f046f9..1e1eb43315 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -189,6 +189,9 @@ export const dashboardRouter = createTRPCRouter({
const traces = await getTracesGroupedByUsers(
input.projectId,
input.filter ?? [],
+ undefined,
+ 1000,
+ 0,
dashboardColumnDefinitions,
);
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 22edd1dbb2..a0f0f41dca 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -9,6 +9,7 @@ import {
} from "@/src/server/api/trpc";
import {
filterAndValidateDbScoreList,
+ type FilterState,
orderBy,
paginationZod,
type SessionOptions,
@@ -27,11 +28,11 @@ import {
traceException,
getSessionsTable,
getSessionsTableCount,
- getTracesGroupedByUserIds,
getTracesGroupedByTags,
getTracesForSession,
getScoresForTraces,
getCostForTraces,
+ getTracesGroupedByUsers,
} from "@langfuse/shared/src/server";
const SessionFilterOptions = z.object({
@@ -353,24 +354,36 @@ export const sessionRouter = createTRPCRouter({
clickhouseSelect: "timestamp",
},
];
+ const filter: FilterState = [
+ {
+ column: "t.session_id",
+ operator: "is not null",
+ type: "null",
+ value: "",
+ },
+ ];
+ if (timestampFilter) {
+ filter.push(timestampFilter);
+ }
const [userIds, tags] = await Promise.all([
- getTracesGroupedByUserIds({
- projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- sessionIdNullFilter: true,
+ getTracesGroupedByUsers(
+ input.projectId,
+ filter,
+ undefined,
+ 1000,
+ 0,
columns,
- }),
+ ),
getTracesGroupedByTags({
projectId: input.projectId,
- filter: timestampFilter ? [timestampFilter] : [],
- sessionIdNullFilter: true,
+ filter,
columns,
}),
]);
return {
userIds: userIds.map((row) => ({
- value: row.user_id,
+ value: row.user,
})),
tags: tags.map((row) => ({
value: row.value,
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index a2bee0a7db..ae38c0a235 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -271,6 +271,7 @@ export const traceRouter = createTRPCRouter({
const scores = await getScoresForTraces(
ctx.session.projectId,
res.map((r) => r.id),
+ undefined,
1000,
0,
);
@@ -541,10 +542,15 @@ export const traceRouter = createTRPCRouter({
input.projectId,
input.timestamp ?? undefined,
),
- getObservationsViewForTrace(input.traceId, input.projectId),
+ getObservationsViewForTrace(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ ),
getScoresForTraces(
input.projectId,
[input.traceId],
+ input.timestamp ?? undefined,
undefined,
undefined,
),
diff --git a/web/src/server/api/routers/users.ts b/web/src/server/api/routers/users.ts
index f1296e17ed..d04ff1c32c 100644
--- a/web/src/server/api/routers/users.ts
+++ b/web/src/server/api/routers/users.ts
@@ -9,8 +9,8 @@ import { Prisma } from "@langfuse/shared/src/db";
import { usersTableCols } from "@/src/server/api/definitions/usersTable";
import {
getTotalUserCount,
+ getTracesGroupedByUsers,
getUserMetrics,
- getUsersAndTraceCount,
tableColumnsToSqlFilterAndPrefix,
} from "@langfuse/shared/src/server";
import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
@@ -89,12 +89,13 @@ export const userRouter = createTRPCRouter({
},
clickhouseExecution: async () => {
const [users, totalUsers] = await Promise.all([
- getUsersAndTraceCount(
+ getTracesGroupedByUsers(
ctx.session.projectId,
input.filter ?? [],
input.searchQuery ?? undefined,
input.limit,
input.page,
+ undefined,
),
getTotalUserCount(
ctx.session.projectId,
@@ -105,7 +106,10 @@ export const userRouter = createTRPCRouter({
return {
totalUsers: totalUsers.shift()?.totalCount ?? 0,
- users,
+ users: users.map((user) => ({
+ userId: user.user,
+ totalTraces: BigInt(user.count),
+ })),
};
},
});