Skip to content

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

feat: move trace not found to 404 (#4270)

Max Deichmann723098994b40
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index a4413c8e8a..a4fbefa634 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -276,18 +276,6 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
});
};
-export const getTraceById = async (
- traceId: string,
- projectId: string,
- timestamp?: Date,
-): Promise<Trace | undefined> => {
- try {
- return getTraceByIdOrThrow(traceId, projectId, timestamp);
- } catch (e) {
- return undefined;
- }
-};
-
export const getTracesByIds = async (
traceIds: string[],
projectId: string,
@@ -356,7 +344,7 @@ export const hasAnyTrace = async (projectId: string) => {
return rows.length > 0 && Number(rows[0].count) > 0;
};
-export const getTraceByIdOrThrow = async (
+export const getTraceById = async (
traceId: string,
projectId: string,
timestamp?: Date,
@@ -384,12 +372,7 @@ export const getTraceByIdOrThrow = async (
const res = records.map(convertClickhouseToDomain);
- if (res.length === 0) {
- const errorMessage = `Trace not found for traceId: ${traceId}, projectId: ${projectId}, and timestamp: ${timestamp}`;
- logger.error(errorMessage);
- throw new Error(errorMessage);
- }
- return res[0] as Trace;
+ return res.shift();
};
export const getTracesGroupedByName = async (
diff --git a/web/src/__tests__/server/repositories/trace-repository.servertest.ts b/web/src/__tests__/server/repositories/trace-repository.servertest.ts
index c38ebfe168..5c43974c0b 100644
--- a/web/src/__tests__/server/repositories/trace-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/trace-repository.servertest.ts
@@ -1,7 +1,7 @@
import { createTraces } from "@/src/__tests__/server/repositories/clickhouse-helpers";
import { pruneDatabase } from "@/src/__tests__/test-utils";
import {
- getTraceByIdOrThrow,
+ getTraceById,
getTracesBySessionId,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
@@ -14,7 +14,7 @@ describe("Clickhouse Traces Repository Test", () => {
});
it("should throw if no traces are found", async () => {
- await expect(getTraceByIdOrThrow(v4(), v4())).rejects.toThrow();
+ expect(await getTraceById(v4(), v4())).toBeUndefined();
});
it("should return a trace if it exists", async () => {
@@ -41,11 +41,15 @@ describe("Clickhouse Traces Repository Test", () => {
await createTraces([trace]);
- const result = await getTraceByIdOrThrow(
+ const result = await getTraceById(
traceId,
projectId,
new Date(trace.timestamp),
);
+ expect(result).not.toBeNull();
+ if (!result) {
+ return;
+ }
expect(result.id).toEqual(trace.id);
expect(result.projectId).toEqual(trace.project_id);
expect(result.name).toEqual(trace.name);
@@ -88,7 +92,11 @@ describe("Clickhouse Traces Repository Test", () => {
await createTraces([trace]);
- const result = await getTraceByIdOrThrow(traceId, projectId);
+ const result = await getTraceById(traceId, projectId);
+ expect(result).not.toBeNull();
+ if (!result) {
+ return;
+ }
expect(result.id).toEqual(trace.id);
expect(result.projectId).toEqual(trace.project_id);
expect(result.name).toEqual(trace.name);
@@ -106,7 +114,6 @@ describe("Clickhouse Traces Repository Test", () => {
expect(result.createdAt).toEqual(new Date(trace.created_at));
expect(result.updatedAt).toEqual(new Date(trace.updated_at));
});
-
it("should retrieve traces by session ID", async () => {
const sessionId = v4();
const trace1 = {
diff --git a/web/src/pages/api/trpc/[trpc].ts b/web/src/pages/api/trpc/[trpc].ts
index a824c3f6e2..fd3d9e88a2 100644
--- a/web/src/pages/api/trpc/[trpc].ts
+++ b/web/src/pages/api/trpc/[trpc].ts
@@ -14,10 +14,11 @@ export default createNextApiHandler({
createContext: createTRPCContext,
onError: ({ path, error }) => {
logger.error(
- `❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`,
+ `tRPC route failed on ${path ?? "<no-path>"}: ${error.message}`,
error,
);
traceException(error);
+ return error;
},
responseMeta() {
return {
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index a60d8e7518..0eadf9edf9 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -31,7 +31,6 @@ import {
getTracesTable,
getTracesTableCount,
getScoresForTraces,
- getTraceByIdOrThrow,
getScoresGroupedByName,
getTracesGroupedByName,
getTracesGroupedByTags,
@@ -451,11 +450,18 @@ export const traceRouter = createTRPCRouter({
});
},
clickhouseExecution: async () => {
- return getTraceByIdOrThrow(
+ const trace = getTraceById(
input.traceId,
input.projectId,
input.timestamp ?? undefined,
);
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+ }
+ return trace;
},
});
}),
@@ -475,7 +481,7 @@ export const traceRouter = createTRPCRouter({
user: ctx.session.user ?? undefined,
pgExecution: async () => {
const [trace, observations, scores] = await Promise.all([
- ctx.prisma.trace.findFirstOrThrow({
+ ctx.prisma.trace.findFirst({
where: {
id: input.traceId,
projectId: input.projectId,
@@ -531,6 +537,14 @@ export const traceRouter = createTRPCRouter({
},
}),
]);
+
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+ }
+
const validatedScores = filterAndValidateDbScoreList(
scores,
traceException,
@@ -563,7 +577,7 @@ export const traceRouter = createTRPCRouter({
},
clickhouseExecution: async () => {
const [trace, observations, scores] = await Promise.all([
- getTraceByIdOrThrow(
+ getTraceById(
input.traceId,
input.projectId,
input.timestamp ?? undefined,
@@ -582,6 +596,13 @@ export const traceRouter = createTRPCRouter({
),
]);
+ if (!trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found",
+ });
+ }
+
const validatedScores = filterAndValidateDbScoreList(
scores,
traceException,
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 2fd5580414..b855690465 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -80,7 +80,7 @@ import { setUpSuperjson } from "@/src/utils/superjson";
import { DB } from "@/src/server/db";
import {
addUserToSpan,
- getTraceByIdOrThrow,
+ getTraceById,
logger,
} from "@langfuse/shared/src/server";
import { isClickhouseAdminEligible } from "@/src/server/utils/checkClickhouseAccess";
@@ -121,13 +121,17 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {
const res = await next({ ctx }); // pass the context to the next middleware
if (!res.ok) {
- logger.error("middleware intercepted error", res.error);
+ logger.error(
+ `middleware intercepted error with code ${res.error.code}`,
+ res.error,
+ );
// Throw a new TRPC error with:
// - The same error code as the original error
// - Either the original error message OR "Internal error" if it's an INTERNAL_SERVER_ERROR
- throw new TRPCError({
+ res.error = new TRPCError({
code: res.error.code,
+ cause: null, // do not expose stack traces
message:
res.error.code !== "INTERNAL_SERVER_ERROR"
? res.error.message
@@ -349,11 +353,7 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
result.data.queryClickhouse === true &&
isClickhouseAdminEligible(ctx.session?.user) // basically checks if user exists and admin
) {
- trace = await getTraceByIdOrThrow(
- traceId,
- projectId,
- timestamp ?? undefined,
- );
+ trace = await getTraceById(traceId, projectId, timestamp ?? undefined);
// check from postgres for non admins when env is set accordingly
} else if (env.LANGFUSE_READ_FROM_POSTGRES_ONLY === "true") {
trace = await prisma.trace.findFirst({
@@ -367,11 +367,7 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
});
// check clickhouse otherwise
} else {
- trace = await getTraceByIdOrThrow(
- traceId,
- projectId,
- timestamp ?? undefined,
- );
+ trace = await getTraceById(traceId, projectId, timestamp ?? undefined);
}
if (!trace) {