Skip to content

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

13.0 KB
Raw Blame
import {
  queryClickhouse,
  queryClickhouseStream,
  queryClickhouseStreamRawText,
  queryClickhouseExecRaw,
  queryClickhouseWithProgress,
  ClickHouseResourceError,
  ClickHouseQueryAbortedError,
  isRow,
  isProgressRow,
} from "@langfuse/shared/src/server";
import { fail } from "assert";
import { randomUUID } from "node:crypto";

const QUERY_ID_PATTERN =
  /\[query_id: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]/;

describe("ClickHouse Resource Error Handling", () => {
  describe("queryClickhouse", () => {
    describe("Error transformation with throwIf", () => {
      // 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}` },
              tags: {
                surface: "trpc",
                route: "test.resource-error",
                projectId: "project-1",
              },
            });
            fail(
              "Should have thrown an error, observed instead " +
                JSON.stringify(res),
            );
          } catch (error: any) {
            expect(error).toBeInstanceOf(ClickHouseResourceError);
            expect(error.errorType).toBe("MEMORY_LIMIT");
            expect(error.tags).toEqual({
              tag_schema_version: "1",
              surface: "trpc",
              route: "test.resource-error",
              projectId: "project-1",
            });
          }
        });
      });

      it("should transform OvercommitTracker errors", async () => {
        try {
          await queryClickhouse({
            query: `SELECT throwIf(true, 'OvercommitTracker decision: Query was selected to stop by OvercommitTracker')`,
          });
          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')`,
          });
          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`,
          }),
        ).rejects.toThrow();

        try {
          await queryClickhouse({
            query: `SELECT * FROM non_existent_table_xyz123`,
          });
        } 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",
        });

        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", () => {
    // 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 = 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) {
              fullResponse.push(item);
            }
            fail(
              "Should have thrown an error, observed instead " +
                JSON.stringify(fullResponse),
            );
          })(),
        ).rejects.toThrow(ClickHouseResourceError);
      });

      it("should stream successful queries", async () => {
        const queryId = randomUUID();
        const generator = queryClickhouseStream({
          query:
            "SELECT number, queryID() AS query_id FROM system.numbers LIMIT 3",
          queryId,
        });

        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");
        expect(results[0]).toHaveProperty("query_id", queryId);
      });
    });

    describe("query_id propagation (LFE-11043)", () => {
      it("should include query_id in errors thrown mid-stream", async () => {
        const generator = queryClickhouseStream({
          query: `SELECT throwIf(number = 2, 'memory limit exceeded: would use 10.23 GiB') as V FROM numbers(10)`,
          clickhouseSettings: { max_block_size: "1" },
        });

        const rows: unknown[] = [];
        try {
          for await (const item of generator) {
            rows.push(item);
          }
          fail("Should have thrown an error");
        } catch (error: any) {
          expect(error).toBeInstanceOf(ClickHouseResourceError);
          expect(error.message).toMatch(QUERY_ID_PATTERN);
        }
      });

      it("should include query_id in errors thrown before streaming starts", async () => {
        const generator = queryClickhouseStream({
          query: `SELECT * FROM non_existent_table_xyz123`,
        });

        const rows: unknown[] = [];
        try {
          for await (const item of generator) {
            rows.push(item);
          }
          fail("Should have thrown an error");
        } catch (error: any) {
          expect(error.message).toMatch(QUERY_ID_PATTERN);
          expect(error.message.match(/\[query_id:/g)).toHaveLength(1);
        }
      });
    });
  });

  describe("queryClickhouseStreamRawText", () => {
    it("should include query_id in errors thrown before streaming starts", async () => {
      const generator = queryClickhouseStreamRawText({
        query: `SELECT * FROM non_existent_table_xyz123`,
      });

      const rows: string[] = [];
      try {
        for await (const item of generator) {
          rows.push(item);
        }
        fail("Should have thrown an error");
      } catch (error: any) {
        expect(error.message).toMatch(QUERY_ID_PATTERN);
        expect(error.message.match(/\[query_id:/g)).toHaveLength(1);
      }
    });
  });

  describe("queryClickhouseWithProgress", () => {
    it("streams the same rows and reports scan counters", async () => {
      const query = "SELECT toUInt32(number) AS n FROM numbers(5)";
      const rows: { n: number }[] = [];
      let readRows = 0;
      let readBytes = 0;
      for await (const item of queryClickhouseWithProgress<{ n: number }>({
        query,
        clickhouseSettings: { interactive_delay: "0", max_block_size: "1" },
      })) {
        if (isRow(item)) rows.push(item.row);
        if (isProgressRow(item)) {
          readRows = Number(item.progress.read_rows);
          readBytes = Number(item.progress.read_bytes);
        }
      }
      expect(rows).toEqual(await queryClickhouse({ query }));
      expect(readRows).toBeGreaterThanOrEqual(5);
      expect(readBytes).toBeGreaterThan(0);
    });

    it.each(["before", "during"])(
      "returns a typed cancellation error when aborted %s a query",
      async (when) => {
        const stream = queryClickhouseWithProgress({
          query: "SELECT sleepEachRow(0.02) FROM numbers(100)",
          abortSignal:
            when === "before" ? AbortSignal.abort() : AbortSignal.timeout(50),
          clickhouseSettings: {
            cancel_http_readonly_queries_on_client_close: 1,
          },
        });
        await expect(Array.fromAsync(stream)).rejects.toBeInstanceOf(
          ClickHouseQueryAbortedError,
        );
      },
    );

    it("should include query_id exactly once in errors thrown before streaming starts", async () => {
      const generator = queryClickhouseWithProgress({
        query: `SELECT * FROM non_existent_table_xyz123`,
      });

      const rows: unknown[] = [];
      try {
        for await (const item of generator) {
          rows.push(item);
        }
        fail("Should have thrown an error");
      } catch (error: any) {
        expect(error.message).toMatch(QUERY_ID_PATTERN);
        expect(error.message.match(/\[query_id:/g)).toHaveLength(1);
      }
    });
  });

  describe("queryClickhouseExecRaw", () => {
    it("should include query_id exactly once in errors thrown before streaming", async () => {
      try {
        await queryClickhouseExecRaw({
          query: `SELECT * FROM non_existent_table_xyz123`,
          format: "Parquet",
        });
        fail("Should have thrown an error");
      } catch (error: any) {
        expect(error.message).toMatch(QUERY_ID_PATTERN);
        expect(error.message.match(/\[query_id:/g)).toHaveLength(1);
      }
    });
  });

  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: "Memory limit for query exceeded (capitalized)",
        errorMessage:
          "Memory limit (for query) exceeded: would use 2.25 GiB (attempt to allocate chunk of 0.00 B), current RSS: 1.42 GiB, maximum: 2.25 GiB",
        shouldBeResourceError: true,
        errorType: "MEMORY_LIMIT",
      },
      {
        name: "Memory limit total exceeded (capitalized)",
        errorMessage:
          "Memory limit (total) exceeded: would use 2.25 GiB, current RSS: 1.42 GiB, maximum: 2.25 GiB",
        shouldBeResourceError: true,
        errorType: "MEMORY_LIMIT",
      },
      {
        name: "Memory limit for user exceeded (capitalized)",
        errorMessage: "Memory limit (for user) exceeded: would use 2.25 GiB",
        shouldBeResourceError: true,
        errorType: "MEMORY_LIMIT",
      },
      {
        name: "Overcommit decision with memory limit message",
        errorMessage:
          "(total) memory limit exceeded: would use 2.25 GiB. OvercommitTracker decision: Query was selected to stop by OvercommitTracker: While executing AggregatingTransform",
        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;
            }
            return false;
          })(wrappedError);

          expect(isResourceError).toBe(shouldBeResourceError);
          expect(ClickHouseResourceError.is(wrappedError)).toBe(
            shouldBeResourceError,
          );

          const resourceError = wrappedError as ClickHouseResourceError;
          if (shouldBeResourceError && errorType) {
            expect(resourceError.errorType).toBe(errorType);
          }
        });
      },
    );
  });
});