Skip to content

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

fix: improve error message for CH memory issues on public API (#9191)

Valery Meleshkinf4caacabdb18
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index f58393c0a3..dff34e0897 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -16,6 +16,70 @@ import {
StorageServiceFactory,
} from "../services/StorageService";
+/**
+ * Custom error class for ClickHouse resource-related errors
+ */
+// Error type configuration map
+const ERROR_TYPE_CONFIG: Record<
+ "MEMORY_LIMIT" | "OVERCOMMIT" | "TIMEOUT",
+ {
+ discriminators: string[];
+ }
+> = {
+ MEMORY_LIMIT: {
+ discriminators: ["memory limit exceeded"],
+ },
+ OVERCOMMIT: {
+ discriminators: ["OvercommitTracker"],
+ },
+ TIMEOUT: {
+ discriminators: ["Timeout", "timeout", "timed out"],
+ },
+};
+
+type ErrorType = keyof typeof ERROR_TYPE_CONFIG;
+
+export class ClickHouseResourceError extends Error {
+ static ERROR_ADVICE_MESSAGE = [
+ "Database resource limit exceeded.",
+ "Please use more specific filters or a shorter time range.",
+ "We are continuously improving our API performance.",
+ ].join(" ");
+
+ public readonly errorType: ErrorType;
+
+ constructor(errType: ErrorType, originalError: Error) {
+ super(originalError.message, { cause: originalError });
+ this.name = "ClickHouseResourceError";
+ this.errorType = errType;
+ // Preserve the original stack trace if available
+ if (originalError.stack) {
+ this.stack = originalError.stack;
+ }
+ }
+
+ static wrapIfResourceError(originalError: Error): Error {
+ const errorMessage = originalError.message || "";
+
+ for (const [type, config] of Object.entries(ERROR_TYPE_CONFIG) as Array<
+ [
+ keyof typeof ERROR_TYPE_CONFIG,
+ (typeof ERROR_TYPE_CONFIG)[keyof typeof ERROR_TYPE_CONFIG],
+ ]
+ >) {
+ const hasDiscriminator = config.discriminators.some((discriminator) =>
+ errorMessage.includes(discriminator),
+ );
+
+ if (hasDiscriminator) {
+ return new ClickHouseResourceError(type, originalError);
+ }
+ }
+
+ return originalError;
+ }
+}
+
let s3StorageServiceClient: StorageService;
const getS3StorageServiceClient = (bucketName: string): StorageService => {
@@ -153,9 +217,8 @@ export async function* queryClickhouseStream<T>(opts: {
});
try {
- const res = await context.with(
- trace.setSpan(context.active(), span),
- async () => {
+ const res = await context
+ .with(trace.setSpan(context.active(), span), async () => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
span.setAttribute("db.system", "clickhouse");
@@ -198,14 +261,20 @@ export async function* queryClickhouseStream<T>(opts: {
}
}
return res;
- },
- );
+ })
+ .catch((error) => {
+ // Transform resource errors to provide actionable advice
+ throw ClickHouseResourceError.wrapIfResourceError(error as Error);
+ });
for await (const rows of res.stream<T>()) {
for (const row of rows) {
yield row.json();
}
}
+ } catch (error) {
+ // Also catch errors during streaming
+ throw ClickHouseResourceError.wrapIfResourceError(error as Error);
} finally {
span.end();
}
@@ -313,7 +382,10 @@ export async function queryClickhouse<T>(opts: {
timeMultiple: 1,
maxDelay: 100,
},
- );
+ ).catch((error) => {
+ // Transform resource errors to provide actionable advice
+ throw ClickHouseResourceError.wrapIfResourceError(error as Error);
+ });
},
);
}
diff --git a/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts b/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts
new file mode 100644
index 0000000000..2be29d8515
--- /dev/null
+++ b/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts
@@ -0,0 +1,187 @@
+import {
+ queryClickhouse,
+ queryClickhouseStream,
+ ClickHouseResourceError,
+} from "@langfuse/shared/src/server";
+import { fail } from "assert";
+
+describe("ClickHouse Resource Error Handling", () => {
+ describe("queryClickhouse", () => {
+ describe("Error transformation with throwIf", () => {
+ it("should transform OOM errors to ClickHouseResourceError", async () => {
+ try {
+ await queryClickhouse({
+ query: `SELECT throwIf(true, 'memory limit exceeded: would use 10.08 GiB, maximum: 8.40 GiB')`,
+ params: {},
+ });
+ fail("Should have thrown an error");
+ } catch (error: any) {
+ expect(error).toBeInstanceOf(ClickHouseResourceError);
+ expect(error.errorType).toBe("MEMORY_LIMIT");
+ }
+ });
+
+ it("should transform OvercommitTracker errors", async () => {
+ try {
+ await queryClickhouse({
+ query: `SELECT throwIf(true, 'OvercommitTracker decision: Query was selected to stop by OvercommitTracker')`,
+ params: {},
+ });
+ fail("Should have thrown an error");
+ } catch (error: any) {
+ expect(error).toBeInstanceOf(ClickHouseResourceError);
+ expect(error.errorType).toBe("OVERCOMMIT");
+ }
+ });
+
+ it("should transform timeout errors", async () => {
+ try {
+ await queryClickhouse({
+ query: `SELECT throwIf(true, 'Timeout exceeded while reading from socket')`,
+ params: {},
+ });
+ fail("Should have thrown an error");
+ } catch (error: any) {
+ expect(error).toBeInstanceOf(ClickHouseResourceError);
+ expect(error.errorType).toBe("TIMEOUT");
+ }
+ });
+
+ it("should NOT transform regular SQL errors", async () => {
+ await expect(
+ queryClickhouse({
+ query: `SELECT * FROM non_existent_table_xyz123`,
+ params: {},
+ }),
+ ).rejects.toThrow();
+
+ try {
+ await queryClickhouse({
+ query: `SELECT * FROM non_existent_table_xyz123`,
+ params: {},
+ });
+ } catch (error: any) {
+ expect(error).not.toBeInstanceOf(ClickHouseResourceError);
+ }
+ });
+
+ it("should pass through successful queries", async () => {
+ const result = await queryClickhouse<{ test_value: Number }>({
+ query: "SELECT 1 as test_value",
+ params: {},
+ });
+
+ expect(result).toBeDefined();
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+ expect(result[0]).toHaveProperty("test_value");
+ expect(result[0].test_value).toBe(1);
+ });
+ });
+ });
+
+ describe("queryClickhouseStream", () => {
+ describe("Error transformation with throwIf", () => {
+ it("should transform errors during streaming", async () => {
+ const generator = queryClickhouseStream({
+ query: `SELECT throwIf(number > 3, 'memory limit exceeded: would use 10.23 GiB') FROM numbers(10)`,
+ params: {},
+ });
+
+ await expect(
+ (async () => {
+ for await (const item of generator) {
+ fail("Should have thrown an error, observed instead " + item);
+ // Should not reach here
+ }
+ })(),
+ ).rejects.toThrow(ClickHouseResourceError);
+ });
+
+ it("should stream successful queries", async () => {
+ const generator = queryClickhouseStream({
+ query: "SELECT number FROM system.numbers LIMIT 3",
+ params: {},
+ });
+
+ const results = [];
+ for await (const item of generator) {
+ results.push(item);
+ }
+
+ expect(results).toBeDefined();
+ expect(Array.isArray(results)).toBe(true);
+ expect(results.length).toBe(3);
+ expect(results[0]).toHaveProperty("number");
+ });
+ });
+ });
+
+ describe("Error patterns documentation", () => {
+ // Document the actual error patterns we handle
+ const errorPatterns = [
+ {
+ name: "Memory limit exceeded with details",
+ errorMessage:
+ "(total) memory limit exceeded: would use 10.08 GiB (attempt to allocate chunk of 4.49 MiB bytes), current RSS: 1.83 GiB, maximum: 8.40 GiB",
+ shouldBeResourceError: true,
+ errorType: "MEMORY_LIMIT",
+ },
+ {
+ name: "OvercommitTracker error",
+ errorMessage:
+ "OvercommitTracker decision: Query was selected to stop by OvercommitTracker: While executing WaitForAsyncInsert",
+ shouldBeResourceError: true,
+ errorType: "OVERCOMMIT",
+ },
+ {
+ name: "Simple memory error",
+ errorMessage: "memory limit exceeded",
+ shouldBeResourceError: true,
+ errorType: "MEMORY_LIMIT",
+ },
+ {
+ name: "Timeout error",
+ errorMessage: "Timeout exceeded while reading from socket",
+ shouldBeResourceError: true,
+ errorType: "TIMEOUT",
+ },
+ {
+ name: "SQL error (not a resource error)",
+ errorMessage: "Table 'test.non_existent' doesn't exist",
+ shouldBeResourceError: false,
+ errorType: null,
+ },
+ {
+ name: "Network error (retryable but not a resource error)",
+ errorMessage: "socket hang up",
+ shouldBeResourceError: false,
+ errorType: null,
+ },
+ ];
+
+ errorPatterns.forEach(
+ ({ name, errorMessage, shouldBeResourceError, errorType }) => {
+ it(`should correctly classify "${name}"`, () => {
+ const error = new Error(errorMessage);
+ const wrappedError =
+ ClickHouseResourceError.wrapIfResourceError(error);
+ const isResourceError = ((err: Error) => {
+ if (err instanceof ClickHouseResourceError) {
+ return true;
+ } else {
+ return false;
+ }
+ })(wrappedError);
+
+ expect(isResourceError).toBe(shouldBeResourceError);
+
+ const resourceError = wrappedError as ClickHouseResourceError;
+ if (shouldBeResourceError && errorType) {
+ expect(resourceError.errorType).toBe(errorType);
+ }
+ });
+ },
+ );
+ });
+});
diff --git a/web/src/__tests__/withMiddlewares.servertest.ts b/web/src/__tests__/withMiddlewares.servertest.ts
new file mode 100644
index 0000000000..f101b6ca15
--- /dev/null
+++ b/web/src/__tests__/withMiddlewares.servertest.ts
@@ -0,0 +1,362 @@
+/** @jest-environment node */
+import type { NextApiRequest, NextApiResponse } from "next";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ BaseError,
+ LangfuseNotFoundError,
+ UnauthorizedError,
+} from "@langfuse/shared";
+import {
+ ClickHouseResourceError,
+ logger,
+ traceException,
+} from "@langfuse/shared/src/server";
+import { createMocks } from "node-mocks-http";
+import { z } from "zod/v4";
+import { Prisma } from "@prisma/client";
+
+// Mock the logger and traceException
+jest.mock("@langfuse/shared/src/server", () => ({
+ ...jest.requireActual("@langfuse/shared/src/server"),
+ logger: {
+ info: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ },
+ traceException: jest.fn(),
+}));
+
+describe("withMiddlewares error handling", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe("BaseError handling", () => {
+ it("should handle BaseError with 4xx status code", async () => {
+ const error = new BaseError("BadRequest", 400, "Bad Request", false);
+
+ const handler = withMiddlewares({
+ POST: async () => {
+ throw error;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Bad Request",
+ error: "BadRequest",
+ });
+ });
+
+ it("should handle BaseError with 5xx status code and trace exception", async () => {
+ const error = new BaseError(
+ "ServiceUnavailable",
+ 503,
+ "Internal Error",
+ true,
+ );
+
+ const handler = withMiddlewares({
+ GET: async () => {
+ throw error;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(503);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Internal Error",
+ error: "ServiceUnavailable",
+ });
+ // Should trace 5xx errors
+ expect(traceException).toHaveBeenCalledWith(error);
+ });
+ });
+
+ describe("LangfuseNotFoundError handling", () => {
+ it("should handle LangfuseNotFoundError and log as info", async () => {
+ const error = new LangfuseNotFoundError("Resource not found");
+
+ const handler = withMiddlewares({
+ GET: async () => {
+ throw error;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(404);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Resource not found",
+ error: "LangfuseNotFoundError",
+ });
+ // Should log as info, not error
+ expect(logger.info).toHaveBeenCalledWith(error);
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("UnauthorizedError handling", () => {
+ it("should handle UnauthorizedError and log as info", async () => {
+ const error = new UnauthorizedError("Invalid credentials");
+
+ const handler = withMiddlewares({
+ POST: async () => {
+ throw error;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(401);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Invalid credentials",
+ error: "UnauthorizedError",
+ });
+ // Should log as info, not error
+ expect(logger.info).toHaveBeenCalledWith(error);
+ expect(logger.error).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("MethodNotAllowedError handling", () => {
+ it("should throw MethodNotAllowedError for unsupported methods", async () => {
+ const handler = withMiddlewares({
+ GET: async () => {},
+ // POST is not defined
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(405);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Method not allowed",
+ error: "MethodNotAllowedError",
+ });
+ });
+ });
+
+ describe("ClickHouseResourceError handling", () => {
+ it("should handle ClickHouseResourceError with 400 status", async () => {
+ const originalError = new Error("Memory limit exceeded: maximum: 10GB");
+ const resourceError = new ClickHouseResourceError(
+ "MEMORY_LIMIT",
+ originalError,
+ );
+
+ const handler = withMiddlewares({
+ POST: async () => {
+ throw resourceError;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(524);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData["message"]).toBeDefined();
+ expect(jsonData["message"]).toContain(
+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
+ );
+ });
+ });
+
+ describe("Prisma exception handling", () => {
+ it("should handle Prisma exceptions with generic 500 error", async () => {
+ // Create a real Prisma error
+ const prismaError = new Prisma.PrismaClientKnownRequestError(
+ "Unique constraint failed",
+ { code: "P2002", clientVersion: "5.0.0" },
+ );
+
+ const handler = withMiddlewares({
+ POST: async () => {
+ throw prismaError;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(500);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Internal Server Error",
+ error: "An unknown error occurred",
+ });
+
+ expect(traceException).toHaveBeenCalledWith(prismaError);
+ });
+ });
+
+ describe("Zod validation error handling", () => {
+ it("should handle Zod validation errors with 400 status", async () => {
+ const schema = z.object({
+ name: z.string(),
+ age: z.number(),
+ });
+
+ const handler = withMiddlewares({
+ POST: async () => {
+ // This will throw a ZodError
+ schema.parse({ name: "John", age: "not a number" });
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Invalid request data",
+ error: expect.arrayContaining([
+ expect.objectContaining({
+ code: "invalid_type",
+ path: ["age"],
+ }),
+ ]),
+ });
+ });
+ });
+
+ describe("Generic error handling", () => {
+ it("should handle generic Error instances with 500 status", async () => {
+ const error = new Error("Something went wrong");
+
+ const handler = withMiddlewares({
+ DELETE: async () => {
+ throw error;
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "DELETE",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(500);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Internal Server Error",
+ error: "Something went wrong",
+ });
+
+ expect(traceException).toHaveBeenCalledWith(error);
+ });
+
+ it("should handle non-Error thrown values with 500 status", async () => {
+ const handler = withMiddlewares({
+ PATCH: async () => {
+ throw "string error"; // eslint-disable-line no-throw-literal
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "PATCH",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(500);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Internal Server Error",
+ error: "An unknown error occurred",
+ });
+ });
+
+ it("should handle null/undefined errors with 500 status", async () => {
+ const handler = withMiddlewares({
+ PUT: async () => {
+ throw null; // eslint-disable-line no-throw-literal
+ },
+ });
+
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "PUT",
+ headers: {
+ "x-langfuse-public-key": "test-key",
+ },
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(500);
+ const jsonData = JSON.parse(res._getData());
+ expect(jsonData).toMatchObject({
+ message: "Internal Server Error",
+ error: "An unknown error occurred",
+ });
+ });
+ });
+});
diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.ts
index 7fba60208f..169f061d6b 100644
--- a/web/src/features/public-api/server/withMiddlewares.ts
+++ b/web/src/features/public-api/server/withMiddlewares.ts
@@ -12,6 +12,7 @@ import {
logger,
traceException,
contextWithLangfuseProps,
+ ClickHouseResourceError,
} from "@langfuse/shared/src/server";
import * as opentelemetry from "@opentelemetry/api";
@@ -28,6 +29,11 @@ const defaultHandler = () => {
throw new MethodNotAllowedError();
};
+const CH_ERROR_ADVICE_FULL = [
+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
+ "See https://langfuse.com/docs/api-and-data-platform/features/public-api for more details.",
+].join("\n");
+
export function withMiddlewares(handlers: Handlers) {
return async (req: NextApiRequest, res: NextApiResponse) => {
const ctx = contextWithLangfuseProps({
@@ -73,6 +79,22 @@ export function withMiddlewares(handlers: Handlers) {
});
}
+ // Handle ClickHouse resource errors
+ if (error instanceof ClickHouseResourceError) {
+ const resourceError = error as ClickHouseResourceError;
+
+ logger.error("ClickHouse resource limit exceeded", {
+ errorType: resourceError.errorType,
+ message: resourceError.message,
+ suggestion: CH_ERROR_ADVICE_FULL,
+ });
+
+ return res.status(524).json({
+ message: CH_ERROR_ADVICE_FULL,
+ error: "Request is taking too long to process.",
+ });
+ }
+
if (isPrismaException(error)) {
traceException(error);
return res.status(500).json({
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 95ca76d2bf..30b82ecc64 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -87,6 +87,7 @@ import {
logger,
addUserToSpan,
contextWithLangfuseProps,
+ ClickHouseResourceError,
} from "@langfuse/shared/src/server";
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
@@ -138,17 +139,26 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {
);
}
- // 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
- 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
- : "Internal error",
- });
+ if (res.error.cause instanceof ClickHouseResourceError) {
+ // Surface ClickHouse errors using an advice message
+ // which is supposed to provide a bit of guidance to the user.
+ res.error = new TRPCError({
+ code: "TIMEOUT",
+ message: ClickHouseResourceError.ERROR_ADVICE_MESSAGE,
+ });
+ } else {
+ // 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
+ 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
+ : "Internal error",
+ });
+ }
}
return res;