Skip to content

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

feat: support sessions API from Clickhouse (#4065)

Max Deichmann259d832d3797
diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.ts
index 560a96f606..f1a7b67cd0 100644
--- a/packages/shared/scripts/prepareClickhouse.ts
+++ b/packages/shared/scripts/prepareClickhouse.ts
@@ -1,3 +1,4 @@
+import { prisma } from "../src/db";
import { clickhouseClient, logger } from "../src/server";
function randn_bm(min: number, max: number, skew: number) {
@@ -70,7 +71,7 @@ export const prepareClickhouse = async (
array('tag1', 'tag2') as tags,
repeat('input', toInt64(randExponential(1 / 100))) AS input,
repeat('output', toInt64(randExponential(1 / 100))) AS output,
- concat('session_', toString(rand() % 100)) AS session_id,
+ if(randUniform(0, 1) < 0.2, NULL, concat('session_', toString(rand() % 1000))) AS session_id,
timestamp AS created_at,
timestamp AS updated_at,
timestamp AS event_ts,
@@ -157,6 +158,34 @@ export const prepareClickhouse = async (
},
});
}
+ // we also need to upsert trace sessions in postgres
+
+ const sessionQuery = `
+ SELECT session_id, project_id
+ FROM traces
+ WHERE session_id IS NOT NULL;
+ `;
+ const sessionResult = await clickhouseClient.query({
+ query: sessionQuery,
+ format: "JSONEachRow",
+ });
+
+ const sessionData = await sessionResult.json<{
+ session_id: string;
+ project_id: string;
+ }>();
+
+ const idProjectIdCombinations = sessionData.map((session) => ({
+ id: session.session_id,
+ projectId: session.project_id,
+ public: Math.random() < 0.1,
+ bookmarked: Math.random() < 0.1,
+ }));
+
+ await prisma.traceSession.createMany({
+ data: idProjectIdCombinations,
+ skipDuplicates: true,
+ });
}
const tables = ["traces", "scores", "observations"];
diff --git a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
index 99db33e553..0509186830 100644
--- a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
+++ b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts
@@ -14,6 +14,8 @@ function randomCharacters() {
export interface Filter {
apply(): ClickhouseFilter;
clickhouseTable: string;
+ operator: (typeof filterOperators)[keyof typeof filterOperators][number];
+ field: string;
}
type ClickhouseFilter = {
query: string;
@@ -22,9 +24,9 @@ type ClickhouseFilter = {
export class StringFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected value: string;
- protected operator: (typeof filterOperators)["string"][number];
+ public field: string;
+ public value: string;
+ public operator: (typeof filterOperators)["string"][number];
protected tablePrefix?: string;
constructor(opts: {
@@ -75,9 +77,9 @@ export class StringFilter implements Filter {
export class NumberFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected value: number;
- protected operator: (typeof filterOperators)["number"][number];
+ public field: string;
+ public value: number;
+ public operator: (typeof filterOperators)["number"][number];
protected tablePrefix?: string;
constructor(opts: {
@@ -106,9 +108,9 @@ export class NumberFilter implements Filter {
export class DateTimeFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected value: Date;
- protected operator: (typeof filterOperators)["datetime"][number];
+ public field: string;
+ public value: Date;
+ public operator: (typeof filterOperators)["datetime"][number];
protected tablePrefix?: string;
constructor(opts: {
@@ -137,9 +139,9 @@ export class DateTimeFilter implements Filter {
export class StringOptionsFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected values: string[];
- protected operator: (typeof filterOperators.stringOptions)[number];
+ public field: string;
+ public values: string[];
+ public operator: (typeof filterOperators.stringOptions)[number];
protected tablePrefix?: string;
constructor(opts: {
@@ -173,10 +175,10 @@ export class StringOptionsFilter implements Filter {
// As we use the MAP form clickhouse, we can only filter efficiently on the first level of a json obj.
export class StringObjectFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected key: string;
- protected value: string;
- protected operator: (typeof filterOperators)["stringObject"][number];
+ public field: string;
+ public key: string;
+ public value: string;
+ public operator: (typeof filterOperators)["stringObject"][number];
protected tablePrefix?: string;
constructor(opts: {
@@ -232,9 +234,9 @@ export class StringObjectFilter implements Filter {
// this is used when we want to filter multiple values on a clickhouse column which is also an array
export class ArrayOptionsFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected values: string[];
- protected operator: (typeof filterOperators.arrayOptions)[number];
+ public field: string;
+ public values: string[];
+ public operator: (typeof filterOperators.arrayOptions)[number];
protected tablePrefix?: string;
constructor(opts: {
@@ -279,10 +281,10 @@ export class ArrayOptionsFilter implements Filter {
export class NumberObjectFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected key: string;
- protected value: number;
- protected operator: (typeof filterOperators)["numberObject"][number];
+ public field: string;
+ public key: string;
+ public value: number;
+ public operator: (typeof filterOperators)["numberObject"][number];
protected tablePrefix?: string;
constructor(opts: {
@@ -314,13 +316,15 @@ export class NumberObjectFilter implements Filter {
export class BooleanFilter implements Filter {
public clickhouseTable: string;
- protected field: string;
- protected value: boolean;
+ public field: string;
+ public operator: (typeof filterOperators)["boolean"][number];
+ public value: boolean;
protected tablePrefix?: string;
constructor(opts: {
clickhouseTable: string;
field: string;
+ operator: (typeof filterOperators)["boolean"][number];
value: boolean;
tablePrefix?: string;
}) {
@@ -328,13 +332,14 @@ export class BooleanFilter implements Filter {
this.field = opts.field;
this.value = opts.value;
this.tablePrefix = opts.tablePrefix;
+ this.operator = opts.operator;
}
apply(): ClickhouseFilter {
const uid = randomCharacters();
const varName = `booleanFilter${uid}`;
return {
- query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} = {${varName}: Boolean}`,
+ query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} ${this.operator} {${varName}: Boolean}`,
params: { [varName]: this.value },
};
}
diff --git a/packages/shared/src/server/queries/clickhouse-filter/factory.ts b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
index c509d3214a..ca9ee9364d 100644
--- a/packages/shared/src/server/queries/clickhouse-filter/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-filter/factory.ts
@@ -80,6 +80,7 @@ export const createFilterFromFilterState = (
clickhouseTable: column.clickhouseTableName,
field: column.clickhouseSelect,
value: frontEndFilter.value,
+ operator: frontEndFilter.operator,
tablePrefix: column.queryPrefix,
});
case "numberObject":
@@ -114,7 +115,6 @@ const matchAndVerifyTracesUiColumn = (
) => {
// tries to match the column name to the clickhouse table name
logger.debug(`Filter to match: ${JSON.stringify(filter)}`);
-
const uiTable = uiTableDefinitions.find(
(col) =>
col.uiTableName === filter.column || col.uiTableId === filter.column, // matches on the NAME of the column in the UI.
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 6984c03500..fd034edef7 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -653,3 +653,25 @@ export const getObservationsGroupedByPromptName = async (
promptName: p.name,
}));
};
+
+export const getCostForTraces = async (
+ projectId: string,
+ traceIds: string[],
+) => {
+ 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)});
+ `;
+
+ const res = await queryClickhouse<{ total_cost: string }>({
+ query,
+ params: {
+ projectId,
+ traceIds,
+ },
+ });
+ return res.length > 0 ? Number(res[0].total_cost) : undefined;
+};
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 1f818de8c3..dc5f4dd282 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -9,12 +9,16 @@ import {
import { ObservationLevel, Trace } from "@prisma/client";
import { FilterState } from "../../types";
import { logger } from "../logger";
-import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
+import {
+ DateTimeFilter,
+ FilterList,
+} from "../queries/clickhouse-filter/clickhouse-filter";
import { TraceRecordReadType } from "./definitions";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions/mapTracesTable";
import { OrderByState } from "../../interfaces/orderBy";
import { orderByToClickhouseSql } from "../queries/clickhouse-filter/orderby-factory";
import { UiColumnMapping } from "../../tableDefinitions";
+import { sessionCols } from "../../tableDefinitions/mapSessionTable";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
const convertClickhouseToDomain = (record: TraceRecordReadType): Trace => {
@@ -276,27 +280,30 @@ export const getTracesGroupedByName = async (
return rows;
};
-export const getTracesGroupedByTags = async (
- projectId: string,
- timestampFilter?: FilterState,
-) => {
- const chFilter = timestampFilter
- ? createFilterFromFilterState(
- timestampFilter,
- tracesTableUiColumnDefinitions,
- )
- : undefined;
+export type GroupedTracesQueryProp = {
+ projectId: string;
+ filter: FilterState;
+ sessionIdNullFilter?: boolean;
+ columns?: UiColumnMapping[];
+};
- const timestampFilterRes = chFilter
- ? new FilterList(chFilter).apply()
- : undefined;
+export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
+ const { projectId, filter, sessionIdNullFilter, columns } = props;
+
+ const chFilter = createFilterFromFilterState(
+ filter,
+ columns ?? tracesTableUiColumnDefinitions,
+ );
+
+ const filterRes = new FilterList(chFilter).apply();
const query = `
select
distinct(arrayJoin(tags)) as value
from traces t final
WHERE t.project_id = {projectId: String}
- ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
+ ${sessionIdNullFilter ? "AND t.session_id IS NOT NULL" : ""}
+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}
LIMIT 1000;
`;
@@ -306,9 +313,254 @@ export const getTracesGroupedByTags = async (
query: query,
params: {
projectId: projectId,
- ...(timestampFilterRes ? timestampFilterRes.params : {}),
+ ...(filterRes ? filterRes.params : {}),
+ },
+ });
+
+ 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;
+ min_timestamp: string;
+ trace_ids: string[];
+ user_ids: string[];
+ trace_count: number;
+ trace_tags: string[];
+ total_observations: number;
+ duration: number;
+ session_usage_details: Record<string, number>;
+ session_cost_details: Record<string, number>;
+ session_input_cost: string;
+ session_output_cost: string;
+ session_total_cost: string;
+ session_input_usage: string;
+ session_output_usage: string;
+ session_total_usage: string;
+};
+
+export const getSessionsTableCount = async (props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy?: OrderByState;
+ limit?: number;
+ offset?: number;
+}) => {
+ const rows = await getSessionsTableGeneric<{ count: string }>({
+ select: `
+ count(session_id) as count
+ `,
+ projectId: props.projectId,
+ filter: props.filter,
+ orderBy: props.orderBy,
+ limit: props.limit,
+ offset: props.offset,
+ });
+
+ return rows.length > 0 ? Number(rows[0].count) : 0;
+};
+
+export const getSessionsTable = async (props: {
+ projectId: string;
+ filter: FilterState;
+ orderBy?: OrderByState;
+ limit?: number;
+ offset?: number;
+}) => {
+ const rows = await getSessionsTableGeneric<SessionDataReturnType>({
+ select: `
+ session_id,
+ max_timestamp,
+ min_timestamp,
+ trace_ids,
+ user_ids,
+ trace_count,
+ trace_tags,
+ total_observations,
+ duration,
+ session_usage_details,
+ session_cost_details,
+ session_input_cost,
+ session_output_cost,
+ session_total_cost,
+ session_input_usage,
+ session_output_usage,
+ session_total_usage
+ `,
+ projectId: props.projectId,
+ filter: props.filter,
+ orderBy: props.orderBy,
+ limit: props.limit,
+ offset: props.offset,
+ });
+
+ return rows;
+};
+
+const getSessionsTableGeneric = async <T>(props: FetchTracesTableProps) => {
+ const { select, projectId, filter, orderBy, limit, offset } = props;
+
+ const { tracesFilter, scoresFilter, observationsFilter } =
+ getProjectIdDefaultFilter(projectId, { tracesPrefix: "s" });
+
+ tracesFilter.push(...createFilterFromFilterState(filter, sessionCols));
+
+ const tracesFilterRes = tracesFilter.apply();
+ const scoresAvgFilterRes = scoresFilter.apply();
+ const observationsStatsRes = observationsFilter.apply();
+
+ const traceTimestampFilter: DateTimeFilter | undefined = tracesFilter.find(
+ (f) =>
+ f.field === "min_timestamp" &&
+ (f.operator === ">=" || f.operator === ">"),
+ ) as DateTimeFilter | undefined;
+
+ const query = `
+ WITH observations_agg AS (
+ SELECT o.trace_id,
+ count(*) as obs_count,
+ min(o.start_time) as min_start_time,
+ max(o.end_time) as max_end_time,
+ sumMap(usage_details) as sum_usage_details,
+ sumMap(cost_details) as sum_cost_details,
+ anyLast(project_id) as project_id
+ FROM observations o FINAL
+ WHERE o.project_id = {projectId: String}
+ ${traceTimestampFilter ? `AND o.start_time >= {observationsStartTime: DateTime} - INTERVAL 1 DAY` : ""}
+ GROUP BY o.trace_id
+ ),
+ session_data AS (
+ SELECT
+ t.session_id,
+ anyLast(t.project_id) as project_id,
+ max(t.timestamp) as max_timestamp,
+ min(t.timestamp) as min_timestamp,
+ groupArray(t.id) AS trace_ids,
+ groupUniqArray(t.user_id) AS user_ids,
+ count(*) as trace_count,
+ groupUniqArrayArray(t.tags) as trace_tags,
+ -- Aggregate observations data at session level
+ sum(o.obs_count) as total_observations,
+ date_diff('seconds', min(min_start_time), max(max_end_time)) as duration,
+ sumMap(o.sum_usage_details) as session_usage_details,
+ sumMap(o.sum_cost_details) as session_cost_details,
+ sumMap(o.sum_cost_details)['input'] as session_input_cost,
+ sumMap(o.sum_cost_details)['output'] as session_output_cost,
+ sumMap(o.sum_cost_details)['total'] as session_total_cost,
+ sumMap(o.sum_usage_details)['input'] as session_input_usage,
+ 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
+ WHERE t.session_id IS NOT NULL
+ AND t.project_id = {projectId: String}
+ GROUP BY t.session_id
+ )
+ SELECT ${select}
+ FROM session_data s
+ WHERE ${tracesFilterRes.query ? tracesFilterRes.query : ""}
+ ${orderByToClickhouseSql(orderBy ?? null, sessionCols)}
+ ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ const obsStartTimeValue = traceTimestampFilter
+ ? convertDateToClickhouseDateTime(traceTimestampFilter.value)
+ : null;
+
+ const res = await queryClickhouse<T>({
+ query: query,
+ params: {
+ projectId,
+ limit: limit,
+ offset: offset,
+ ...tracesFilterRes.params,
+ ...observationsStatsRes.params,
+ ...scoresAvgFilterRes.params,
+ ...(obsStartTimeValue
+ ? { observationsStartTime: obsStartTimeValue }
+ : {}),
+ },
+ });
+
+ return res;
+};
+
+export const getTracesForSession = async (
+ projectId: string,
+ sessionId: string,
+) => {
+ const query = `
+ SELECT
+ id,
+ user_id,
+ 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;
+ `;
+
+ const rows = await queryClickhouse<{
+ id: string;
+ user_id: string;
+ name: string;
+ timestamp: string;
+ }>({
+ query: query,
+ params: {
+ projectId,
+ sessionId,
+ },
+ });
+
+ return rows.map((row) => ({
+ id: row.id,
+ userId: row.user_id,
+ name: row.name,
+ timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
+ }));
+};
diff --git a/packages/shared/src/tableDefinitions/mapSessionTable.ts b/packages/shared/src/tableDefinitions/mapSessionTable.ts
new file mode 100644
index 0000000000..c7cf9f09d6
--- /dev/null
+++ b/packages/shared/src/tableDefinitions/mapSessionTable.ts
@@ -0,0 +1,113 @@
+import { UiColumnMapping } from ".";
+
+export const sessionCols: UiColumnMapping[] = [
+ // we do not access the traces scores in clichouse. We default back to the trace timestamps.
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "min_timestamp",
+ },
+ {
+ uiTableName: "User IDs",
+ uiTableId: "userIds",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "user_ids",
+ },
+ {
+ uiTableName: "Session Duration",
+ uiTableId: "sessionDuration",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "duration",
+ },
+ {
+ uiTableName: "Count Traces",
+ uiTableId: "countTraces",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "trace_count",
+ },
+ {
+ uiTableName: "Session Input Cost",
+ uiTableId: "inputCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_input_cost",
+ },
+ {
+ uiTableName: "Session Output Cost",
+ uiTableId: "outputCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_output_cost",
+ },
+ {
+ uiTableName: "Session Total Cost",
+ uiTableId: "totalCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_total_cost",
+ },
+ {
+ uiTableName: "Input Tokens",
+ uiTableId: "inputTokens",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_input_usage",
+ },
+ {
+ uiTableName: "Output Tokens",
+ uiTableId: "outputTokens",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_output_usage",
+ },
+ {
+ uiTableName: "Total Tokens",
+ uiTableId: "totalTokens",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_total_usage",
+ },
+ {
+ uiTableName: "Usage",
+ uiTableId: "totalTokens",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_total_usage",
+ },
+ {
+ uiTableName: "Session Total Usage",
+ uiTableId: "usage",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_total_usage",
+ },
+ {
+ uiTableName: "Session Duration (s)",
+ uiTableId: "sessionDuration",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "duration",
+ },
+ {
+ uiTableName: "Traces Count",
+ uiTableId: "tracesCount",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "trace_count",
+ },
+ {
+ uiTableName: "Input Cost ($)",
+ uiTableId: "inputCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_input_cost",
+ },
+ {
+ uiTableName: "Output Cost ($)",
+ uiTableId: "outputCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_output_cost",
+ },
+ {
+ uiTableName: "Total Cost ($)",
+ uiTableId: "totalCost",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "session_total_cost",
+ },
+ {
+ uiTableName: "Trace Tags",
+ uiTableId: "traceTags",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "trace_tags",
+ },
+];
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 17b858e52a..8af2844b44 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -18,6 +18,7 @@ import { Button } from "@/src/components/ui/button";
import useLocalStorage from "@/src/components/useLocalStorage";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { ScrollScreenPage } from "@/src/components/layouts/scroll-screen-page";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
// some projects have thousands of traces in a sessions, paginate to avoid rendering all at once
const PAGE_SIZE = 50;
@@ -32,6 +33,7 @@ export const SessionPage: React.FC<{
{
sessionId,
projectId: projectId,
+ queryClickhouse: useClickhouse(),
},
{
retry(failureCount, error) {
@@ -185,7 +187,7 @@ const SessionIO = ({
projectId: string;
}) => {
const trace = api.traces.byId.useQuery(
- { traceId, projectId },
+ { traceId, projectId, queryClickhouse: useClickhouse() },
{
enabled: typeof traceId === "string",
trpc: {
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 3fcf244a14..4e17915cda 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -29,6 +29,7 @@ import TagList from "@/src/features/tag/components/TagList";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { cn } from "@/src/utils/tailwind";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";
export type SessionTableRow = {
id: string;
@@ -109,6 +110,7 @@ export default function SessionsTable({
orderBy: null,
page: 0,
limit: 1,
+ queryClickhouse: useClickhouse(),
};
const payloadGetAll = {
@@ -125,6 +127,7 @@ export default function SessionsTable({
{
projectId,
sessionIds: sessions.data?.sessions.map((s) => s.id) ?? [],
+ queryClickhouse: useClickhouse(),
},
{
enabled: sessions.data !== undefined,
@@ -146,6 +149,7 @@ export default function SessionsTable({
dateRangeFilter[0]?.type === "datetime"
? dateRangeFilter[0]
: undefined,
+ queryClickhouse: useClickhouse(),
},
{
trpc: {
@@ -499,21 +503,23 @@ export default function SessionsTable({
: {
isLoading: false,
isError: false,
- data: sessionRowData.rows?.map((session) => ({
- id: session.id,
- createdAt: session.createdAt.toLocaleString(),
- userIds: session.userIds,
- countTraces: session.countTraces,
- bookmarked: session.bookmarked,
- sessionDuration: session.sessionDuration,
- inputCost: session.inputCost,
- outputCost: session.outputCost,
- totalCost: session.totalCost,
- inputTokens: session.promptTokens,
- outputTokens: session.completionTokens,
- totalTokens: session.totalTokens,
- traceTags: session.traceTags,
- })),
+ data: sessionRowData.rows?.map<SessionTableRow>(
+ (session) => ({
+ id: session.id,
+ bookmarked: session.bookmarked,
+ createdAt: session.createdAt.toLocaleString(),
+ userIds: session.userIds,
+ countTraces: session.countTraces,
+ sessionDuration: session.sessionDuration,
+ inputCost: session.inputCost,
+ outputCost: session.outputCost,
+ totalCost: session.totalCost,
+ inputTokens: session.promptTokens,
+ outputTokens: session.completionTokens,
+ totalTokens: session.totalTokens,
+ traceTags: session.traceTags,
+ }),
+ ),
}
}
pagination={{
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 1ed4185be2..9ec03df36e 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -78,9 +78,9 @@ export const filterOptionsQuery = protectedProjectProcedure
const getClickhouseTraceTags = async (): Promise<
Array<{ tag: string }>
> => {
- const traces = await getTracesGroupedByTags(
- input.projectId,
- startTimeFilter
+ const traces = await getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: startTimeFilter
? [
{
column: "Timestamp",
@@ -90,7 +90,7 @@ export const filterOptionsQuery = protectedProjectProcedure
},
]
: [],
- );
+ });
return traces.map((i) => ({ tag: i.value }));
};
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 3aaa63f7b2..f32a9d7472 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -235,10 +235,10 @@ export const scoresRouter = createTRPCRouter({
input.projectId,
timestampFilter ? [timestampFilter] : [],
),
- getTracesGroupedByTags(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ }),
]);
const res: ScoreOptions = {
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 2b1982b944..fbd8955fc0 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -14,16 +14,25 @@ import {
type SessionOptions,
singleFilter,
timeFilter,
+ tracesTableUiColumnDefinitions,
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
-
-import type Decimal from "decimal.js";
+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
+import Decimal from "decimal.js";
import {
createSessionsAllQuery,
datetimeFilterToPrismaSql,
traceException,
+ getSessionsTable,
+ getSessionsTableCount,
+ getTracesGroupedByUserIds,
+ getTracesGroupedByTags,
+ getTracesForSession,
+ getScoresForTraces,
+ getCostForTraces,
} from "@langfuse/shared/src/server";
+
const SessionFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
filter: z.array(singleFilter).nullable(),
@@ -33,9 +42,65 @@ const SessionFilterOptions = z.object({
export const sessionRouter = createTRPCRouter({
all: protectedProjectProcedure
- .input(SessionFilterOptions)
+ .input(
+ SessionFilterOptions.extend({
+ queryClickhouse: z.boolean().default(false),
+ }),
+ )
.query(async ({ input, ctx }) => {
try {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const sessions = await getSessionsTable({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ offset: input.page * input.limit,
+ limit: input.limit,
+ });
+
+ const prismaSessionInfo = await ctx.prisma.traceSession.findMany({
+ where: {
+ id: {
+ in: sessions.map((s) => s.session_id),
+ },
+ projectId: input.projectId,
+ },
+ select: {
+ id: true,
+ bookmarked: true,
+ public: true,
+ },
+ });
+ return {
+ sessions: sessions.map((s) => ({
+ id: s.session_id,
+ userIds: s.user_ids,
+ countTraces: s.trace_ids.length,
+ sessionDuration: Number(s.duration),
+ inputCost: new Decimal(s.session_input_cost),
+ outputCost: new Decimal(s.session_output_cost),
+ totalCost: new Decimal(s.session_total_cost),
+ promptTokens: Number(s.session_input_usage),
+ completionTokens: Number(s.session_output_usage),
+ totalTokens: Number(s.session_total_usage),
+ traceTags: s.trace_tags,
+ createdAt: s.min_timestamp,
+ bookmarked:
+ prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.bookmarked ?? false,
+ public: prismaSessionInfo.find((p) => p.id === s.session_id)
+ ?.public,
+ })),
+ };
+ }
+
const sessions = await ctx.prisma.$queryRaw<
Array<{
id: string;
@@ -67,9 +132,34 @@ export const sessionRouter = createTRPCRouter({
}
}),
countAll: protectedProjectProcedure
- .input(SessionFilterOptions)
+ .input(
+ SessionFilterOptions.extend({
+ queryClickhouse: z.boolean().default(false),
+ }),
+ )
.query(async ({ input, ctx }) => {
try {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const count = await getSessionsTableCount({
+ projectId: input.projectId,
+ filter: input.filter ?? [],
+ orderBy: input.orderBy,
+ offset: input.page * input.limit,
+ limit: input.limit,
+ });
+
+ return {
+ totalCount: count,
+ };
+ }
+
const inputForTotal: z.infer<typeof SessionFilterOptions> = {
filter: input.filter,
projectId: input.projectId,
@@ -110,11 +200,24 @@ export const sessionRouter = createTRPCRouter({
z.object({
projectId: z.string(),
sessionIds: z.array(z.string()),
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
try {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
if (input.sessionIds.length === 0) return [];
+
+ if (input.queryClickhouse) {
+ return []; // initial endpoint returns all data from CH.
+ }
+
const inputForMetrics: z.infer<typeof SessionFilterOptions> = {
filter: [],
projectId: input.projectId,
@@ -179,11 +282,55 @@ export const sessionRouter = createTRPCRouter({
z.object({
projectId: z.string(),
timestampFilter: timeFilter.optional(),
+ queryClickhouse: z.boolean().default(false),
}),
)
.query(async ({ input, ctx }) => {
try {
const { timestampFilter } = input;
+
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const columns = [
+ ...tracesTableUiColumnDefinitions,
+ {
+ uiTableName: "Created At",
+ uiTableId: "createdAt",
+ clickhouseTableName: "traces",
+ clickhouseSelect: "timestamp",
+ },
+ ];
+ const [userIds, tags] = await Promise.all([
+ getTracesGroupedByUserIds({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ sessionIdNullFilter: true,
+ columns,
+ }),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ sessionIdNullFilter: true,
+ columns,
+ }),
+ ]);
+
+ return {
+ userIds: userIds.map((row) => ({
+ value: row.user_id,
+ })),
+ tags: tags.map((row) => ({
+ value: row.value,
+ })),
+ };
+ }
+
const rawTimestampFilter =
timestampFilter && timestampFilter.type === "datetime"
? datetimeFilterToPrismaSql(
@@ -235,9 +382,73 @@ export const sessionRouter = createTRPCRouter({
}
}),
byId: protectedGetSessionProcedure
- .input(z.object({ projectId: z.string(), sessionId: z.string() }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ sessionId: z.string(),
+ queryClickhouse: z.boolean().default(false),
+ }),
+ )
.query(async ({ input, ctx }) => {
try {
+ if (input.queryClickhouse && !isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (input.queryClickhouse) {
+ const postgresSession = await ctx.prisma.traceSession.findFirst({
+ where: {
+ id: input.sessionId,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!postgresSession) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project",
+ });
+ }
+
+ const clickhouseTraces = await getTracesForSession(
+ input.projectId,
+ input.sessionId,
+ );
+
+ const [scores, costData] = await Promise.all([
+ getScoresForTraces(
+ input.projectId,
+ clickhouseTraces.map((t) => t.id),
+ ),
+ getCostForTraces(
+ input.projectId,
+ clickhouseTraces.map((t) => t.id),
+ ),
+ ]);
+
+ const validatedScores = filterAndValidateDbScoreList(
+ scores,
+ traceException,
+ );
+
+ return {
+ ...postgresSession,
+ traces: clickhouseTraces.map((t) => ({
+ ...t,
+ scores: validatedScores.filter((s) => s.traceId === t.id),
+ })),
+ totalCost: costData,
+ users: [
+ ...new Set(
+ clickhouseTraces.map((t) => t.userId).filter((t) => t !== null),
+ ),
+ ],
+ };
+ }
+
const session = await ctx.prisma.traceSession.findFirst({
where: {
id: input.sessionId,
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 3a70f4e96a..6f924f42fd 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -438,10 +438,10 @@ export const traceRouter = createTRPCRouter({
tracesTableUiColumnDefinitions,
timestampFilter ? [timestampFilter] : [],
),
- getTracesGroupedByTags(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter: timestampFilter ? [timestampFilter] : [],
+ }),
]);
const res: TraceOptions = {
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 3169e9c8e9..e5d4fe70f3 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -141,6 +141,7 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {
const withOtelTracingProcedure = t.procedure.use(
tracing({ collectInput: true, collectResult: true }),
);
+
/**
* Public (unauthenticated) procedure
*
@@ -405,6 +406,7 @@ export const protectedGetTraceProcedure = withOtelTracingProcedure
const inputSessionSchema = z.object({
sessionId: z.string(),
projectId: z.string(),
+ queryClickhouse: z.boolean().nullish(),
});
const enforceSessionAccess = t.middleware(async ({ ctx, rawInput, next }) => {
@@ -417,6 +419,7 @@ const enforceSessionAccess = t.middleware(async ({ ctx, rawInput, next }) => {
const { sessionId, projectId } = result.data;
+ // trace sessions are stored in postgres. No need to check for clickhouse eligibility.
const session = await prisma.traceSession.findFirst({
where: {
id: sessionId,