🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
fix(queries): show useful errors and allow 60-second execution
Bill Yang8e627f109d8b
diff --git a/server/src/api/analytics/customQueryExecution.test.ts b/server/src/api/analytics/customQueryExecution.test.tsnew file mode 100644index 000000000..84a6daf50--- /dev/null+++ b/server/src/api/analytics/customQueryExecution.test.ts@@ -0,0 +1,81 @@+import { ClickHouseError } from "@clickhouse/client";+import Fastify, { FastifyInstance } from "fastify";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ query: vi.fn(), getSitesUserHasAccessTo: vi.fn() }));+vi.mock("../../db/clickhouse/clickhouse.js", () => ({ clickhouseQuery: { query: mocks.query } }));+vi.mock("../../lib/auth-utils.js", () => ({ getSitesUserHasAccessTo: mocks.getSitesUserHasAccessTo }));++import { runCustomQuery } from "./runCustomQuery.js";+import { runDashboardCardQuery } from "./runDashboardCardQuery.js";++let app: FastifyInstance;++beforeEach(async () => {+ vi.resetAllMocks();+ mocks.getSitesUserHasAccessTo.mockResolvedValue([{ siteId: 1, organizationId: "org-1" }]);+ app = Fastify();+ app.post<{ Params: { organizationId: string }; Body: unknown }>(+ "/organizations/:organizationId/query",+ runCustomQuery+ );+ app.post<{ Params: { siteId: string }; Body: unknown }>("/sites/:siteId/run-card", runDashboardCardQuery);+ await app.ready();+});++afterEach(async () => {+ await app.close();+});++describe.each(["/organizations/org-1/query", "/sites/1/run-card"])("custom SQL response at %s", url => {+ const request = () => app.inject({ method: "POST", url, payload: { query: "SELECT count() FROM scoped_events" } });++ it.each(["query", "json"])("returns an actionable SDK timeout raised during %s", async stage => {+ const error = new ClickHouseError({+ code: "159",+ type: "TIMEOUT_EXCEEDED",+ message: "Timeout exceeded: elapsed 60040 ms, maximum: 60000 ms.",+ });+ if (stage === "query") {+ mocks.query.mockRejectedValue(error);+ } else {+ mocks.query.mockResolvedValue({+ json: async () => {+ throw error;+ },+ });+ }++ const response = await request();+ expect(response.statusCode).toBe(400);+ expect(response.json()).toEqual({+ error: "Query exceeded the 60-second time limit. Try a shorter date range or simplify the query.",+ });+ });++ it("returns the SQL error instead of a generic failure", async () => {+ mocks.query.mockRejectedValue(+ new ClickHouseError({+ code: "47",+ type: "UNKNOWN_IDENTIFIER",+ message: "Unknown expression identifier 'missing_column'",+ })+ );++ const response = await request();+ expect(response.statusCode).toBe(400);+ expect(response.json()).toEqual({ error: "Unknown expression identifier 'missing_column'" });+ });++ it("reports the 60-second execution limit for successful queries", async () => {+ mocks.query.mockResolvedValue({ query_id: "test-query", json: async () => [{ count: 1 }] });+ const response = await request();+ expect(response.statusCode).toBe(200);+ expect(response.json().meta).toEqual({+ queryId: "test-query",+ rowCount: 1,+ maxExecutionTimeSeconds: 60,+ maxRows: 1000,+ });+ });+});diff --git a/server/src/api/analytics/runCustomQuery.ts b/server/src/api/analytics/runCustomQuery.tsindex b969b635e..7f21f2124 100644--- a/server/src/api/analytics/runCustomQuery.ts+++ b/server/src/api/analytics/runCustomQuery.ts@@ -1,6 +1,7 @@import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { clickhouseQuery } from "../../db/clickhouse/clickhouse.js";+import { QUERY_USER_LIMITS } from "../../db/clickhouse/queryLimits.js";import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";import {MAX_CUSTOM_QUERY_LENGTH,@@ -9,10 +10,6 @@ import {validateScopedQuery,} from "./utils/customQueryValidation.js";-// Mirrors the rybbit_query ClickHouse profile (docker-compose clickhouse_user_settings).-const MAX_EXECUTION_TIME_SECONDS = 10;-const MAX_RESULT_ROWS = 1000;-const requestBodySchema = z.object({query: z.string().trim().min(1).max(MAX_CUSTOM_QUERY_LENGTH),// When provided, scope scoped_events to this single site (the per-site Query@@ -75,7 +72,7 @@ export async function runCustomQuery(format: "JSONEachRow",query_params: {siteIds,- limit: MAX_RESULT_ROWS,+ limit: QUERY_USER_LIMITS.maxResultRows,},// Execution limits (readonly, max_execution_time, max_memory_usage,// max_result_rows, …) come from the rybbit_query settings profile and are@@ -88,8 +85,8 @@ export async function runCustomQuery(meta: {queryId: result.query_id,rowCount: data.length,- maxExecutionTimeSeconds: MAX_EXECUTION_TIME_SECONDS,- maxRows: MAX_RESULT_ROWS,+ maxExecutionTimeSeconds: QUERY_USER_LIMITS.maxExecutionTimeSeconds,+ maxRows: QUERY_USER_LIMITS.maxResultRows,},});} catch (error) {diff --git a/server/src/api/analytics/runDashboardCardQuery.ts b/server/src/api/analytics/runDashboardCardQuery.tsindex d50c2c06a..b457b91f0 100644--- a/server/src/api/analytics/runDashboardCardQuery.ts+++ b/server/src/api/analytics/runDashboardCardQuery.ts@@ -2,6 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";import SqlString from "sqlstring";import { z } from "zod";import { clickhouseQuery } from "../../db/clickhouse/clickhouse.js";+import { QUERY_USER_LIMITS } from "../../db/clickhouse/queryLimits.js";import {MAX_CUSTOM_QUERY_LENGTH,normalizeCustomQuery,@@ -11,10 +12,6 @@ import {import { validateHttpTimeParams } from "./utils/query-validation.js";import { bucketIntervalMap, getTimeStatement } from "./utils/timeWindow.js";-// Mirrors the rybbit_query ClickHouse profile (docker-compose clickhouse_user_settings).-const MAX_EXECUTION_TIME_SECONDS = 10;-const MAX_RESULT_ROWS = 1000;-const BUCKET_TOKEN = /\{\{\s*bucket\s*\}\}/gi;const TZ_TOKEN = /\{\{\s*tz\s*\}\}/gi;@@ -81,9 +78,7 @@ export async function runDashboardCardQuery(// so day buckets align to local calendar days, matching the standard charts.const bucketInterval = bucketIntervalMap[body.data.bucket ?? "hour"];const timeZoneLiteral = SqlString.escape(body.data.timeZone || "UTC");- const substitutedQuery = body.data.query- .replace(BUCKET_TOKEN, bucketInterval)- .replace(TZ_TOKEN, timeZoneLiteral);+ const substitutedQuery = body.data.query.replace(BUCKET_TOKEN, bucketInterval).replace(TZ_TOKEN, timeZoneLiteral);const validationError = validateScopedQuery(substitutedQuery);if (validationError) {@@ -115,7 +110,7 @@ export async function runDashboardCardQuery(format: "JSONEachRow",query_params: {siteIds: [siteId],- limit: MAX_RESULT_ROWS,+ limit: QUERY_USER_LIMITS.maxResultRows,},// Execution limits (readonly, max_execution_time, max_memory_usage,// max_result_rows, …) come from the rybbit_query settings profile and are@@ -128,8 +123,8 @@ export async function runDashboardCardQuery(meta: {queryId: result.query_id,rowCount: data.length,- maxExecutionTimeSeconds: MAX_EXECUTION_TIME_SECONDS,- maxRows: MAX_RESULT_ROWS,+ maxExecutionTimeSeconds: QUERY_USER_LIMITS.maxExecutionTimeSeconds,+ maxRows: QUERY_USER_LIMITS.maxResultRows,},});} catch (error) {diff --git a/server/src/api/analytics/utils/customQueryValidation.test.ts b/server/src/api/analytics/utils/customQueryValidation.test.tsindex 47286963c..d7836a0b3 100644--- a/server/src/api/analytics/utils/customQueryValidation.test.ts+++ b/server/src/api/analytics/utils/customQueryValidation.test.ts@@ -1,3 +1,4 @@+import { ClickHouseError } from "@clickhouse/client";import { describe, expect, it } from "vitest";import { sanitizeClickhouseError, validateScopedQuery } from "./customQueryValidation.js";@@ -167,6 +168,67 @@ describe("validateScopedQuery lexer-mismatch bypasses", () => {});describe("sanitizeClickhouseError", () => {+ it("uses the SDK's separate error code to preserve SQL diagnostics", () => {+ const error = new ClickHouseError({+ code: "47",+ type: "UNKNOWN_IDENTIFIER",+ message: "Unknown expression identifier 'missing_column' (from 10.0.0.1:8123)",+ });+ expect(sanitizeClickhouseError(error)).toBe("Unknown expression identifier 'missing_column'");+ });++ it("explains the execution timeout reported by the SDK", () => {+ const error = new ClickHouseError({+ code: "159",+ type: "TIMEOUT_EXCEEDED",+ message: "Timeout exceeded: elapsed 60040 ms, maximum: 60000 ms.",+ });+ expect(sanitizeClickhouseError(error)).toBe(+ "Query exceeded the 60-second time limit. Try a shorter date range or simplify the query."+ );+ });++ it.each(["sdk", "raw"])("explains %s memory errors without exposing storage paths", format => {+ const message =+ "Query memory limit exceeded: would use 3.73 GiB: (while reading from part /var/lib/clickhouse/store/private/).";+ const error =+ format === "sdk"+ ? new ClickHouseError({ code: "241", type: "MEMORY_LIMIT_EXCEEDED", message })+ : new Error(`Code: 241. DB::Exception: ${message}`);+ expect(sanitizeClickhouseError(error)).toBe(+ "Query exceeded the memory limit. Try a shorter date range or simplify the query."+ );+ });++ it("explains the SDK's connection timeout", () => {+ expect(sanitizeClickhouseError(new Error("Timeout error."))).toBe(+ "Timed out waiting for the database. Try again or use a shorter date range."+ );+ });++ it("explains connection failures without exposing the database address", () => {+ const error = Object.assign(new Error("connect ECONNREFUSED 10.0.0.1:8123"), { code: "ECONNREFUSED" });+ expect(sanitizeClickhouseError(error)).toBe("Could not connect to the database. Please try again shortly.");+ });++ it("explains the concurrent-query limit", () => {+ const error = new ClickHouseError({+ code: "202",+ type: "TOO_MANY_SIMULTANEOUS_QUERIES",+ message: "Too many simultaneous queries for user rybbit_query.",+ });+ expect(sanitizeClickhouseError(error)).toBe("Too many queries are running at once. Wait a moment and try again.");+ });++ it("keeps internal SDK errors private", () => {+ const error = new ClickHouseError({+ code: "1",+ type: "UNSUPPORTED_METHOD",+ message: "user rybbit_query failed reading /var/lib/clickhouse/store/x.bin on host ch-1",+ });+ expect(sanitizeClickhouseError(error)).toBe("Query failed (ClickHouse error 1)");+ });+it("strips version, table UUIDs and stack traces", () => {const message ="Code: 47. DB::Exception: Unknown expression identifier 'foo' (table default.events (072583d3-1467-4d46-89ff-3f6981180a16)). (UNKNOWN_IDENTIFIER) (version 26.7.4.58 (official build))";diff --git a/server/src/api/analytics/utils/customQueryValidation.ts b/server/src/api/analytics/utils/customQueryValidation.tsindex b3c7f136c..d451bc6c0 100644--- a/server/src/api/analytics/utils/customQueryValidation.ts+++ b/server/src/api/analytics/utils/customQueryValidation.ts@@ -1,3 +1,5 @@+import { QUERY_USER_LIMITS } from "../../../db/clickhouse/queryLimits.js";+export const MAX_CUSTOM_QUERY_LENGTH = 20_000;const blockedKeywords = [@@ -519,17 +521,13 @@ const userFacingClickhouseErrorCodes = new Set([70, // CANNOT_CONVERT_TYPE117, // INCORRECT_DATA158, // TOO_MANY_ROWS- 159, // TIMEOUT_EXCEEDED- 160, // TOO_SLOW164, // READONLY179, // MULTIPLE_EXPRESSIONS_FOR_ALIAS182, // ILLEGAL_PREWHERE184, // ILLEGAL_AGGREGATION215, // NOT_AN_AGGREGATE- 241, // MEMORY_LIMIT_EXCEEDED306, // TOO_DEEP_RECURSION386, // NO_COMMON_TYPE- 394, // QUERY_WAS_CANCELLED452, // SETTING_CONSTRAINT_VIOLATION497, // ACCESS_DENIED (handled separately, listed for clarity)]);@@ -539,10 +537,38 @@ export function sanitizeClickhouseError(error: unknown): string {if (!raw) {return "Failed to run query";}- const code = Number(/^Code: (\d+)\./.exec(raw)?.[1]);+ // The SDK removes "Code: ..." from message and puts it on error.code.+ // Also accept unparsed ClickHouse errors returned while reading a response.+ const errorCode = error instanceof Error && "code" in error ? error.code : undefined;+ const code = Number(+ (typeof errorCode === "string" || typeof errorCode === "number") && /^\d+$/.test(String(errorCode))+ ? errorCode+ : /^Code: (\d+)\./.exec(raw)?.[1]+ );if (code === 497 || /Not enough privileges/i.test(raw)) {return "Query references data outside scoped_events";}+ if (code === 159 || code === 160) {+ return `Query exceeded the ${QUERY_USER_LIMITS.maxExecutionTimeSeconds}-second time limit. Try a shorter date range or simplify the query.`;+ }+ if (code === 241) {+ return "Query exceeded the memory limit. Try a shorter date range or simplify the query.";+ }+ if (code === 202) {+ return "Too many queries are running at once. Wait a moment and try again.";+ }+ if (code === 394) {+ return "Query was cancelled. Try running it again.";+ }+ if (raw === "Timeout error." || errorCode === "ETIMEDOUT") {+ return "Timed out waiting for the database. Try again or use a shorter date range.";+ }+ if (+ typeof errorCode === "string" &&+ ["ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EAI_AGAIN", "EPIPE"].includes(errorCode)+ ) {+ return "Could not connect to the database. Please try again shortly.";+ }if (!Number.isFinite(code) || !userFacingClickhouseErrorCodes.has(code)) {return Number.isFinite(code) ? `Query failed (ClickHouse error ${code})` : "Failed to run query";}diff --git a/server/src/db/clickhouse/client.ts b/server/src/db/clickhouse/client.tsindex 1bd9135e1..7307c7c8a 100644--- a/server/src/db/clickhouse/client.ts+++ b/server/src/db/clickhouse/client.ts@@ -1,4 +1,5 @@import { createClient } from "@clickhouse/client";+import { QUERY_REQUEST_TIMEOUT_MS } from "./queryLimits.js";export const CLICKHOUSE_REQUEST_TIMEOUT_MS = 300_000;@@ -10,9 +11,9 @@ export const clickhouse = createClient({});// Least-privilege connection for user-authored SQL (custom query page and-// dashboard cards). The `rybbit_query` user is defined in the ClickHouse-// users.d config shipped in docker-compose: SELECT on the events table only,-// no table-function grants (url/s3/file/remote…), readonly=2, and its own+// dashboard cards). queryUser.ts provisions `rybbit_query` at startup with+// SELECT on the events table only, no table-function grants (url/s3/file/remote…),+// readonly=2, and its own// memory/time/concurrency limits. The SQL validator is defense-in-depth on top// of this — a validator bypass must still land inside these grants.export const CLICKHOUSE_QUERY_USER = process.env.CLICKHOUSE_QUERY_USER || "rybbit_query";@@ -22,5 +23,5 @@ export const clickhouseQuery = createClient({database: process.env.CLICKHOUSE_DB,username: CLICKHOUSE_QUERY_USER,password: process.env.CLICKHOUSE_QUERY_PASSWORD || process.env.CLICKHOUSE_PASSWORD,- request_timeout: 30_000,+ request_timeout: QUERY_REQUEST_TIMEOUT_MS,});diff --git a/server/src/db/clickhouse/queryLimits.ts b/server/src/db/clickhouse/queryLimits.tsnew file mode 100644index 000000000..582337ae3--- /dev/null+++ b/server/src/db/clickhouse/queryLimits.ts@@ -0,0 +1,12 @@+// Shared by query-user provisioning, the HTTP client, and custom-query responses.+export const QUERY_USER_LIMITS = {+ maxExecutionTimeSeconds: 60,+ maxMemoryUsageBytes: 4_000_000_000,+ maxThreads: 4,+ maxResultRows: 1000,+ maxConcurrentQueriesForUser: 8,+ maxBytesBeforeExternalBytes: 2_000_000_000,+} as const;++// Let ClickHouse return its execution-timeout error before the socket times out.+export const QUERY_REQUEST_TIMEOUT_MS = (QUERY_USER_LIMITS.maxExecutionTimeSeconds + 15) * 1000;diff --git a/server/src/db/clickhouse/queryUser.test.ts b/server/src/db/clickhouse/queryUser.test.tsindex 3f2303a08..fa3bef301 100644--- a/server/src/db/clickhouse/queryUser.test.ts+++ b/server/src/db/clickhouse/queryUser.test.ts@@ -10,7 +10,7 @@ describe("buildQueryUserStatements", () => {const profile = statements.find(s => s.startsWith("ALTER SETTINGS PROFILE"))!;for (const setting of ["readonly = 2",- "max_execution_time = 10",+ "max_execution_time = 60","max_memory_usage = 4000000000","max_threads = 4","max_result_rows = 1000",diff --git a/server/src/db/clickhouse/queryUser.ts b/server/src/db/clickhouse/queryUser.tsindex 4711d6c8e..4ffde1009 100644--- a/server/src/db/clickhouse/queryUser.ts+++ b/server/src/db/clickhouse/queryUser.ts@@ -1,6 +1,9 @@import SqlString from "sqlstring";import { CLICKHOUSE_QUERY_USER, clickhouse, clickhouseQuery } from "./client.js";import { clickhouseInitLogger as logger } from "./initUtils.js";+import { QUERY_USER_LIMITS } from "./queryLimits.js";++export { QUERY_USER_LIMITS } from "./queryLimits.js";// Least-privilege ClickHouse user for user-authored SQL (custom query page and// dashboard cards). Provisioned with SQL at startup so every deployment type@@ -13,15 +16,6 @@ import { clickhouseInitLogger as logger } from "./initUtils.js";// The SQL validator is defense-in-depth on top of this user: a validator bypass// must still land inside SELECT-on-events, with no table functions// (url/s3/file/remote…), no system tables, and the pinned resource limits.-export const QUERY_USER_LIMITS = {- maxExecutionTimeSeconds: 10,- maxMemoryUsageBytes: 4_000_000_000,- maxThreads: 4,- maxResultRows: 1000,- maxConcurrentQueriesForUser: 8,- maxBytesBeforeExternalBytes: 2_000_000_000,-} as const;-const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;export function buildQueryUserStatements(database: string, user: string, password: string): string[] {