🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: read traces and observations from clickhouse (#3810)
Max Deichmanna6dfc58c7234
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex f6849683a7..7b42f95419 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -20,6 +20,7 @@"prettier.documentSelectors": ["**/*.{cjs,mjs,ts,tsx,astro,md,mdx,json,yaml,yml}"],+ "prettier.trailingComma": "all","mdx.experimentalLanguageServer": true,"typescript.preferences.importModuleSpecifier": "non-relative","docwriter.style": "JSDoc",diff --git a/packages/shared/scripts/load-seed.ts b/packages/shared/scripts/load-seed.tsindex 79503ee0f3..6e65fce566 100644--- a/packages/shared/scripts/load-seed.ts+++ b/packages/shared/scripts/load-seed.ts@@ -7,7 +7,7 @@ import {logger,} from "../src/server";import { prepareClickhouse } from "./prepareClickhouse";-import { redis } from "@langfuse/shared/src/server";+import { redis } from "../src/server";const createRandomProjectId = () => randomUUID().toString();@@ -75,9 +75,9 @@ const prepareProjectsAndApiKeys = async (};async function main() {- let numOfProjects = parseInt(process.argv[3], 10);- let numberOfDays = parseInt(process.argv[4], 10);- let totalObservations = parseInt(process.argv[5], 10);+ let numOfProjects = parseInt(process.argv[2], 10);+ let numberOfDays = parseInt(process.argv[3], 10);+ let totalObservations = parseInt(process.argv[4], 10);if (isNaN(totalObservations)) {logger.warn(diff --git a/packages/shared/scripts/prepareClickhouse.ts b/packages/shared/scripts/prepareClickhouse.tsindex 1d7af17d53..e4e92edc3d 100644--- a/packages/shared/scripts/prepareClickhouse.ts+++ b/packages/shared/scripts/prepareClickhouse.ts@@ -136,8 +136,9 @@ export const prepareClickhouse = async ('comment' as comment,toString(rand() % 100) as author_user_id,toString(rand() % 100) as config_id,- toString(rand() % 100) as data_type,+ if (rand() < 0.33, 'NUMERIC', if (rand() < 0.5, 'CATEGORICAL', 'BOOLEAN')) as data_type,toString(rand() % 100) as string_value,+ NULL as queue_id,timestamp AS created_at,timestamp AS updated_at,timestamp AS event_ts,diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 159ad45511..984057e1fe 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -6,7 +6,7 @@ export * from "./interfaces/parseDbOrg";export * from "./interfaces/customLLMProviderConfigSchemas";export * from "./tableDefinitions";export * from "./types";-export * from "./tracesTable";+export * from "./tableDefinitions/tracesTable";export * from "./server/auth/apiKeys";export * from "./observationsTable";export * from "./utils/zod";diff --git a/packages/shared/src/server/clickhouse.ts b/packages/shared/src/server/clickhouse.tsdeleted file mode 100644index 9a103d36c0..0000000000--- a/packages/shared/src/server/clickhouse.ts+++ /dev/null@@ -1,48 +0,0 @@-import { createClient } from "@clickhouse/client";--import { env } from "../env";-import { eventTypes } from "./ingestion/types";-import { LangfuseNotFoundError } from "../errors";--export enum ClickhouseEntityType {- Trace = "trace",- Score = "score",- Observation = "observation",- SdkLog = "sdk-log",-}--export function getClickhouseEntityType(- eventType: string,-): ClickhouseEntityType {- switch (eventType) {- case eventTypes.TRACE_CREATE:- return ClickhouseEntityType.Trace;- case eventTypes.OBSERVATION_CREATE:- case eventTypes.OBSERVATION_UPDATE:- case eventTypes.EVENT_CREATE:- case eventTypes.SPAN_CREATE:- case eventTypes.SPAN_UPDATE:- case eventTypes.GENERATION_CREATE:- case eventTypes.GENERATION_UPDATE:- return ClickhouseEntityType.Observation;- case eventTypes.SCORE_CREATE:- return ClickhouseEntityType.Score;- case eventTypes.SDK_LOG:- return ClickhouseEntityType.SdkLog;- default:- throw new LangfuseNotFoundError(`Unknown event type: ${eventType}`);- }-}--export type ClickhouseClientType = ReturnType<typeof createClient>;--export const clickhouseClient = createClient({- url: env.CLICKHOUSE_URL,- username: env.CLICKHOUSE_USER,- password: env.CLICKHOUSE_PASSWORD,- database: "default",- clickhouse_settings: {- async_insert: 1,- wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse- },-});diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.tsnew file mode 100644index 0000000000..556cca6a8a--- /dev/null+++ b/packages/shared/src/server/clickhouse/client.ts@@ -0,0 +1,15 @@+import { createClient } from "@clickhouse/client";+import { env } from "../../env";++export type ClickhouseClientType = ReturnType<typeof createClient>;++export const clickhouseClient = createClient({+ url: env.CLICKHOUSE_URL,+ username: env.CLICKHOUSE_USER,+ password: env.CLICKHOUSE_PASSWORD,+ database: "default",+ clickhouse_settings: {+ async_insert: 1,+ wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse+ },+});diff --git a/packages/shared/src/server/clickhouse/schema-utils.ts b/packages/shared/src/server/clickhouse/schema-utils.tsnew file mode 100644index 0000000000..b61cb9fb1d--- /dev/null+++ b/packages/shared/src/server/clickhouse/schema-utils.ts@@ -0,0 +1,83 @@+import { LangfuseNotFoundError } from "../../errors";+import { eventTypes } from "../ingestion/types";+import {+ ClickhouseTableName,+ ClickhouseTableNames,+ TraceClickhouseRecord,+ ObservationClickhouseRecord,+ ScoreClickhouseRecord,+ TraceClickhouseColumns,+ ObservationClickhouseColumns,+ ScoreClickhouseColumns,+} from "./schema";++export const isValidTableName = (+ tableName: string,+): tableName is ClickhouseTableName =>+ Object.keys(ClickhouseTableNames).includes(tableName);++export function isKeyOfTraceClickhouseRecord(+ key: string,+): key is keyof TraceClickhouseRecord {+ return TraceClickhouseColumns.some((column) => key === column.name);+}++export function isKeyOfObservationClickhouseRecord(+ key: string,+): key is keyof ObservationClickhouseRecord {+ return ObservationClickhouseColumns.some((column) => key === column.name);+}++export function isKeyOfScoreClickhouseRecord(+ key: string,+): key is keyof ScoreClickhouseRecord {+ return ScoreClickhouseColumns.some((column) => key === column.name);+}++export function isKeyOfClickhouseRecord(+ tableName: ClickhouseTableName,+ key: string,+): key is+ | keyof TraceClickhouseRecord+ | keyof ObservationClickhouseRecord+ | keyof ScoreClickhouseRecord {+ switch (tableName) {+ case "traces":+ return isKeyOfTraceClickhouseRecord(key);+ case "observations":+ return isKeyOfObservationClickhouseRecord(key);+ case "scores":+ return isKeyOfScoreClickhouseRecord(key);+ default:+ throw new Error(`Unhandled table case: ${tableName}`);+ }+}++export type IngestionEntityTypes =+ | "trace"+ | "observation"+ | "score"+ | "sdk_log";++export const getClickhouseEntityType = (+ eventType: string,+): IngestionEntityTypes => {+ switch (eventType) {+ case eventTypes.TRACE_CREATE:+ return "trace";+ case eventTypes.OBSERVATION_CREATE:+ case eventTypes.OBSERVATION_UPDATE:+ case eventTypes.EVENT_CREATE:+ case eventTypes.SPAN_CREATE:+ case eventTypes.SPAN_UPDATE:+ case eventTypes.GENERATION_CREATE:+ case eventTypes.GENERATION_UPDATE:+ return "observation";+ case eventTypes.SCORE_CREATE:+ return "score";+ case eventTypes.SDK_LOG:+ return "sdk_log";+ default:+ throw new LangfuseNotFoundError(`Unknown event type: ${eventType}`);+ }+};diff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.tsnew file mode 100644index 0000000000..1a92c8387a--- /dev/null+++ b/packages/shared/src/server/clickhouse/schema.ts@@ -0,0 +1,306 @@+import { z } from "zod";++export const TraceClickhouseRecordSchema = z.object({+ id: z.string(),+ timestamp: z.string(), // DateTime64(3)+ name: z.string(),+ user_id: z.string().optional(),+ metadata: z.record(z.string()),+ release: z.string().optional(),+ version: z.string().optional(),+ project_id: z.string(),+ public: z.boolean(),+ bookmarked: z.boolean(),+ tags: z.array(z.string()),+ input: z.string().optional(),+ output: z.string().optional(),+ session_id: z.string().optional(),+ created_at: z.string(), // DateTime64(3)+ updated_at: z.string(), // DateTime64(3)+ event_ts: z.string(), // DateTime64(3)+});++export type TraceClickhouseRecord = z.infer<typeof TraceClickhouseRecordSchema>;++export const ObservationClickhouseRecordSchema = z.object({+ id: z.string(),+ trace_id: z.string(),+ project_id: z.string(),+ type: z.string(), // LowCardinality(String)+ parent_observation_id: z.string().optional(),+ start_time: z.string(), // DateTime64(3)+ end_time: z.string().optional(), // Nullable(DateTime64(3))+ name: z.string(),+ metadata: z.record(z.string()),+ level: z.string(), // LowCardinality(String)+ status_message: z.string().optional(),+ version: z.string().optional(),+ input: z.string().optional(),+ output: z.string().optional(),+ provided_model_name: z.string().optional(),+ internal_model_id: z.string().optional(),+ model_parameters: z.string().optional(),+ provided_usage_details: z.record(z.number()).optional(), // Map(LowCardinality(String), UInt64)+ usage_details: z.record(z.number()).optional(), // Map(LowCardinality(String), UInt64)+ provided_cost_details: z.record(z.number()).optional(), // Map(LowCardinality(String), Decimal64(12))+ cost_details: z.record(z.number()).optional(), // Map(LowCardinality(String), Decimal64(12))+ total_cost: z.number().optional(), // Nullable(Decimal64(12))+ completion_start_time: z.string().optional(), // Nullable(DateTime64(3))+ prompt_id: z.string().optional(),+ prompt_name: z.string().optional(),+ prompt_version: z.number().optional(), // Nullable(UInt16)+ created_at: z.string(), // DateTime64(3)+ updated_at: z.string(), // DateTime64(3)+ event_ts: z.string(), // DateTime64(3)+});++export type ObservationClickhouseRecord = z.infer<+ typeof ObservationClickhouseRecordSchema+>;++export const ScoreClickhouseRecordSchema = z.object({+ id: z.string(),+ timestamp: z.string(), // DateTime64(3)+ project_id: z.string(),+ trace_id: z.string(),+ observation_id: z.string().optional(),+ name: z.string(),+ value: z.number(),+ source: z.string(),+ comment: z.string().optional(),+ author_user_id: z.string().optional(),+ config_id: z.string().optional(),+ data_type: z.string(),+ string_value: z.string().optional(),+ created_at: z.string(), // DateTime64(3)+ updated_at: z.string(), // DateTime64(3)+ event_ts: z.string(), // DateTime64(3)+});++export type ScoreClickhouseRecord = z.infer<typeof ScoreClickhouseRecordSchema>;++export const ClickhouseTableNames = {+ traces: "traces",+ observations: "observations",+ scores: "scores",+} as const;++export type ClickhouseTableName = keyof typeof ClickhouseTableNames;++export const ClickhouseColumnDefinitionSchema = z.object({+ name: z.string(), // column name (camel case)+ clickhouse_mapping: z.string(), // clickhouse column name (snake case)+ type: z.enum(["number", "string", "datetime", "boolean", "map"]),+ nullable: z.boolean().optional(),+});++export type ClickhouseColumnDefinition = z.infer<+ typeof ClickhouseColumnDefinitionSchema+>;++export const TraceClickhouseColumns: ClickhouseColumnDefinition[] = [+ { name: "id", clickhouse_mapping: "id", type: "string" },+ { name: "timestamp", clickhouse_mapping: "timestamp", type: "datetime" },+ { name: "name", clickhouse_mapping: "name", type: "string" },+ {+ name: "userId",+ clickhouse_mapping: "user_id",+ type: "string",+ nullable: true,+ },+ { name: "metadata", clickhouse_mapping: "metadata", type: "string" },+ {+ name: "release",+ clickhouse_mapping: "release",+ type: "string",+ nullable: true,+ },+ {+ name: "version",+ clickhouse_mapping: "version",+ type: "string",+ nullable: true,+ },+ { name: "projectId", clickhouse_mapping: "project_id", type: "string" },+ { name: "public", clickhouse_mapping: "public", type: "boolean" },+ { name: "bookmarked", clickhouse_mapping: "bookmarked", type: "boolean" },+ { name: "tags", clickhouse_mapping: "tags", type: "string" },+ {+ name: "input",+ clickhouse_mapping: "input",+ type: "string",+ nullable: true,+ },+ {+ name: "output",+ clickhouse_mapping: "output",+ type: "string",+ nullable: true,+ },+ {+ name: "sessionId",+ clickhouse_mapping: "session_id",+ type: "string",+ nullable: true,+ },+ { name: "createdAt", clickhouse_mapping: "created_at", type: "datetime" },+ { name: "updatedAt", clickhouse_mapping: "updated_at", type: "datetime" },+ { name: "eventTs", clickhouse_mapping: "event_ts", type: "datetime" },+ { name: "level", clickhouse_mapping: "level", type: "string" },+];++export const ObservationClickhouseColumns: ClickhouseColumnDefinition[] = [+ { name: "id", clickhouse_mapping: "id", type: "string" },+ { name: "traceId", clickhouse_mapping: "trace_id", type: "string" },+ { name: "projectId", clickhouse_mapping: "project_id", type: "string" },+ { name: "type", clickhouse_mapping: "type", type: "string" },+ {+ name: "parentObservationId",+ clickhouse_mapping: "parent_observation_id",+ type: "string",+ nullable: true,+ },+ { name: "startTime", clickhouse_mapping: "start_time", type: "datetime" },+ {+ name: "endTime",+ clickhouse_mapping: "end_time",+ type: "datetime",+ nullable: true,+ },+ { name: "name", clickhouse_mapping: "name", type: "string" },+ { name: "metadata", clickhouse_mapping: "metadata", type: "string" },+ { name: "level", clickhouse_mapping: "level", type: "string" },+ {+ name: "statusMessage",+ clickhouse_mapping: "status_message",+ type: "string",+ nullable: true,+ },+ {+ name: "version",+ clickhouse_mapping: "version",+ type: "string",+ nullable: true,+ },+ {+ name: "input",+ clickhouse_mapping: "input",+ type: "string",+ nullable: true,+ },+ {+ name: "output",+ clickhouse_mapping: "output",+ type: "string",+ nullable: true,+ },+ {+ name: "providedModelName",+ clickhouse_mapping: "provided_model_name",+ type: "string",+ nullable: true,+ },+ {+ name: "internalModelId",+ clickhouse_mapping: "internal_model_id",+ type: "string",+ nullable: true,+ },+ {+ name: "modelParameters",+ clickhouse_mapping: "model_parameters",+ type: "string",+ nullable: true,+ },+ {+ name: "providedUsageDetails",+ clickhouse_mapping: "provided_usage_details",+ type: "map",+ nullable: true,+ },+ {+ name: "usageDetails",+ clickhouse_mapping: "usage_details",+ type: "map",+ nullable: true,+ },+ {+ name: "providedCostDetails",+ clickhouse_mapping: "provided_cost_details",+ type: "map",+ nullable: true,+ },+ {+ name: "costDetails",+ clickhouse_mapping: "cost_details",+ type: "map",+ nullable: true,+ },+ {+ name: "totalCost",+ clickhouse_mapping: "total_cost",+ type: "number",+ nullable: true,+ },+ {+ name: "completionStartTime",+ clickhouse_mapping: "completion_start_time",+ type: "datetime",+ nullable: true,+ },+ {+ name: "promptId",+ clickhouse_mapping: "prompt_id",+ type: "string",+ nullable: true,+ },+ {+ name: "promptName",+ clickhouse_mapping: "prompt_name",+ type: "string",+ nullable: true,+ },+ {+ name: "promptVersion",+ clickhouse_mapping: "prompt_version",+ type: "number",+ nullable: true,+ },+ { name: "createdAt", clickhouse_mapping: "created_at", type: "datetime" },+ { name: "updatedAt", clickhouse_mapping: "updated_at", type: "datetime" },+ { name: "eventTs", clickhouse_mapping: "event_ts", type: "datetime" },+];++export const ScoreClickhouseColumns: ClickhouseColumnDefinition[] = [+ { name: "id", clickhouse_mapping: "id", type: "string" },+ { name: "timestamp", clickhouse_mapping: "timestamp", type: "datetime" },+ { name: "projectId", clickhouse_mapping: "project_id", type: "string" },+ { name: "traceId", clickhouse_mapping: "trace_id", type: "string" },+ {+ name: "observationId",+ clickhouse_mapping: "observation_id",+ type: "string",+ nullable: true,+ },+ { name: "name", clickhouse_mapping: "name", type: "string" },+ { name: "value", clickhouse_mapping: "value", type: "number" },+ { name: "source", clickhouse_mapping: "source", type: "string" },+ {+ name: "comment",+ clickhouse_mapping: "comment",+ type: "string",+ nullable: true,+ },+ {+ name: "authorUserId",+ clickhouse_mapping: "author_user_id",+ type: "string",+ nullable: true,+ },+ {+ name: "configId",+ clickhouse_mapping: "config_id",+ type: "string",+ nullable: true,+ },+];diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 617a9bb875..829bd1ad3a 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -9,7 +9,9 @@ export * from "./llm/fetchLLMCompletion";export * from "./llm/types";export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";-export * from "./clickhouse";+export * from "./clickhouse/client";+export * from "./clickhouse/schema-utils";+export * from "./clickhouse/schema";export * from "../server/definitions";export * from "../server/ingestion/types";export * from "./ingestion/modelMatch";@@ -29,3 +31,4 @@ export * from "./filterToPrisma";export * from "./instrumentation";export * from "./logger";export * from "./queries";+export * from "./repositories";diff --git a/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.tsnew file mode 100644index 0000000000..ce69437f00--- /dev/null+++ b/packages/shared/src/server/queries/clickhouse-filter/clickhouse-filter.ts@@ -0,0 +1,253 @@+import { filterOperators } from "../../../interfaces/filters";++export interface Filter {+ apply(): ClickhouseFilter;+ clickhouseTable: string;+}+type ClickhouseFilter = {+ query: string;+ params: { [x: string]: any };+};++export class StringFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected value: string;+ protected operator: (typeof filterOperators)["string"][number];+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ operator: (typeof filterOperators)["string"][number];+ value: string;+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.value = opts.value;+ this.operator = opts.operator;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `stringFilter${this.field}`;++ const fieldWithPrefix = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;+ let query: string;+ switch (this.operator) {+ case "=":+ query = `${fieldWithPrefix} = {${varName}: String}`;+ break;+ case "contains":+ query = `position(${fieldWithPrefix}, {${varName}: String}) > 0`;+ break;+ case "does not contain":+ query = `position(${fieldWithPrefix}, {${varName}: String}) = 0`;+ break;+ case "starts with":+ query = `startsWith(${fieldWithPrefix}, {${varName}: String})`;+ break;+ case "ends with":+ query = `endsWith(${fieldWithPrefix}, {${varName}: String})`;+ break;+ default:+ throw new Error(`Unsupported operator: ${this.operator}`);+ }++ return {+ query: query,+ params: { [varName]: this.value },+ };+ }+}++export class NumberFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected value: number;+ protected operator: (typeof filterOperators)["number"][number];+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ operator: (typeof filterOperators)["number"][number];+ value: number;+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.value = opts.value;+ this.operator = opts.operator;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `stringFilter${this.field}`;+ return {+ query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} ${this.operator} {${varName}: String}`,+ params: { [varName]: this.value },+ };+ }+}++export class DateTimeFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected value: Date;+ protected operator: (typeof filterOperators)["datetime"][number];+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ operator: (typeof filterOperators)["datetime"][number];+ value: Date;+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.value = opts.value;+ this.operator = opts.operator;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `timeFilter${this.field}`;+ return {+ query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} ${this.operator} {${varName}: DateTime64(3)}`,+ params: { [varName]: new Date(this.value).getTime() },+ };+ }+}++export class StringOptionsFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected values: string[];+ protected operator: (typeof filterOperators.stringOptions)[number];+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ operator: (typeof filterOperators.stringOptions)[number];+ values: string[];+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.values = opts.values;+ this.operator = opts.operator;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `stringOptionsFilter${this.field}`;+ return {+ query:+ this.operator === "any of"+ ? `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`+ : `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = False`,+ params: { [varName]: this.values },+ };+ }+}++export class ArrayOptionsFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected values: string[];+ protected operator: (typeof filterOperators.arrayOptions)[number];+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ operator: (typeof filterOperators.arrayOptions)[number];+ values: string[];+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.values = opts.values;+ this.operator = opts.operator;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `arrayOptionsFilter${this.field}`;+ let query: string;++ switch (this.operator) {+ case "any of":+ query = `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;+ break;+ case "none of":+ query = `has({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = False`;+ break;+ case "all of":+ query = `arrayAll(x -> has({${varName}: Array(String)}, x), ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;+ break;+ default:+ throw new Error(`Unsupported operator: ${this.operator}`);+ }++ return {+ query,+ params: { [varName]: this.values },+ };+ }+}++export class BooleanFilter implements Filter {+ public clickhouseTable: string;+ protected field: string;+ protected value: boolean;+ protected tablePrefix?: string;++ constructor(opts: {+ clickhouseTable: string;+ field: string;+ value: boolean;+ tablePrefix?: string;+ }) {+ this.clickhouseTable = opts.clickhouseTable;+ this.field = opts.field;+ this.value = opts.value;+ this.tablePrefix = opts.tablePrefix;+ }++ apply(): ClickhouseFilter {+ const varName = `booleanFilter${this.field}`;+ return {+ query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} = {${varName}: Boolean}`,+ params: { [varName]: this.value },+ };+ }+}++export class FilterList {+ private filters: Filter[];++ constructor(filters: Filter[]) {+ this.filters = filters;+ }++ push(...filter: Filter[]) {+ this.filters.push(...filter);+ }++ public apply(): ClickhouseFilter {+ const queries = this.filters.map((filter) => filter.apply().query);+ const params = this.filters.reduce((acc, filter) => {+ return { ...acc, ...filter.apply().params };+ }, {});++ return {+ query: queries.join(" AND "),+ params,+ };+ }+}diff --git a/packages/shared/src/server/queries/clickhouse-filter/factory.ts b/packages/shared/src/server/queries/clickhouse-filter/factory.tsnew file mode 100644index 0000000000..51ad47161c--- /dev/null+++ b/packages/shared/src/server/queries/clickhouse-filter/factory.ts@@ -0,0 +1,210 @@+import z from "zod";+import { singleFilter } from "../../../interfaces/filters";+import { tracesTableUiColumnDefinitions } from "../../../tableDefinitions/mapTracesTable";+import { FilterCondition } from "../../../types";+import {+ ObservationClickhouseColumns,+ TraceClickhouseColumns,+} from "../../clickhouse/schema";+import {+ isKeyOfClickhouseRecord,+ isValidTableName,+} from "../../clickhouse/schema-utils";+import { logger } from "../../logger";+import { UiColumnMapping } from "../../../tableDefinitions";+import {+ StringFilter,+ DateTimeFilter,+ StringOptionsFilter,+ FilterList,+ NumberFilter,+ ArrayOptionsFilter,+ BooleanFilter,+} from "./clickhouse-filter";++export class QueryBuilderError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "QueryBuilderError";+ }+}++// This function ensures that the user only selects valid columns from the clickhouse schema.+// The filter property in this column needs to be zod verified.+// User input for values (e.g. project_id = <value>) are sent to Clickhouse as parameters to prevent SQL injection+export const createFilterFromFilterState = (+ filter: FilterCondition[],+ opts?: {+ tracesPrefix?: string;+ observationsPrefix?: string;+ scoresPrefix?: string;+ },+) => {+ return filter.map((frontEndFilter) => {+ // checks if the column exists in the clickhouse schema+ const { col, table } = matchAndVerifyTracesUiColumn(+ frontEndFilter,+ tracesTableUiColumnDefinitions,+ );++ const prefix =+ table === "observations" ? opts?.observationsPrefix : opts?.tracesPrefix;++ switch (frontEndFilter.type) {+ case "string":+ return new StringFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ operator: frontEndFilter.operator,+ value: frontEndFilter.value,+ tablePrefix: prefix,+ });+ case "datetime":+ return new DateTimeFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ operator: frontEndFilter.operator,+ value: frontEndFilter.value,+ tablePrefix: prefix,+ });+ case "stringOptions":+ return new StringOptionsFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ operator: frontEndFilter.operator,+ values: frontEndFilter.value,+ tablePrefix: prefix,+ });+ case "number":+ return new NumberFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ operator: frontEndFilter.operator,+ value: frontEndFilter.value,+ tablePrefix: prefix,+ });+ case "arrayOptions":+ return new ArrayOptionsFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ operator: frontEndFilter.operator,+ values: frontEndFilter.value,+ tablePrefix: prefix,+ });+ case "boolean":+ return new BooleanFilter({+ clickhouseTable: table,+ field: col.clickhouse_mapping,+ value: frontEndFilter.value,+ tablePrefix: prefix,+ });+ default:+ throw new QueryBuilderError(+ `Invalid filter type: ${frontEndFilter.type}`,+ );+ }+ });+};++const matchAndVerifyTracesUiColumn = (+ filter: z.infer<typeof singleFilter>,+ uiTableDefinitions: UiColumnMapping[],+) => {+ // 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, // matches on the NAME of the column in the UI.+ );++ if (!uiTable) {+ throw new QueryBuilderError(+ `Column ${filter.column} does not match a UI / CH table mapping.`,+ );+ }++ if (!isValidTableName(uiTable.clickhouseTableName)) {+ throw new QueryBuilderError(+ `Invalid clickhouse table name: ${uiTable.clickhouseTableName}`,+ );+ }++ if (+ !isKeyOfClickhouseRecord(+ uiTable.clickhouseTableName,+ uiTable.clickhouseColumnName,+ )+ ) {+ throw new QueryBuilderError(+ `Column ${uiTable.clickhouseColumnName} does not exist in table ${JSON.stringify(uiTable)}.`,+ );+ }++ if (uiTable.clickhouseTableName === "traces") {+ const column = TraceClickhouseColumns.find(+ (col) => col.name === uiTable.clickhouseColumnName,+ );+ if (!column) {+ throw new QueryBuilderError(+ `Column ${uiTable.clickhouseColumnName} does not exist in traces table.`,+ );+ }+ return {+ col: column,+ table: uiTable.clickhouseTableName,+ };+ } else if (uiTable.clickhouseTableName === "observations") {+ const column = ObservationClickhouseColumns.find(+ (col) => col.name === uiTable.clickhouseColumnName,+ );+ if (!column) {+ throw new QueryBuilderError(+ `Column ${uiTable.clickhouseColumnName} does not exist in observations table.`,+ );+ }+ return {+ col: column,+ table: uiTable.clickhouseTableName,+ };+ }+ throw new QueryBuilderError(+ `Unhandled table case: ${uiTable.clickhouseTableName}`,+ );+};++export function getProjectIdDefaultFilter(+ projectId: string,+ opts: { tracesPrefix: string },+): {+ tracesFilter: FilterList;+ scoresFilter: FilterList;+ observationsFilter: FilterList;+} {+ return {+ tracesFilter: new FilterList([+ new StringFilter({+ clickhouseTable: "traces",+ field: "project_id",+ operator: "=",+ value: projectId,+ tablePrefix: opts.tracesPrefix,+ }),+ ]),+ scoresFilter: new FilterList([+ new StringFilter({+ clickhouseTable: "scores",+ field: "project_id",+ operator: "=",+ value: projectId,+ }),+ ]),+ observationsFilter: new FilterList([+ new StringFilter({+ clickhouseTable: "observations",+ field: "project_id",+ operator: "=",+ value: projectId,+ }),+ ]),+ };+}diff --git a/packages/shared/src/server/queries/createTracesQuery.ts b/packages/shared/src/server/queries/createTracesQuery.tsindex 72580c7732..3fbe4ba21e 100644--- a/packages/shared/src/server/queries/createTracesQuery.ts+++ b/packages/shared/src/server/queries/createTracesQuery.ts@@ -4,7 +4,7 @@ import {datetimeFilterToPrismaSql,tableColumnsToSqlFilterAndPrefix,} from "../filterToPrisma";-import { tracesTableCols } from "../../tracesTable";+import { tracesTableCols } from "../../tableDefinitions/tracesTable";import { orderByToPrismaSql } from "../orderByToPrisma";export function parseTraceAllFilters(input: TableFilters) {diff --git a/web/src/server/api/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tssimilarity index 71%rename from web/src/server/api/repositories/clickhouse.tsrename to packages/shared/src/server/repositories/clickhouse.tsindex 0e3d00c7f7..b8311cc290 100644--- a/web/src/server/api/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -1,51 +1,56 @@+import Decimal from "decimal.js";+import { z } from "zod";+import { JsonNested } from "../../utils/zod";import {- parseJsonPrioritised,- type JsonNested,- type ObservationType,- type ObservationLevel,- type Trace,- type ObservationView,-} from "@langfuse/shared";+ ObservationLevel,+ ObservationType,+ ObservationView,+ Trace,+} from "@prisma/client";+import { parseJsonPrioritised } from "../../utils/json";+import { env } from "../../env";import {- clickhouseClient,clickhouseStringDateSchema,observationRecordReadSchema,scoreRecordReadSchema,traceRecordReadSchema,-} from "@langfuse/shared/src/server";-import Decimal from "decimal.js";-import { z } from "zod";+} from "../definitions";+import { clickhouseClient } from "../clickhouse/client";+import { logger } from "../logger";+import { getCurrentSpan } from "../instrumentation";export const getObservation = async (observationId: string,projectId: string,) => {- const query = `SELECT * FROM observations FINAL WHERE id = '${observationId}' AND project_id = '${projectId}' LIMIT 1`;- const records = await queryClickhouse(query);+ const query = `SELECT * FROM observations FINAL WHERE id = {observationId: String} AND project_id = {projectId: String} LIMIT 1`;+ const records = await queryClickhouse({+ query,+ params: { observationId, projectId },+ });- return records.length ? convertObservations(records)[0] : undefined;+ return convertObservations(records).shift();};export const getTraceObservations = async (traceId: string,projectId: string,) => {- const query = `SELECT * FROM observations FINAL where trace_id = '${traceId}' and project_id = '${projectId}'`;- const records = await queryClickhouse(query);+ const query = `SELECT * FROM observations FINAL WHERE trace_id = {traceId: String} AND project_id = {projectId: String}`;+ const records = await queryClickhouse({+ query,+ params: { traceId, projectId },+ });return convertObservations(records);};-export const getTrace = async (traceId: string, projectId: string) => {- const query = `SELECT * FROM traces FINAL where id = '${traceId}' and project_id = '${projectId}' LIMIT 1`;- const records = await queryClickhouse(query);-- return records.length ? convertTraces(records)[0] : undefined;-};-export const getScores = async (traceId: string, projectId: string) => {- const query = `SELECT * FROM scores FINAL where trace_id = '${traceId}' and project_id = '${projectId}'`;- const records = await queryClickhouse(query);+ const query = `SELECT * FROM scores FINAL where trace_id = {traceId: String} and project_id = {projectId: String}`;+ const records = await queryClickhouse({+ query,+ params: { traceId, projectId },+ });const parsedRecords = z.array(scoreRecordReadSchema).parse(records);return parsedRecords.map((record) => {@@ -79,13 +84,28 @@ export const convertRecordToJsonSchema = (return jsonSchema;};-async function queryClickhouse(query: string) {+export async function queryClickhouse<T>(opts: {+ query: string;+ params?: Record<string, unknown> | undefined;+}) {+ // https://opentelemetry.io/docs/specs/semconv/database/database-spans/+ getCurrentSpan()?.setAttribute("db.query.text", opts.query);++ // same logic as for prisma. we want to see queries in development+ if (env.NODE_ENV === "development") {+ logger.info(`clickhouse:query ${opts.query}`);+ }+return (- await clickhouseClient.query({ query, format: "JSONEachRow" })- ).json();+ await clickhouseClient.query({+ query: opts.query,+ format: "JSONEachRow",+ query_params: opts.params,+ })+ ).json<T>();}-function convertObservations(jsonRecords: unknown[]): ObservationView[] {+export function convertObservations(jsonRecords: unknown[]): ObservationView[] {const parsedRecord = z.array(observationRecordReadSchema).parse(jsonRecords);const parsedObservations = parsedRecord.map((record) => {diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsnew file mode 100644index 0000000000..c0f0bd503c--- /dev/null+++ b/packages/shared/src/server/repositories/index.ts@@ -0,0 +1,2 @@+export * from "./scores";+export * from "./traces";diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsnew file mode 100644index 0000000000..0389951c11--- /dev/null+++ b/packages/shared/src/server/repositories/scores.ts@@ -0,0 +1,104 @@+import { ScoreDataType, ScoreSource } from "@prisma/client";+import { queryClickhouse } from "./clickhouse";++export type FetchScoresReturnType = {+ id: string;+ timestamp: string;+ project_id: string;+ trace_id: string;+ observation_id: string | null;+ name: string;+ value: number;+ source: string;+ comment: string | null;+ author_user_id: string | null;+ config_id: string | null;+ data_type: string;+ string_value: string | null;+ queue_id: string | null;+ created_at: string;+ updated_at: string;+ event_ts: string;+ is_deleted: number;+ projectId: string;+};++const convertToScore = (row: FetchScoresReturnType) => {+ return {+ id: row.id,+ timestamp: new Date(row.timestamp),+ projectId: row.project_id,+ traceId: row.trace_id,+ observationId: row.observation_id,+ name: row.name,+ value: row.value,+ source: row.source as ScoreSource,+ comment: row.comment,+ authorUserId: row.author_user_id,+ configId: row.config_id,+ dataType: row.data_type as ScoreDataType,+ stringValue: row.string_value,+ queueId: row.queue_id,+ createdAt: new Date(row.created_at),+ updatedAt: new Date(row.updated_at),+ };+};++export const getScoresForTraces = async (+ projectId: string,+ traceIds: string[],+ limit: number,+ offset: number+) => {+ const query = `+ select+ *+ from scores s final+ WHERE s.project_id = {projectId: String}+ AND s.trace_id IN ({traceIds: Array(String)})+ limit {limit: Int32} offset {offset: Int32};+ `;++ const rows = await queryClickhouse<FetchScoresReturnType>({+ query: query,+ params: {+ projectId: projectId,+ traceIds: traceIds,+ limit: limit,+ offset: offset,+ },+ });++ return rows.map(convertToScore);+};++export const getScoresGroupedByNameSourceType = async (projectId: string) => {+ const query = `+ select+ name,+ source,+ data_type+ from scores s final+ WHERE s.project_id = {projectId: String}+ GROUP BY name, source, data_type+ ORDER BY count() desc+ LIMIT 1000;+ `;++ const rows = await queryClickhouse<{+ name: string;+ source: string;+ data_type: string;+ }>({+ query: query,+ params: {+ projectId: projectId,+ },+ });++ return rows.map((row) => ({+ name: row.name,+ source: row.source as ScoreSource,+ dataType: row.data_type as ScoreDataType,+ }));+};diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsnew file mode 100644index 0000000000..0cc03142f4--- /dev/null+++ b/packages/shared/src/server/repositories/traces.ts@@ -0,0 +1,158 @@+import { TraceClickhouseRecord } from "../clickhouse/schema";+import { queryClickhouse } from "./clickhouse";+import {+ createFilterFromFilterState,+ getProjectIdDefaultFilter,+} from "../queries/clickhouse-filter/factory";+import { ObservationLevel } from "@prisma/client";+import { FilterState } from "../../types";+import { logger } from "../logger";++export type TracesTableReturnType = Pick<+ TraceClickhouseRecord,+ | "project_id"+ | "id"+ | "name"+ | "timestamp"+ | "bookmarked"+ | "release"+ | "version"+ | "user_id"+ | "session_id"+ | "tags"+ | "metadata"+ | "public"+> & {+ level: ObservationLevel;+ observation_count: number | null;+ latency: number;+ usage_details: Record<string, number>;+ cost_details: Record<string, number>;+ scores_avg: Array<{ name: string; avg_value: number }>;+};++export const getTracesTable = async (+ projectId: string,+ filter: FilterState,+ limit?: number,+ offset?: number,+) => {+ logger.info(`input filter ${JSON.stringify(filter)}`);+ const { tracesFilter, scoresFilter, observationsFilter } =+ getProjectIdDefaultFilter(projectId, { tracesPrefix: "t" });++ tracesFilter.push(+ ...createFilterFromFilterState(filter, { tracesPrefix: "t" }),+ );++ const tracesFilterRes = tracesFilter.apply();+ const scoresAvgFilterRes = scoresFilter.apply();+ const observationsStatsRes = observationsFilter.apply();++ 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('seconds', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latencyMs,+ 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 ${observationsStatsRes.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 ${scoresAvgFilterRes.query}+ GROUP BY project_id,+ trace_id,+ name+ ) tmp+ GROUP BY project_id,+ trace_id)+ select+ t.id,+ t.project_id,+ t.timestamp,+ t.tags,+ t.bookmarked,+ t.name,+ t.release,+ t.version,+ t.user_id,+ t.session_id,+ os.latencyMs as latency,+ os.cost_details as cost_details,+ os.usage_details as usage_details,+ os.level as level,+ os.observation_count as observation_count,+ s.scores_avg as scores_avg,+ t.metadata,+ t.public+ 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}+ order by t.timestamp desc+ ${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}+ `;++ const rows = await queryClickhouse<TracesTableReturnType>({+ query: query,+ params: {+ limit: limit,+ offset: offset,+ ...tracesFilterRes.params,+ ...observationsStatsRes.params,+ ...scoresAvgFilterRes.params,+ },+ });++ return rows;+};++export const getTraceById = async (traceId: string, projectId: string) => {+ const query = `SELECT * FROM traces where id = {traceId: String} and project_id = {projectId: String} order by event_ts desc LIMIT 1 by id, project_id`;+ const records = await queryClickhouse<TraceClickhouseRecord>({+ query,+ params: { traceId, projectId },+ });++ const res = records.map((record) => {+ return {+ id: record.id,+ projectId: record.project_id,+ name: record.name,+ timestamp: new Date(record.timestamp),+ tags: record.tags,+ bookmarked: record.bookmarked,+ release: record.release,+ version: record.version,+ userId: record.user_id,+ sessionId: record.session_id,+ public: record.public,+ input: record.input,+ output: record.output,+ metadata: record.metadata,+ };+ });++ return res.length ? res[0] : undefined;+};diff --git a/packages/shared/src/tableDefinitions/mapTracesTable.ts b/packages/shared/src/tableDefinitions/mapTracesTable.tsnew file mode 100644index 0000000000..7122e8a284--- /dev/null+++ b/packages/shared/src/tableDefinitions/mapTracesTable.ts@@ -0,0 +1,102 @@+// This structure is maintained to relate the frontend table definitions with the clickhouse table definitions.+// The frontend only sends the column names to the backend. This needs to be changed in the future to send column IDs.++import { UiColumnMapping } from "./types";++export const tracesTableUiColumnDefinitions: UiColumnMapping[] = [+ {+ uiTableName: "bookmarked",+ clickhouseTableName: "traces",+ clickhouseColumnName: "bookmarked",+ },+ {+ uiTableName: "Level",+ clickhouseTableName: "observations",+ clickhouseColumnName: "level",+ },+ {+ uiTableName: "ID",+ clickhouseTableName: "traces",+ clickhouseColumnName: "id",+ },+ {+ uiTableName: "Name",+ clickhouseTableName: "traces",+ clickhouseColumnName: "name",+ },+ {+ uiTableName: "Timestamp",+ clickhouseTableName: "traces",+ clickhouseColumnName: "timestamp",+ },+ {+ uiTableName: "User ID",+ clickhouseTableName: "traces",+ clickhouseColumnName: "userId",+ },+ {+ uiTableName: "Session ID",+ clickhouseTableName: "traces",+ clickhouseColumnName: "sessionId",+ },+ {+ uiTableName: "Metadata",+ clickhouseTableName: "traces",+ clickhouseColumnName: "metadata",+ },+ {+ uiTableName: "Version",+ clickhouseTableName: "traces",+ clickhouseColumnName: "version",+ },+ {+ uiTableName: "Release",+ clickhouseTableName: "traces",+ clickhouseColumnName: "release",+ },+ {+ uiTableName: "Tags",+ clickhouseTableName: "traces",+ clickhouseColumnName: "tags",+ },+ {+ uiTableName: "Input Tokens",+ clickhouseTableName: "traces",+ clickhouseColumnName: "promptTokens",+ },+ {+ uiTableName: "Output Tokens",+ clickhouseTableName: "traces",+ clickhouseColumnName: "completionTokens",+ },+ {+ uiTableName: "Total Tokens",+ clickhouseTableName: "traces",+ clickhouseColumnName: "totalTokens",+ },+ {+ uiTableName: "Usage",+ clickhouseTableName: "traces",+ clickhouseColumnName: "totalTokens",+ },+ {+ uiTableName: "Latency (s)",+ clickhouseTableName: "traces",+ clickhouseColumnName: "latency",+ },+ {+ uiTableName: "Input Cost ($)",+ clickhouseTableName: "traces",+ clickhouseColumnName: "calculatedInputCost",+ },+ {+ uiTableName: "Output Cost ($)",+ clickhouseTableName: "traces",+ clickhouseColumnName: "calculatedOutputCost",+ },+ {+ uiTableName: "Total Cost ($)",+ clickhouseTableName: "traces",+ clickhouseColumnName: "calculatedTotalCost",+ },+];diff --git a/packages/shared/src/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.tssimilarity index 96%rename from packages/shared/src/tracesTable.tsrename to packages/shared/src/tableDefinitions/tracesTable.tsindex 1bdf044d74..3451bbcf70 100644--- a/packages/shared/src/tracesTable.ts+++ b/packages/shared/src/tableDefinitions/tracesTable.ts@@ -1,7 +1,7 @@import { ObservationLevel } from "@prisma/client";-import { ColumnDefinition, OptionsDefinition } from ".";+import { ColumnDefinition, OptionsDefinition } from "..";-const tracesOnlyCols: ColumnDefinition[] = [+export const tracesOnlyCols: ColumnDefinition[] = [{name: "⭐️",id: "bookmarked",diff --git a/packages/shared/src/tableDefinitions/types.ts b/packages/shared/src/tableDefinitions/types.tsindex e5bda80422..3e55835b0b 100644--- a/packages/shared/src/tableDefinitions/types.ts+++ b/packages/shared/src/tableDefinitions/types.ts@@ -1,3 +1,9 @@+export type UiColumnMapping = {+ uiTableName: string;+ clickhouseTableName: string;+ clickhouseColumnName: string;+};+export type OptionsDefinition = {value: string;count?: number;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 56766ad540..dddea21c23 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11620,7 +11620,7 @@ snapshots:'@aws-sdk/client-sso-oidc': 3.675.0(@aws-sdk/[email protected])'@aws-sdk/client-sts': 3.675.0'@aws-sdk/core': 3.667.0- '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])'@aws-sdk/middleware-host-header': 3.667.0'@aws-sdk/middleware-logger': 3.667.0'@aws-sdk/middleware-recursion-detection': 3.667.0@@ -12124,7 +12124,7 @@ snapshots:- '@aws-sdk/client-sso-oidc'- aws-crt- '@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])':+ '@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])':dependencies:'@aws-sdk/client-sts': 3.675.0'@aws-sdk/core': 3.667.0@@ -12201,30 +12201,11 @@ snapshots:- '@aws-sdk/client-sts'- aws-crt- '@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])':- dependencies:- '@aws-sdk/credential-provider-env': 3.667.0- '@aws-sdk/credential-provider-http': 3.667.0- '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])- '@aws-sdk/credential-provider-process': 3.667.0- '@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))- '@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])- '@aws-sdk/types': 3.667.0- '@smithy/credential-provider-imds': 3.2.4- '@smithy/property-provider': 3.1.7- '@smithy/shared-ini-file-loader': 3.1.8- '@smithy/types': 3.5.0- tslib: 2.6.3- transitivePeerDependencies:- - '@aws-sdk/client-sso-oidc'- - '@aws-sdk/client-sts'- - aws-crt-'@aws-sdk/[email protected](@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])':dependencies:'@aws-sdk/credential-provider-env': 3.667.0'@aws-sdk/credential-provider-http': 3.667.0- '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])+ '@aws-sdk/credential-provider-ini': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])'@aws-sdk/credential-provider-process': 3.667.0'@aws-sdk/credential-provider-sso': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))'@aws-sdk/credential-provider-web-identity': 3.667.0(@aws-sdk/[email protected])diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsxindex 26c43c359a..b31016f320 100644--- a/web/src/components/table/use-cases/generations.tsx+++ b/web/src/components/table/use-cases/generations.tsx@@ -55,6 +55,7 @@ import {} from "@/src/components/ui/dropdown-menu";import { Button } from "@/src/components/ui/button";import { ChevronDownIcon, Loader } from "lucide-react";+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";export type GenerationsTableRow = {id: string;@@ -187,6 +188,7 @@ export default function GenerationsTable({page: paginationState.pageIndex,limit: paginationState.pageSize,orderBy: orderByState,+ queryClickhouse: useClickhouse(),};const generations = api.generations.all.useQuery(getAllPayload);diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex f360f8875d..7e0535d75f 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -49,6 +49,7 @@ import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCimport { Skeleton } from "@/src/components/ui/skeleton";import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";export type TracesTableRow = {bookmarked: boolean;@@ -154,6 +155,7 @@ export default function TracesTable({page: paginationState.pageIndex,limit: paginationState.pageSize,orderBy: orderByState,+ queryClickhouse: useClickhouse(),};const traces = api.traces.all.useQuery(tracesAllQueryFilter);const totalCountQuery = api.traces.countAll.useQuery(tracesAllCountFilter);@@ -161,6 +163,7 @@ export default function TracesTable({{projectId,traceIds: traces.data?.traces.map((t) => t.id) ?? [],+ queryClickhouse: useClickhouse(),},{enabled: traces.data !== undefined,@@ -726,7 +729,6 @@ export default function TracesTable({}) ?? []): [];}, [traces, traceRowData, scoreKeysAndProps]);-return (<><DataTableToolbar@@ -818,7 +820,7 @@ const TracesDynamicCell = ({singleLine?: boolean;}) => {const trace = api.traces.byId.useQuery(- { traceId, projectId },+ { traceId, projectId, queryClickhouse: useClickhouse() },{enabled: typeof traceId === "string",trpc: {diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsxindex fa7e783798..335fa261c8 100644--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx@@ -18,6 +18,7 @@ import { NumericScoreHistogram } from "@/src/features/dashboard/components/scoreimport DocPopup from "@/src/components/layouts/doc-popup";import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";import { Flex, Text } from "@tremor/react";+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";export function ScoreAnalytics(props: {className?: string;@@ -33,6 +34,7 @@ export function ScoreAnalytics(props: {{projectId: props.projectId,selectedTimeOption: { option: props.agg, filterSource: "DASHBOARD" },+ queryClickhouse: useClickhouse(),},{trpc: {diff --git a/web/src/features/scores/hooks/useIndividualScoreColumns.ts b/web/src/features/scores/hooks/useIndividualScoreColumns.tsindex f7f07e2a0c..644a047a64 100644--- a/web/src/features/scores/hooks/useIndividualScoreColumns.ts+++ b/web/src/features/scores/hooks/useIndividualScoreColumns.ts@@ -3,6 +3,7 @@ import { api } from "@/src/utils/api";import { type TableRowTypesWithIndividualScoreColumns } from "@/src/features/scores/lib/types";import { constructIndividualScoreColumns } from "@/src/features/scores/components/ScoreDetailColumnHelpers";import { type TableDateRangeOptions } from "@/src/utils/date-range-utils";+import { useClickhouse } from "@/src/components/layouts/ClickhouseAdminToggle";export function useIndividualScoreColumns<T extends TableRowTypesWithIndividualScoreColumns,@@ -24,6 +25,7 @@ export function useIndividualScoreColumns<const scoreKeysAndProps = api.scores.getScoreKeysAndProps.useQuery({projectId,+ queryClickhouse: useClickhouse(),...(selectedFilterOption? {selectedTimeOption: {diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.tsindex 0936d16434..8c8de8aac6 100644--- a/web/src/server/api/routers/generations/getAllQueries.ts+++ b/web/src/server/api/routers/generations/getAllQueries.ts@@ -1,4 +1,4 @@-import { type z } from "zod";+import { z } from "zod";import { protectedProjectProcedure } from "@/src/server/api/trpc";import { paginationZod } from "@langfuse/shared";@@ -7,28 +7,48 @@ import { Prisma } from "@langfuse/shared/src/db";import { GenerationTableOptions } from "./utils/GenerationTableOptions";import { getAllGenerations } from "@/src/server/api/routers/generations/db/getAllGenerationsSqlQuery";import { parseGetAllGenerationsInput } from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";-const getAllGenerationsInput = GenerationTableOptions.extend({+const GetAllGenerationsInput = GenerationTableOptions.extend({...paginationZod,});-export type GetAllGenerationsInput = z.infer<typeof getAllGenerationsInput>;+export type GetAllGenerationsInput = z.infer<typeof GetAllGenerationsInput>;export const getAllQueries = {all: protectedProjectProcedure- .input(getAllGenerationsInput)- .query(async ({ input }) => {- const { generations } = await getAllGenerations({- input,- selectIOAndMetadata: false,- });+ .input(+ GetAllGenerationsInput.extend({+ queryClickhouse: z.boolean().default(false),+ }),+ )+ .query(async ({ input, ctx }) => {+ if (!input.queryClickhouse) {+ const { generations } = await getAllGenerations({+ input,+ selectIOAndMetadata: false,+ });- return {- generations: generations,- };+ return {+ generations: generations,+ };+ } else {+ if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }++ throw new TRPCError({+ code: "NOT_IMPLEMENTED",+ message: "Clickhouse query not implemented yet",+ });+ }}),countAll: protectedProjectProcedure- .input(getAllGenerationsInput)+ .input(GetAllGenerationsInput).query(async ({ input, ctx }) => {const { searchCondition, filterCondition, datetimeFilter } =parseGetAllGenerationsInput(input);diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 885a1fe8ac..0fc495cd5a 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -28,9 +28,12 @@ import { Prisma, type Score } from "@langfuse/shared/src/db";import {datetimeFilterToPrisma,datetimeFilterToPrismaSql,+ getScoresGroupedByNameSourceType,orderByToPrismaSql,tableColumnsToSqlFilterAndPrefix,} from "@langfuse/shared/src/server";+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";+import { TRPCError } from "@trpc/server";const ScoreFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -336,32 +339,51 @@ export const scoresRouter = createTRPCRouter({z.object({projectId: z.string(),selectedTimeOption: SelectedTimeOptionSchema,+ queryClickhouse: z.boolean().default(false),}),).query(async ({ input, ctx }) => {const date = getDateFromOption(input.selectedTimeOption);- const scores = await ctx.prisma.score.groupBy({- where: {- projectId: input.projectId,- ...(date ? { timestamp: { gte: date } } : {}),- },- take: 1000,- orderBy: {- _count: {- id: "desc",+ if (!input.queryClickhouse) {+ const scores = await ctx.prisma.score.groupBy({+ where: {+ projectId: input.projectId,+ ...(date ? { timestamp: { gte: date } } : {}),},- },- by: ["name", "source", "dataType"],- });+ take: 1000,+ orderBy: {+ _count: {+ id: "desc",+ },+ },+ by: ["name", "source", "dataType"],+ });++ if (scores.length === 0) return [];+ return scores.map(({ name, source, dataType }) => ({+ key: composeAggregateScoreKey({ name, source, dataType }),+ name: name,+ source: source,+ dataType: dataType,+ }));+ } else {+ if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }- if (scores.length === 0) return [];- return scores.map(({ name, source, dataType }) => ({- key: composeAggregateScoreKey({ name, source, dataType }),- name: name,- source: source,- dataType: dataType,- }));+ const res = await getScoresGroupedByNameSourceType(input.projectId);++ return res.map(({ name, source, dataType }) => ({+ key: composeAggregateScoreKey({ name, source, dataType }),+ name: name,+ source: source,+ dataType: dataType,+ }));+ }}),});diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex eeef8f9dd7..0d10af7032 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -29,9 +29,15 @@ import {traceException,createTracesQuery,parseTraceAllFilters,+ getTracesTable,+ getScoresForTraces,+ getTraceById,+ type TracesTableReturnType,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";-import type Decimal from "decimal.js";+import Decimal from "decimal.js";+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";+import { type ScoreAggregate } from "@/src/features/scores/lib/types";const TraceFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -49,6 +55,76 @@ export type ObservationReturnType = Omit<traceId: string;};+export type TracesAllReturnType = {+ id: string;+ timestamp: Date;+ name: string | undefined;+ projectId: string;+ userId: string | undefined;+ release: string | undefined;+ version: string | undefined;+ public: boolean;+ bookmarked: boolean;+ sessionId: string | undefined;+ tags: string[];+};++export const convertToReturnType = (+ row: TracesTableReturnType,+): TracesAllReturnType => {+ return {+ id: row.id,+ name: row.name,+ timestamp: new Date(row.timestamp),+ tags: row.tags,+ bookmarked: row.bookmarked,+ release: row.release,+ version: row.version,+ projectId: row.project_id,+ userId: row.user_id,+ sessionId: row.session_id,+ public: row.public,+ };+};++export type TracesMetricsReturnType = {+ id: string;+ promptTokens: bigint;+ completionTokens: bigint;+ totalTokens: bigint;+ latency: number | null;+ level: ObservationLevel;+ observationCount: bigint;+ calculatedTotalCost: Decimal | null;+ calculatedInputCost: Decimal | null;+ calculatedOutputCost: Decimal | null;+ scores: ScoreAggregate;+};++export const convertMetricsReturnType = (+ row: TracesTableReturnType & { scores: ScoreAggregate },+): TracesMetricsReturnType => {+ return {+ id: row.id,+ promptTokens: BigInt(row.usage_details?.input ?? 0),+ completionTokens: BigInt(row.usage_details?.output ?? 0),+ totalTokens: BigInt(row.usage_details?.total ?? 0),+ latency: row.latency,+ level: row.level,+ observationCount: BigInt(row.observation_count ?? 0),+ calculatedTotalCost: row.cost_details?.total+ ? new Decimal(row.cost_details.total)+ : null,+ calculatedInputCost: row.cost_details?.input+ ? new Decimal(row.cost_details.input)+ : null,+ calculatedOutputCost: row.cost_details?.output+ ? new Decimal(row.cost_details.output)+ : null,+ scores: row.scores,+ };+};+export const traceRouter = createTRPCRouter({hasAny: protectedProjectProcedure.input(z.object({ projectId: z.string() }))@@ -64,40 +140,70 @@ export const traceRouter = createTRPCRouter({return hasAny !== null;}),all: protectedProjectProcedure- .input(TraceFilterOptions)+ .input(+ TraceFilterOptions.extend({+ queryClickhouse: z.boolean().default(false),+ }),+ ).query(async ({ input, ctx }) => {- const {- filterCondition,- orderByCondition,- observationTimeseriesFilter,- searchCondition,- } = parseTraceAllFilters(input);+ if (!input.queryClickhouse) {+ const {+ filterCondition,+ orderByCondition,+ observationTimeseriesFilter,+ searchCondition,+ } = parseTraceAllFilters(input);- const tracesQuery = createTracesQuery({- select: Prisma.sql`+ const tracesQuery = createTracesQuery({+ select: Prisma.sql`t.*,t."user_id" AS "userId",t.session_id AS "sessionId"`,- projectId: input.projectId,- observationTimeseriesFilter,- page: input.page,- limit: input.limit,- searchCondition,- filterCondition,- orderByCondition,- });+ projectId: input.projectId,+ observationTimeseriesFilter,+ page: input.page,+ limit: input.limit,+ searchCondition,+ filterCondition,+ orderByCondition,+ });- const traces = await ctx.prisma.$queryRaw<Array<Trace>>(tracesQuery);+ const traces = await ctx.prisma.$queryRaw<Array<Trace>>(tracesQuery);- return {- traces: traces.map(- // eslint-disable-next-line @typescript-eslint/no-unused-vars- ({ input, output, metadata, ...trace }) => ({- ...trace,- }),- ),- };+ return {+ traces: traces.map<TracesAllReturnType>(+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ ({ input, output, metadata, ...trace }) => ({+ ...trace,+ name: trace.name ?? undefined,+ release: trace.release ?? undefined,+ version: trace.version ?? undefined,+ externalId: trace.externalId ?? undefined,+ userId: trace.userId ?? undefined,+ sessionId: trace.sessionId ?? undefined,+ }),+ ),+ };+ } else {+ if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }++ const res = await getTracesTable(+ ctx.session.projectId,+ input.filter ?? [],+ input.limit,+ input.page,+ );++ return {+ traces: res.map(convertToReturnType),+ };+ }}),countAll: protectedProjectProcedure.input(TraceFilterOptions)@@ -128,12 +234,15 @@ export const traceRouter = createTRPCRouter({z.object({projectId: z.string(),traceIds: z.array(z.string()),+ queryClickhouse: z.boolean().default(false),}),).query(async ({ input, ctx }) => {if (input.traceIds.length === 0) return [];- const tracesQuery = createTracesQuery({- select: Prisma.sql`++ if (!input.queryClickhouse) {+ const tracesQuery = createTracesQuery({+ select: Prisma.sql`t.id,COALESCE(generation_metrics."promptTokens", 0)::bigint AS "promptTokens",COALESCE(generation_metrics."completionTokens", 0)::bigint AS "completionTokens",@@ -145,48 +254,70 @@ export const traceRouter = createTRPCRouter({COALESCE(generation_metrics."calculatedOutputCost", 0)::numeric AS "calculatedOutputCost",observation_metrics."level" AS "level"`,- projectId: input.projectId,- filterCondition: Prisma.sql`AND t.id IN (${Prisma.join(input.traceIds)})`,- });+ projectId: input.projectId,+ filterCondition: Prisma.sql`AND t.id IN (${Prisma.join(input.traceIds)})`,+ });- const [traceMetrics, scores] = await Promise.all([- // traceMetrics- ctx.prisma.$queryRaw<- Array<{- id: string;- promptTokens: bigint;- completionTokens: bigint;- totalTokens: bigint;- latency: number | null;- level: ObservationLevel;- observationCount: bigint;- calculatedTotalCost: Decimal | null;- calculatedInputCost: Decimal | null;- calculatedOutputCost: Decimal | null;- }>- >(tracesQuery),- // scores- ctx.prisma.score.findMany({- where: {- projectId: input.projectId,- traceId: {- in: input.traceIds,+ const [traceMetrics, scores] = await Promise.all([+ // traceMetrics+ ctx.prisma.$queryRaw<Array<TracesMetricsReturnType>>(tracesQuery),+ // scores+ ctx.prisma.score.findMany({+ where: {+ projectId: input.projectId,+ traceId: {+ in: input.traceIds,+ },},- },- }),- ]);+ }),+ ]);- const validatedScores = filterAndValidateDbScoreList(- scores,- traceException,- );+ const validatedScores = filterAndValidateDbScoreList(+ scores,+ traceException,+ );++ return traceMetrics.map((row) => ({+ ...row,+ scores: aggregateScores(+ validatedScores.filter((s) => s.traceId === row.id),+ ),+ }));+ } else {+ if (!isClickhouseEligible(ctx.session.user.admin === true)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }++ const res = await getTracesTable(+ ctx.session.projectId,+ [],+ // input.filter+ );- return traceMetrics.map((row) => ({- ...row,- scores: aggregateScores(- validatedScores.filter((s) => s.traceId === row.id),- ),- }));+ const scores = await getScoresForTraces(+ ctx.session.projectId,+ res.map((r) => r.id),+ 1000,+ 0,+ );++ const validatedScores = filterAndValidateDbScoreList(+ scores,+ traceException,+ );++ return res.map((r) =>+ convertMetricsReturnType({+ ...r,+ scores: aggregateScores(+ validatedScores.filter((s) => s.traceId === r.id),+ ),+ }),+ );+ }}),filterOptions: protectedProjectProcedure.input(@@ -258,16 +389,27 @@ export const traceRouter = createTRPCRouter({z.object({traceId: z.string(), // used for security checkprojectId: z.string(), // used for security check+ queryClickhouse: z.boolean().default(false),}),).query(async ({ input, ctx }) => {- const trace = await ctx.prisma.trace.findFirstOrThrow({- where: {- id: input.traceId,- projectId: input.projectId,- },- });- return trace;+ if (!input.queryClickhouse) {+ return await ctx.prisma.trace.findFirstOrThrow({+ where: {+ id: input.traceId,+ projectId: input.projectId,+ },+ });+ } else {+ if (!isClickhouseEligible(ctx.session.user?.admin === true)) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Not eligible to query clickhouse",+ });+ }++ return await getTraceById(input.traceId, input.projectId);+ }}),byIdWithObservationsAndScores: protectedGetTraceProcedure.input(diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 51aa878621..98cab4f8b4 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -78,7 +78,12 @@ import superjson from "superjson";import { ZodError } from "zod";import { setUpSuperjson } from "@/src/utils/superjson";import { DB } from "@/src/server/db";-import { addUserToSpan, logger } from "@langfuse/shared/src/server";+import {+ addUserToSpan,+ getTraceById,+ logger,+} from "@langfuse/shared/src/server";+import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";setUpSuperjson();@@ -313,10 +318,12 @@ export const protectedOrganizationProcedure = withOtelTracingProcedureconst inputTraceSchema = z.object({traceId: z.string(),projectId: z.string(),+ queryClickhouse: z.boolean().nullable(),});const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {const result = inputTraceSchema.safeParse(rawInput);+if (!result.success)throw new TRPCError({code: "BAD_REQUEST",@@ -326,15 +333,20 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {const traceId = result.data.traceId;const projectId = result.data.projectId;- const trace = await prisma.trace.findFirst({- where: {- id: traceId,- projectId: projectId,- },- select: {- public: true,- },- });+ // if the user is eligible for clickhouse, and wants to use clickhouse, do so.+ const trace =+ result.data.queryClickhouse === true &&+ isClickhouseEligible(ctx.session?.user?.admin === true)+ ? await getTraceById(traceId, projectId)+ : await prisma.trace.findFirst({+ where: {+ id: traceId,+ projectId: projectId,+ },+ select: {+ public: true,+ },+ });if (!trace)throw new TRPCError({diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.tsnew file mode 100644index 0000000000..19927ba029--- /dev/null+++ b/web/src/server/utils/checkClickhouseAccess.ts@@ -0,0 +1,5 @@+import { env } from "@/src/env.mjs";++export const isClickhouseEligible = (admin: boolean) => {+ return admin === true && env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+};diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex bd09dbbd89..e2de5ea990 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -23,10 +23,10 @@ import {traceRecordReadSchema,ClickhouseClientType,validateAndInflateScore,- ClickhouseEntityType,PromptService,IngestionEventType,UsageCostType,+ IngestionEntityTypes,} from "@langfuse/shared/src/server";import { tokenCount } from "../../features/tokenisation/usage";@@ -75,7 +75,7 @@ export class IngestionService {}public async mergeAndWrite(- eventType: ClickhouseEntityType,+ eventType: IngestionEntityTypes,projectId: string,eventBodyId: string,events: IngestionEventType[],@@ -85,19 +85,19 @@ export class IngestionService {);switch (eventType) {- case ClickhouseEntityType.Trace:+ case "trace":return await this.processTraceEventList({projectId,entityId: eventBodyId,traceEventList: events as TraceEventType[],});- case ClickhouseEntityType.Observation:+ case "observation":return await this.processObservationEventList({projectId,entityId: eventBodyId,observationEventList: events as ObservationEvent[],});- case ClickhouseEntityType.Score: {+ case "score": {return await this.processScoreEventList({projectId,entityId: eventBodyId,