Skip to content

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

perf: query traces via timestamps (#4105)

Max Deichmannedc4cd787301
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index 556cca6a8a..2342e20cca 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -13,3 +13,12 @@ export const clickhouseClient = createClient({
wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
},
});
+
+/**
+ * Accepts a JavaScript date and returns the DateTime in format YYYY-MM-DD HH:MM:SS
+ */
+
+export const convertDateToClickhouseDateTime = (date: Date): string => {
+ // 2024-11-06T20:37:00.000Z -> 2024-11-06 21:37:00
+ return date.toISOString().slice(0, 19).replace("T", " ");
+};
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index f25d9a9fdf..0f9ad33af3 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -12,7 +12,6 @@ import {
import { OrderByState } from "../../interfaces/orderBy";
import { scoresTableUiColumnDefinitions } from "../../tableDefinitions";
import { orderByToClickhouseSql } from "../queries/clickhouse-filter/orderby-factory";
-import { string } from "zod";
export type FetchScoresReturnType = {
id: string;
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 69499c65d7..1f818de8c3 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -12,10 +12,10 @@ import { logger } from "../logger";
import { FilterList } from "../queries/clickhouse-filter/clickhouse-filter";
import { TraceRecordReadType } from "./definitions";
import { tracesTableUiColumnDefinitions } from "../../tableDefinitions/mapTracesTable";
-import { TableCount } from "./types";
import { OrderByState } from "../../interfaces/orderBy";
import { orderByToClickhouseSql } from "../queries/clickhouse-filter/orderby-factory";
import { UiColumnMapping } from "../../tableDefinitions";
+import { convertDateToClickhouseDateTime } from "../clickhouse/client";
const convertClickhouseToDomain = (record: TraceRecordReadType): Trace => {
return {
@@ -209,17 +209,27 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
export const getTraceByIdOrThrow = async (
traceId: string,
projectId: string,
+ timestamp?: Date,
) => {
- 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 query = `SELECT *
+ FROM traces
+ WHERE id = {traceId: String}
+ AND project_id = {projectId: String}
+ ${timestamp ? `AND timestamp >= {timestamp: DateTime}` : ""}
+ ORDER BY event_ts DESC LIMIT 1 by id, project_id`;
const records = await queryClickhouse<TraceRecordReadType>({
query,
- params: { traceId, projectId },
+ params: {
+ traceId,
+ projectId,
+ timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
+ },
});
const res = records.map(convertClickhouseToDomain);
- if (res.length !== 1) {
- const errorMessage = `Trace not found or multiple traces found for traceId: ${traceId}, projectId: ${projectId}`;
+ if (res.length === 0) {
+ const errorMessage = `Trace not found for traceId: ${traceId}, projectId: ${projectId}`;
logger.error(errorMessage);
throw new Error(errorMessage);
}
diff --git a/web/src/components/star-toggle.tsx b/web/src/components/star-toggle.tsx
index eabaa8fc20..476b3758ab 100644
--- a/web/src/components/star-toggle.tsx
+++ b/web/src/components/star-toggle.tsx
@@ -122,11 +122,13 @@ export function StarTraceToggle({
export function StarTraceDetailsToggle({
projectId,
traceId,
+ timestamp,
value,
size = "icon",
}: {
projectId: string;
traceId: string;
+ timestamp?: Date;
value: boolean;
size?: "icon" | "icon-xs";
}) {
@@ -150,6 +152,7 @@ export function StarTraceDetailsToggle({
const prevData = utils.traces.byIdWithObservationsAndScores.getData({
traceId,
projectId,
+ timestamp,
});
return { prevData };
@@ -159,7 +162,7 @@ export function StarTraceDetailsToggle({
trpcErrorToast(err);
// Rollback to the previous value if mutation fails
utils.traces.byIdWithObservationsAndScores.setData(
- { traceId, projectId },
+ { traceId, projectId, timestamp },
context?.prevData,
);
},
@@ -167,7 +170,7 @@ export function StarTraceDetailsToggle({
setIsLoading(false);
utils.traces.byIdWithObservationsAndScores.setData(
- { traceId, projectId },
+ { traceId, projectId, timestamp },
(
oldQueryData:
| RouterOutput["traces"]["byIdWithObservationsAndScores"]
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 112d91c01c..a14fe29c89 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -520,10 +520,13 @@ export default function TracesTable({
size: 400,
cell: ({ row }) => {
const traceId: TracesTableRow["id"] = row.getValue("id");
+ const traceTimestamp: TracesTableRow["timestamp"] =
+ row.getValue("timestamp");
return (
<TracesDynamicCell
traceId={traceId}
projectId={projectId}
+ timestamp={new Date(traceTimestamp)}
col="input"
singleLine={rowHeight === "s"}
/>
@@ -539,10 +542,13 @@ export default function TracesTable({
size: 400,
cell: ({ row }) => {
const traceId: TracesTableRow["id"] = row.getValue("id");
+ const traceTimestamp: TracesTableRow["timestamp"] =
+ row.getValue("timestamp");
return (
<TracesDynamicCell
traceId={traceId}
projectId={projectId}
+ timestamp={new Date(traceTimestamp)}
col="output"
singleLine={rowHeight === "s"}
/>
@@ -561,10 +567,13 @@ export default function TracesTable({
},
cell: ({ row }) => {
const traceId: TracesTableRow["id"] = row.getValue("id");
+ const traceTimestamp: TracesTableRow["timestamp"] =
+ row.getValue("timestamp");
return (
<TracesDynamicCell
traceId={traceId}
projectId={projectId}
+ timestamp={new Date(traceTimestamp)}
col="metadata"
singleLine={rowHeight === "s"}
/>
@@ -817,16 +826,18 @@ export default function TracesTable({
const TracesDynamicCell = ({
traceId,
projectId,
+ timestamp,
col,
singleLine = false,
}: {
traceId: string;
projectId: string;
+ timestamp: Date;
col: "input" | "output" | "metadata";
singleLine?: boolean;
}) => {
const trace = api.traces.byId.useQuery(
- { traceId, projectId, queryClickhouse: useClickhouse() },
+ { traceId, projectId, queryClickhouse: useClickhouse(), timestamp },
{
enabled: typeof traceId === "string",
trpc: {
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index d05f270799..3a70f4e96a 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -457,6 +457,7 @@ export const traceRouter = createTRPCRouter({
z.object({
traceId: z.string(), // used for security check
projectId: z.string(), // used for security check
+ timestamp: z.date().nullish(), // timestamp of the trace. Used to query CH more efficiently
queryClickhouse: z.boolean().default(false),
}),
)
@@ -476,13 +477,18 @@ export const traceRouter = createTRPCRouter({
});
}
- return await getTraceByIdOrThrow(input.traceId, input.projectId);
+ return await getTraceByIdOrThrow(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ );
}
}),
byIdWithObservationsAndScores: protectedGetTraceProcedure
.input(
z.object({
traceId: z.string(), // used for security check
+ timestamp: z.date().nullish(), // timestamp of the trace. Used to query CH more efficiently
projectId: z.string(), // used for security check
queryClickhouse: z.boolean().default(false),
}),
@@ -581,7 +587,11 @@ export const traceRouter = createTRPCRouter({
}
const [trace, observations, scores] = await Promise.all([
- getTraceByIdOrThrow(input.traceId, input.projectId),
+ getTraceByIdOrThrow(
+ input.traceId,
+ input.projectId,
+ input.timestamp ?? undefined,
+ ),
getObservationsViewForTrace(input.traceId, input.projectId),
getScoresForTraces(
input.projectId,
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index d023548586..3169e9c8e9 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -318,6 +318,7 @@ export const protectedOrganizationProcedure = withOtelTracingProcedure
const inputTraceSchema = z.object({
traceId: z.string(),
projectId: z.string(),
+ timestamp: z.date().nullish(),
queryClickhouse: z.boolean().nullish(),
});
@@ -328,12 +329,13 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
logger.error("Invalid input when parsing request body", result.error);
throw new TRPCError({
code: "BAD_REQUEST",
- message: "Invalid input, traceId is required",
+ message: `Invalid input, ${result.error.message}`,
});
}
const traceId = result.data.traceId;
const projectId = result.data.projectId;
+ const timestamp = result.data.timestamp;
// if the user is eligible for clickhouse, and wants to use clickhouse, do so.
let trace;
@@ -345,7 +347,11 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
logger.info(
`Querying Clickhouse for traceid: ${traceId} and project: ${projectId} `,
);
- trace = await getTraceByIdOrThrow(traceId, projectId);
+ trace = await getTraceByIdOrThrow(
+ traceId,
+ projectId,
+ timestamp ?? undefined,
+ );
} else {
trace = await prisma.trace.findFirst({
where: {
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 4729a3806b..b7a69cacad 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -33,6 +33,7 @@ import {
traceRecordReadSchema,
validateAndInflateScore,
UsageCostType,
+ convertDateToClickhouseDateTime,
} from "@langfuse/shared/src/server";
import { tokenCount } from "../../features/tokenisation/usage";
@@ -130,9 +131,7 @@ export class IngestionService {
const timestamp =
minTimestamp === Infinity
? undefined
- : IngestionService.convertDateToClickhouseDateTime(
- new Date(minTimestamp),
- );
+ : convertDateToClickhouseDateTime(new Date(minTimestamp));
const [postgresScoreRecord, clickhouseScoreRecord, scoreRecords] =
await Promise.all([
this.getPostgresRecord({
@@ -215,9 +214,7 @@ export class IngestionService {
const timestamp =
minTimestamp === Infinity
? undefined
- : IngestionService.convertDateToClickhouseDateTime(
- new Date(minTimestamp),
- );
+ : convertDateToClickhouseDateTime(new Date(minTimestamp));
const [postgresTraceRecord, clickhouseTraceRecord] = await Promise.all([
this.getPostgresRecord({
projectId,
@@ -266,9 +263,7 @@ export class IngestionService {
const startTime =
minStartTime === Infinity
? undefined
- : IngestionService.convertDateToClickhouseDateTime(
- new Date(minStartTime),
- );
+ : convertDateToClickhouseDateTime(new Date(minStartTime));
const [postgresObservationRecord, clickhouseObservationRecord, prompt] =
await Promise.all([
this.getPostgresRecord({
@@ -954,13 +949,6 @@ export class IngestionService {
});
}
- /**
- * Accepts a JavaScript date and returns the DateTime in format YYYY-MM-DD HH:MM:SS
- */
- private static convertDateToClickhouseDateTime = (date: Date): string => {
- return date.toISOString().slice(0, 19).replace("T", " ");
- };
-
private stringify(
obj: string | object | number | boolean | undefined | null,
): string | undefined {
diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
index bde847833b..c5269162b2 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
@@ -1,5 +1,6 @@
import { expect, describe, it, vi } from "vitest";
import { IngestionService } from "../../IngestionService";
+import { convertDateToClickhouseDateTime } from "@langfuse/shared/src/server";
describe("IngestionService unit tests", () => {
it("correctly sorts events in ascending order by timestamp", async () => {
@@ -20,9 +21,7 @@ describe("IngestionService unit tests", () => {
it("correctly convert Date to Clickhouse DateTime", async () => {
const date = new Date("2024-10-12T12:13:14.000Z");
- const clickhouseDateTime = (
- IngestionService as any
- ).convertDateToClickhouseDateTime(date);
+ const clickhouseDateTime = convertDateToClickhouseDateTime(date);
expect(clickhouseDateTime).toEqual("2024-10-12 12:13:14");
});