🪢 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
fix: ensure cases when CH outputs an error as a row are handled (#9238)
Valery Meleshkin312d97f509cd
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex dff34e0897..178d809046 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -15,6 +15,7 @@ import {StorageService,StorageServiceFactory,} from "../services/StorageService";+import { ClickHouseSettings } from "@clickhouse/client";/*** Custom error class for ClickHouse resource-related errors@@ -210,6 +211,7 @@ export async function* queryClickhouseStream<T>(opts: {clickhouseConfigs?: NodeClickHouseClientConfigOptions;tags?: Record<string, string>;preferredClickhouseService?: PreferredClickhouseService;+ clickhouseSettings?: ClickHouseSettings;}): AsyncGenerator<T> {const tracer = getTracer("clickhouse-query-stream");const span = tracer.startSpan("clickhouse-query-stream", {@@ -233,6 +235,7 @@ export async function* queryClickhouseStream<T>(opts: {format: "JSONEachRow",query_params: opts.params,clickhouse_settings: {+ ...opts.clickhouseSettings,log_comment: JSON.stringify(opts.tags ?? {}),},});@@ -269,7 +272,7 @@ export async function* queryClickhouseStream<T>(opts: {for await (const rows of res.stream<T>()) {for (const row of rows) {- yield row.json();+ yield handleExceptionRow(row.json());}}} catch (error) {@@ -280,6 +283,39 @@ export async function* queryClickhouseStream<T>(opts: {}}+/**+ * ClickHouse has a quirk when it comes to handling exceptions mid response.+ * It will simply output a row with "exception" key inside, which is indistinguishable from+ * a query like `SELECT "my lovely string" AS exception;` may return.+ *+ * E.g.:+ * ```+ * {"exception":"Code: 395. DB::Exception: memory limit exceeded: would use l0.23 GiB"}+ * ```+ *+ * This function makes the best effort to convert such rows into errors and throws them.+ *+ * See:+ * - https://github.com/ClickHouse/clickhouse-js/issues/332+ * - https://github.com/ClickHouse/ClickHouse/issues/75175+ *+ * Ideally this should get fixed in the future versions of ClickHouse.+ */+function handleExceptionRow<T>(parsedRow: T): T {+ if (+ typeof parsedRow === "object" &&+ parsedRow !== null &&+ Object.keys(parsedRow).length === 1 &&+ "exception" in parsedRow+ ) {+ const potentialException = (parsedRow as { exception: string }).exception;+ if (potentialException.match(/^Code: (\d+)/)) {+ throw new Error(potentialException);+ }+ }+ return parsedRow;+}+/*** Determines if an error is retryable (socket hang up, connection reset, etc.)*/@@ -298,6 +334,7 @@ export async function queryClickhouse<T>(opts: {clickhouseConfigs?: NodeClickHouseClientConfigOptions;tags?: Record<string, string>;preferredClickhouseService?: PreferredClickhouseService;+ clickhouseSettings?: ClickHouseSettings;}): Promise<T[]> {return await instrumentAsync({ name: "clickhouse-query", spanKind: SpanKind.CLIENT },@@ -319,6 +356,7 @@ export async function queryClickhouse<T>(opts: {format: "JSONEachRow",query_params: opts.params,clickhouse_settings: {+ ...opts.clickhouseSettings,log_comment: JSON.stringify(opts.tags ?? {}),},});@@ -348,7 +386,7 @@ export async function queryClickhouse<T>(opts: {}}- return await res.json<T>();+ return (await res.json<T>()).map(handleExceptionRow);},{numOfAttempts: env.LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS,diff --git a/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts b/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.tsindex 2be29d8515..565eb91498 100644--- a/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts+++ b/web/src/__tests__/async/repositories/clickhouse-resource-errors.servertest.ts@@ -8,24 +8,30 @@ 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 is enough to test different block sizes on one error type only+ [1, 10_000].forEach((blockSize) => {+ it(`should transform OOM errors to ClickHouseResourceError; block size: ${blockSize}`, async () => {+ let res = Array<any>();+ try {+ res = await queryClickhouse<any>({+ query: `SELECT throwIf(number >= 2, 'memory limit exceeded: would use 10.23 GiB') AS v FROM system.numbers LIMIT 2000`,+ clickhouseSettings: { max_block_size: `${blockSize}` },+ });+ fail(+ "Should have thrown an error, observed instead " ++ JSON.stringify(res),+ );+ } 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) {@@ -38,7 +44,6 @@ describe("ClickHouse Resource Error Handling", () => {try {await queryClickhouse({query: `SELECT throwIf(true, 'Timeout exceeded while reading from socket')`,- params: {},});fail("Should have thrown an error");} catch (error: any) {@@ -51,14 +56,12 @@ describe("ClickHouse Resource Error Handling", () => {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);@@ -68,7 +71,6 @@ describe("ClickHouse Resource Error Handling", () => {it("should pass through successful queries", async () => {const result = await queryClickhouse<{ test_value: Number }>({query: "SELECT 1 as test_value",- params: {},});expect(result).toBeDefined();@@ -81,19 +83,25 @@ describe("ClickHouse Resource Error Handling", () => {});describe("queryClickhouseStream", () => {- describe("Error transformation with throwIf", () => {- it("should transform errors during streaming", async () => {+ // We don't need to test all error types here, just one is enough+ // to verify streaming works with throwIf and different block sizes.+ [1, 10_000].forEach((blockSize) => {+ it(`should transform errors during streaming; block size ${blockSize}`, async () => {const generator = queryClickhouseStream({- query: `SELECT throwIf(number > 3, 'memory limit exceeded: would use 10.23 GiB') FROM numbers(10)`,- params: {},+ query: `SELECT throwIf(number = 2, 'memory limit exceeded: would use 10.23 GiB') as V FROM numbers(10)`,+ clickhouseSettings: { max_block_size: `${blockSize}` },});+ let fullResponse = [];await expect((async () => {for await (const item of generator) {- fail("Should have thrown an error, observed instead " + item);- // Should not reach here+ fullResponse.push(item);}+ fail(+ "Should have thrown an error, observed instead " ++ JSON.stringify(fullResponse),+ );})(),).rejects.toThrow(ClickHouseResourceError);});@@ -101,7 +109,6 @@ describe("ClickHouse Resource Error Handling", () => {it("should stream successful queries", async () => {const generator = queryClickhouseStream({query: "SELECT number FROM system.numbers LIMIT 3",- params: {},});const results = [];