Skip to content

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

feat: steer reading from CH and PG (#4153)

Max Deichmannb147560a8062
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.ts
index 8e21ccf4d2..697f6a8065 100644
--- a/packages/shared/src/server/instrumentation/index.ts
+++ b/packages/shared/src/server/instrumentation/index.ts
@@ -38,7 +38,7 @@ export async function instrumentAsync<T>(
return getTracer(ctx.traceScope ?? callback.name).startActiveSpan(
ctx.name,
{
- root: !Boolean(ctx.traceContext) && ctx.rootSpan,
+ root: !ctx.traceContext && ctx.rootSpan,
kind: ctx.spanKind,
},
activeContext,
@@ -72,7 +72,7 @@ export function instrumentSync<T>(
return getTracer(ctx.traceScope ?? callback.name).startActiveSpan(
ctx.name,
{
- root: !Boolean(ctx.traceContext) && ctx.rootSpan,
+ root: !ctx.traceContext && ctx.rootSpan,
kind: ctx.spanKind,
},
activeContext,
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 8baea5a672..0f9818c547 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -191,6 +191,8 @@ export const env = createEnv({
.number()
.nonnegative()
.default(15_000),
+ LANGFUSE_READ_FROM_POSTGRES_ONLY: z.enum(["true", "false"]).default("true"),
+ LANGFUSE_RETURN_FROM_CLICKHOUSE: z.enum(["true", "false"]).default("false"),
STRIPE_SECRET_KEY: z.string().optional(),
STRIPE_WEBHOOK_SIGNING_SECRET: z.string().optional(),
SENTRY_AUTH_TOKEN: z.string().optional(),
@@ -395,6 +397,10 @@ export const env = createEnv({
process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
LANGFUSE_INGESTION_QUEUE_DELAY_MS:
process.env.LANGFUSE_INGESTION_QUEUE_DELAY_MS,
+ LANGFUSE_READ_FROM_POSTGRES_ONLY:
+ process.env.LANGFUSE_READ_FROM_POSTGRES_ONLY,
+ LANGFUSE_RETURN_FROM_CLICKHOUSE:
+ process.env.LANGFUSE_RETURN_FROM_CLICKHOUSE,
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SIGNING_SECRET: process.env.STRIPE_WEBHOOK_SIGNING_SECRET,
SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 71506e4895..006a3c493e 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -50,7 +50,10 @@ import {
convertTraceDomainToClickhouse,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
-import { isClickhouseEligible } from "@/src/server/utils/checkClickhouseAccess";
+import {
+ isClickhouseEligible,
+ measureAndReturnApi,
+} from "@/src/server/utils/checkClickhouseAccess";
const TraceFilterOptions = z.object({
projectId: z.string(), // Required for protectedProjectProcedure
@@ -89,66 +92,72 @@ export const traceRouter = createTRPCRouter({
}),
)
.query(async ({ input, ctx }) => {
- if (!input.queryClickhouse) {
- const {
- filterCondition,
- orderByCondition,
- observationTimeseriesFilter,
- searchCondition,
- } = parseTraceAllFilters(input);
-
- 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,
- });
-
- const traces = await ctx.prisma.$queryRaw<Array<Trace>>(tracesQuery);
-
- return {
- traces: traces.map<TracesAllReturnType>(
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- ({ input, output, metadata, ...trace }) => ({
- ...trace,
- name: trace.name,
- release: trace.release,
- version: trace.version,
- externalId: trace.externalId,
- userId: trace.userId,
- sessionId: trace.sessionId,
- }),
- ),
- };
- } else {
- if (!isClickhouseEligible(ctx.session.user)) {
- throw new TRPCError({
- code: "UNAUTHORIZED",
- message: "Not eligible to query clickhouse",
+ return await measureAndReturnApi({
+ input,
+ operation: "traces.all",
+ user: ctx.session.user,
+ pgExecution: async () => {
+ const {
+ filterCondition,
+ orderByCondition,
+ observationTimeseriesFilter,
+ searchCondition,
+ } = parseTraceAllFilters(input);
+
+ 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,
});
- }
- const res = await getTracesTable(
- ctx.session.projectId,
- input.filter ?? [],
- input.searchQuery ?? undefined,
- input.orderBy,
- input.limit,
- input.page,
- );
+ const traces = await ctx.prisma.$queryRaw<Array<Trace>>(tracesQuery);
+
+ return {
+ traces: traces.map<TracesAllReturnType>(
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ ({ input, output, metadata, ...trace }) => ({
+ ...trace,
+ name: trace.name,
+ release: trace.release,
+ version: trace.version,
+ externalId: trace.externalId,
+ userId: trace.userId,
+ sessionId: trace.sessionId,
+ }),
+ ),
+ };
+ },
+ clickhouseExecution: async () => {
+ if (!isClickhouseEligible(ctx.session.user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
- return {
- traces: res.map(convertToReturnType),
- };
- }
+ const res = await getTracesTable(
+ ctx.session.projectId,
+ input.filter ?? [],
+ input.searchQuery ?? undefined,
+ input.orderBy,
+ input.limit,
+ input.page,
+ );
+
+ return {
+ traces: res.map(convertToReturnType),
+ };
+ },
+ });
}),
countAll: protectedProjectProcedure
.input(
diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.ts
index abd609f524..f17ce101c8 100644
--- a/web/src/server/utils/checkClickhouseAccess.ts
+++ b/web/src/server/utils/checkClickhouseAccess.ts
@@ -1,5 +1,8 @@
import { env } from "@/src/env.mjs";
+import { instrumentAsync, logger } from "@langfuse/shared/src/server";
import { type User } from "next-auth";
+import * as opentelemetry from "@opentelemetry/api";
+import { TRPCError } from "@trpc/server";
export const isClickhouseEligible = (user?: User | null) => {
return (
@@ -12,3 +15,80 @@ export const isClickhouseEligible = (user?: User | null) => {
)
);
};
+
+export const measureAndReturnApi = async <T, Y>(args: {
+ input: T & { queryClickhouse: boolean };
+ user: User | undefined;
+ operation: string;
+ pgExecution: (input: T) => Promise<Y>;
+ clickhouseExecution: (input: T) => Promise<Y>;
+}) => {
+ return instrumentAsync(
+ {
+ name: "clickhouse-experiment",
+ spanKind: opentelemetry.SpanKind.INTERNAL,
+ },
+ async (currentSpan) => {
+ const { input, user, pgExecution, clickhouseExecution } = args;
+
+ currentSpan?.setAttribute("operation", args.operation);
+
+ if (!user) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Did not find user in function context",
+ });
+ }
+
+ if (input.queryClickhouse && !isClickhouseEligible(user)) {
+ throw new TRPCError({
+ code: "UNAUTHORIZED",
+ message: "Not eligible to query clickhouse",
+ });
+ }
+
+ if (!input.queryClickhouse) {
+ return await pgExecution(input);
+ }
+
+ if (env.LANGFUSE_READ_FROM_POSTGRES_ONLY === "true") {
+ logger.info("Read from postgres only");
+ return await pgExecution(input);
+ }
+
+ logger.info("Read from postgres and clickhouse");
+ const [[pgResult, pgDuration], [chResult, chDuration]] =
+ await Promise.all([
+ executionWrapper(input, pgExecution, currentSpan, "pg"),
+ executionWrapper(input, clickhouseExecution, currentSpan, "ch"),
+ ]);
+
+ const durationDifference = Math.abs(pgDuration - chDuration);
+ currentSpan?.setAttribute(
+ "execution-time-difference",
+ durationDifference,
+ );
+ currentSpan?.setAttribute("pg-duration", pgDuration);
+ currentSpan?.setAttribute("ch-duration", chDuration);
+
+ if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true") {
+ logger.info("Return data from clickhouse");
+ return chResult;
+ }
+ return pgResult;
+ },
+ );
+};
+
+const executionWrapper = async <T, Y>(
+ input: T & { queryClickhouse: boolean },
+ fn: (input: T) => Promise<Y>,
+ span?: opentelemetry.Span,
+ attributePrefix?: string,
+): Promise<[Y, number]> => {
+ const startTime = Date.now();
+ const res = await fn(input);
+ const duration = Date.now() - startTime;
+ span?.setAttribute(`${attributePrefix}-duration`, duration);
+ return [res, duration];
+};