Skip to content

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

feat(dashboards): add SSE streaming endpoint for ClickHouse query progress (#12429)

Valery Meleshkinfb2529c7ad09
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index bb8a3317c5..fa985be78d 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -15,7 +15,11 @@ import {
StorageService,
StorageServiceFactory,
} from "../services/StorageService";
-import { ClickHouseSettings, type DataFormat } from "@clickhouse/client";
+import {
+ ClickHouseSettings,
+ type RowOrProgress,
+ type DataFormat,
+} from "@clickhouse/client";
import { RESOURCE_LIMIT_ERROR_MESSAGE } from "../../errors/errorMessages";
/**
@@ -443,6 +447,49 @@ export async function queryClickhouse<T>(
);
}
+export async function* queryClickhouseWithProgress<T>(
+ opts: ClickhouseQueryOpts,
+): AsyncGenerator<RowOrProgress<T>> {
+ if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);
+
+ const tracer = getTracer("clickhouse-query-progress");
+ const span = tracer.startSpan("clickhouse-query-progress", {
+ kind: SpanKind.CLIENT,
+ });
+
+ try {
+ setSpanQueryAttributes(span, opts.query);
+
+ const res = await context
+ .with(trace.setSpan(context.active(), span), () =>
+ sendClickhouseQuery({
+ ...opts,
+ clickhouseSettings: {
+ asterisk_include_alias_columns: 1,
+ asterisk_include_materialized_columns: 1,
+ ...opts.clickhouseSettings,
+ },
+ format: "JSONEachRowWithProgress",
+ span,
+ }),
+ )
+ .catch((error) => {
+ throw ClickHouseResourceError.wrapIfResourceError(error as Error);
+ });
+
+ for await (const rows of res.stream()) {
+ for (const row of rows) {
+ yield row.json() as RowOrProgress<T>;
+ }
+ }
+ } catch (error) {
+ if (error instanceof ClickHouseResourceError) throw error;
+ throw ClickHouseResourceError.wrapIfResourceError(error as Error);
+ } finally {
+ span.end();
+ }
+}
+
export async function commandClickhouse(opts: {
query: string;
params?: Record<string, unknown> | undefined;
@@ -502,6 +549,13 @@ export async function commandClickhouse(opts: {
);
}
+export {
+ isProgressRow,
+ isRow,
+ isException,
+ type RowOrProgress,
+} from "@clickhouse/client";
+
export function parseClickhouseUTCDateTimeFormat(dateStr: string): Date {
return new Date(`${dateStr.replace(" ", "T")}Z`);
}
diff --git a/web/src/__tests__/server/execute-query-stream.servertest.ts b/web/src/__tests__/server/execute-query-stream.servertest.ts
new file mode 100644
index 0000000000..24b699389f
--- /dev/null
+++ b/web/src/__tests__/server/execute-query-stream.servertest.ts
@@ -0,0 +1,285 @@
+/** @jest-environment node */
+import { v4 } from "uuid";
+import { createMocks } from "node-mocks-http";
+import type { NextApiRequest, NextApiResponse } from "next";
+import {
+ createOrgProjectAndApiKey,
+ createTrace,
+ createTracesCh,
+ type TraceRecordInsertType,
+} from "@langfuse/shared/src/server";
+import handler from "../../pages/api/dashboard/execute-query-stream";
+
+// --- Auth mock (only thing we need to mock — no real session in tests) ---
+
+const mockGetServerAuthSession = jest.fn();
+jest.mock("../../server/auth", () => ({
+ getServerAuthSession: (...args: unknown[]) =>
+ mockGetServerAuthSession(...args),
+}));
+
+// Admin webhook — not relevant to streaming logic, just suppress side-effects
+const mockSendAdminAccessWebhook = jest.fn();
+jest.mock("../../server/adminAccessWebhook", () => ({
+ sendAdminAccessWebhook: (...args: unknown[]) =>
+ mockSendAdminAccessWebhook(...args),
+}));
+
+// --- Helpers ---
+
+function createPostMocks(body: unknown) {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "POST",
+ body,
+ });
+ // node-mocks-http doesn't implement flushHeaders
+ res.flushHeaders = jest.fn();
+ return { req, res };
+}
+
+function parseSSEEvents(raw: string): Array<{ event: string; data: string }> {
+ return raw
+ .split("\n\n")
+ .filter(Boolean)
+ .map((block) => {
+ const eventMatch = block.match(/^event: (.+)$/m);
+ const dataMatch = block.match(/^data: (.+)$/m);
+ return {
+ event: eventMatch?.[1] ?? "",
+ data: dataMatch?.[1] ?? "",
+ };
+ });
+}
+
+// --- Test setup ---
+
+describe("execute-query-stream handler", () => {
+ let projectId: string;
+ let orgId: string;
+ let fromTimestamp: string;
+ let toTimestamp: string;
+
+ beforeAll(async () => {
+ const org = await createOrgProjectAndApiKey();
+ projectId = org.projectId;
+ orgId = org.orgId;
+
+ const baseTime = new Date("2024-06-15T12:00:00Z").getTime();
+ const TRACE_COUNT = 5;
+
+ const traces: TraceRecordInsertType[] = [];
+ for (let i = 0; i < TRACE_COUNT; i++) {
+ traces.push(
+ createTrace({
+ id: v4(),
+ project_id: projectId,
+ name: `test-trace-${i}`,
+ timestamp: baseTime + i * 60_000,
+ environment: "default",
+ tags: [],
+ metadata: {},
+ created_at: baseTime + i * 60_000,
+ updated_at: baseTime + i * 60_000,
+ event_ts: baseTime + i * 60_000,
+ }),
+ );
+ }
+
+ await createTracesCh(traces);
+
+ fromTimestamp = new Date(baseTime - 60 * 60 * 1000).toISOString();
+ toTimestamp = new Date(baseTime + 60 * 60 * 1000).toISOString();
+ });
+
+ function makeSession(overrides?: {
+ admin?: boolean;
+ projects?: Array<{ id: string }>;
+ }) {
+ return {
+ user: {
+ id: "user-1",
+ email: "[email protected]",
+ admin: overrides?.admin ?? false,
+ organizations: [
+ {
+ id: orgId,
+ projects: overrides?.projects ?? [{ id: projectId }],
+ },
+ ],
+ },
+ };
+ }
+
+ function makeBody(queryOverrides?: Record<string, unknown>) {
+ return {
+ projectId,
+ query: {
+ view: "traces" as const,
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: null,
+ fromTimestamp,
+ toTimestamp,
+ orderBy: null,
+ ...queryOverrides,
+ },
+ };
+ }
+
+ // --- Auth tests (mocks are appropriate here) ---
+
+ it("should return 405 for non-POST requests", async () => {
+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({
+ method: "GET",
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(405);
+ });
+
+ it("should return 401 when no session", async () => {
+ mockGetServerAuthSession.mockResolvedValue(null);
+ const { req, res } = createPostMocks(makeBody());
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(401);
+ expect(JSON.parse(res._getData())).toMatchObject({
+ message: "Unauthorized",
+ });
+ });
+
+ it("should return 403 when user is not a project member", async () => {
+ mockGetServerAuthSession.mockResolvedValue(
+ makeSession({ projects: [{ id: "other-project" }] }),
+ );
+ const { req, res } = createPostMocks(makeBody());
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(403);
+ expect(JSON.parse(res._getData())).toMatchObject({
+ message: "Not a member of this project",
+ });
+ });
+
+ it("should return 400 for invalid input", async () => {
+ mockGetServerAuthSession.mockResolvedValue(makeSession());
+ const { req, res } = createPostMocks({ projectId: 123 });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(400);
+ expect(JSON.parse(res._getData())).toMatchObject({
+ message: "Invalid input",
+ });
+ });
+
+ it("should return 404 when admin accesses non-existent project", async () => {
+ mockGetServerAuthSession.mockResolvedValue(
+ makeSession({ admin: true, projects: [] }),
+ );
+ const { req, res } = createPostMocks({
+ ...makeBody(),
+ projectId: v4(), // random non-existent project
+ });
+
+ await handler(req, res);
+
+ expect(res._getStatusCode()).toBe(404);
+ expect(JSON.parse(res._getData())).toMatchObject({
+ message: "Project not found",
+ });
+ });
+
+ it("should allow admin access to project they are not a member of and send webhook", async () => {
+ mockGetServerAuthSession.mockResolvedValue(
+ makeSession({ admin: true, projects: [] }),
+ );
+ const { req, res } = createPostMocks(makeBody());
+
+ await handler(req, res);
+
+ expect(mockSendAdminAccessWebhook).toHaveBeenCalledWith({
+ email: "[email protected]",
+ projectId,
+ orgId,
+ });
+ // Should still stream data successfully
+ const events = parseSSEEvents(res._getData());
+ expect(events.some((e) => e.event === "done")).toBe(true);
+ });
+
+ // --- Integration tests (real ClickHouse) ---
+
+ it("should stream real trace count from ClickHouse and end with done", async () => {
+ mockGetServerAuthSession.mockResolvedValue(makeSession());
+ const { req, res } = createPostMocks(makeBody());
+
+ await handler(req, res);
+
+ const events = parseSSEEvents(res._getData());
+
+ const rowEvents = events.filter((e) => e.event === "row");
+ expect(rowEvents.length).toBeGreaterThanOrEqual(1);
+
+ // The count query returns count_count (measure_aggregation naming)
+ const firstRow = JSON.parse(rowEvents[0].data);
+ expect(Number(firstRow.count_count)).toBe(5);
+
+ const doneEvents = events.filter((e) => e.event === "done");
+ expect(doneEvents).toHaveLength(1);
+ });
+
+ it("should stream rows with dimension grouping", async () => {
+ mockGetServerAuthSession.mockResolvedValue(makeSession());
+ const { req, res } = createPostMocks(
+ makeBody({
+ dimensions: [{ field: "name" }],
+ orderBy: null,
+ }),
+ );
+
+ await handler(req, res);
+
+ const events = parseSSEEvents(res._getData());
+ const rowEvents = events.filter((e) => e.event === "row");
+
+ // 5 distinct trace names (test-trace-0 through test-trace-4)
+ expect(rowEvents).toHaveLength(5);
+
+ const rows = rowEvents.map((e) => JSON.parse(e.data));
+ for (const row of rows) {
+ expect(row).toHaveProperty("name");
+ expect(row).toHaveProperty("count_count");
+ expect(Number(row.count_count)).toBe(1);
+ }
+
+ expect(events.some((e) => e.event === "done")).toBe(true);
+ });
+
+ it("should return empty result for non-matching time range", async () => {
+ mockGetServerAuthSession.mockResolvedValue(makeSession());
+ const { req, res } = createPostMocks(
+ makeBody({
+ fromTimestamp: "2020-01-01T00:00:00.000Z",
+ toTimestamp: "2020-01-02T00:00:00.000Z",
+ }),
+ );
+
+ await handler(req, res);
+
+ const events = parseSSEEvents(res._getData());
+ const rowEvents = events.filter((e) => e.event === "row");
+
+ // Should get one row with count = 0 (aggregate with no matching data)
+ expect(rowEvents.length).toBeLessThanOrEqual(1);
+ if (rowEvents.length === 1) {
+ expect(Number(JSON.parse(rowEvents[0].data).count_count)).toBe(0);
+ }
+
+ expect(events.some((e) => e.event === "done")).toBe(true);
+ });
+});
diff --git a/web/src/__tests__/server/repositories/clickhouse-progress.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-progress.servertest.ts
new file mode 100644
index 0000000000..9b03c79cef
--- /dev/null
+++ b/web/src/__tests__/server/repositories/clickhouse-progress.servertest.ts
@@ -0,0 +1,95 @@
+import {
+ queryClickhouse,
+ queryClickhouseWithProgress,
+ isProgressRow,
+ isRow,
+ isException,
+} from "@langfuse/shared/src/server";
+
+async function getClickhouseMajorVersion(): Promise<number> {
+ const rows = await queryClickhouse<{ v: string }>({
+ query: "SELECT version() AS v",
+ });
+ return parseInt(rows[0].v.split(".")[0], 10);
+}
+
+describe("queryClickhouseWithProgress", () => {
+ it("should yield data rows wrapped in { row: T }", async () => {
+ const generator = queryClickhouseWithProgress<{ number: string }>({
+ query: "SELECT number FROM system.numbers LIMIT 5",
+ });
+
+ const dataRows: { number: string }[] = [];
+ for await (const event of generator) {
+ if (isRow<{ number: string }>(event)) {
+ dataRows.push(event.row);
+ }
+ }
+
+ expect(dataRows).toHaveLength(5);
+ expect(dataRows[0]).toHaveProperty("number");
+ });
+
+ it("should yield progress events with expected fields", async () => {
+ // Use a larger query to increase the chance of getting progress events.
+ // Progress events are not guaranteed for small/fast queries, so we
+ // verify the structure only when they appear.
+ const generator = queryClickhouseWithProgress<{ n: number }>({
+ query: "SELECT number as n FROM system.numbers LIMIT 100000",
+ });
+
+ const progressEvents: unknown[] = [];
+ const dataRows: unknown[] = [];
+
+ for await (const event of generator) {
+ if (isProgressRow(event)) {
+ progressEvents.push(event.progress);
+ } else if (isRow(event)) {
+ dataRows.push(event.row);
+ }
+ }
+
+ // Data rows should always be present
+ expect(dataRows.length).toBe(100000);
+
+ // Progress events may or may not appear depending on query speed.
+ // When they do appear, verify their structure.
+ for (const p of progressEvents) {
+ expect(p).toHaveProperty("read_rows");
+ expect(p).toHaveProperty("read_bytes");
+ expect(p).toHaveProperty("elapsed_ns");
+ }
+ });
+
+ it("should yield exception events for errors during streaming", async () => {
+ const majorVersion = await getClickhouseMajorVersion();
+ if (majorVersion < 25) {
+ // JSONEachRowWithProgress does not include exception rows on CH < 25
+ return;
+ }
+
+ const generator = queryClickhouseWithProgress({
+ query: `SELECT throwIf(number = 2, 'memory limit exceeded: would use 10.23 GiB') AS v FROM numbers(10)`,
+ clickhouseSettings: { max_block_size: "1" },
+ });
+
+ let foundException = false;
+ let caughtError = false;
+
+ try {
+ for await (const event of generator) {
+ if (isException(event)) {
+ foundException = true;
+ expect(event.exception).toContain("memory limit exceeded");
+ break;
+ }
+ }
+ } catch {
+ // ClickHouse may throw at HTTP level depending on timing
+ caughtError = true;
+ }
+
+ // Either the error came as an exception row or was thrown
+ expect(foundException || caughtError).toBe(true);
+ });
+});
diff --git a/web/src/pages/api/dashboard/execute-query-stream.ts b/web/src/pages/api/dashboard/execute-query-stream.ts
new file mode 100644
index 0000000000..ec98b3ce5a
--- /dev/null
+++ b/web/src/pages/api/dashboard/execute-query-stream.ts
@@ -0,0 +1,183 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import * as z from "zod/v4";
+import {
+ isProgressRow,
+ isRow,
+ isException,
+ ClickHouseResourceError,
+ queryClickhouseWithProgress,
+} from "@langfuse/shared/src/server";
+import { RESOURCE_LIMIT_ERROR_MESSAGE } from "@langfuse/shared";
+import { logger } from "@langfuse/shared/src/server";
+
+import { getServerAuthSession } from "@/src/server/auth";
+import { sendAdminAccessWebhook } from "@/src/server/adminAccessWebhook";
+import { prisma } from "@langfuse/shared/src/db";
+import { query as customQuery, viewVersions } from "@/src/features/query/types";
+import {
+ prepareExecuteQuery,
+ toClickhouseQueryOpts,
+ validateQuery,
+} from "@/src/features/query/server/queryExecutor";
+
+export type SSEEvent =
+ | { type: "progress"; progress: object }
+ | { type: "row"; row: Record<string, unknown> }
+ | { type: "done" }
+ | { type: "error"; message: string };
+
+function formatSSEEvent(event: SSEEvent): string {
+ switch (event.type) {
+ case "progress":
+ return `event: progress\ndata: ${JSON.stringify(event.progress)}\n\n`;
+ case "row":
+ return `event: row\ndata: ${JSON.stringify(event.row)}\n\n`;
+ case "done":
+ return `event: done\ndata: {}\n\n`;
+ case "error":
+ return `event: error\ndata: ${JSON.stringify({ message: event.message })}\n\n`;
+ }
+}
+
+const inputSchema = z.object({
+ projectId: z.string(),
+ query: customQuery,
+ version: viewVersions.optional().default("v1"),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.setHeader("Allow", "POST");
+ res.status(405).end();
+ return;
+ }
+
+ const session = await getServerAuthSession({ req, res });
+ if (!session?.user) {
+ res.status(401).json({ message: "Unauthorized" });
+ return;
+ }
+
+ const parsed = inputSchema.safeParse(req.body);
+ if (!parsed.success) {
+ res.status(400).json({ message: "Invalid input", errors: parsed.error });
+ return;
+ }
+
+ const { projectId, query, version } = parsed.data;
+
+ // Verify user is a member of this project (mirrors enforceUserIsAuthedAndProjectMember)
+ const sessionProject = session.user.organizations
+ .flatMap((org) =>
+ org.projects.map((project) => ({ ...project, organization: org })),
+ )
+ .find((project) => project.id === projectId);
+
+ if (!sessionProject) {
+ if (session.user.admin === true) {
+ const dbProject = await prisma.project.findFirst({
+ select: { orgId: true },
+ where: { id: projectId, deletedAt: null },
+ });
+ if (!dbProject) {
+ res.status(404).json({ message: "Project not found" });
+ return;
+ }
+ await sendAdminAccessWebhook({
+ email: session.user.email,
+ projectId,
+ orgId: dbProject.orgId,
+ });
+ } else {
+ res.status(403).json({ message: "Not a member of this project" });
+ return;
+ }
+ } else if (session.user.admin === true) {
+ await sendAdminAccessWebhook({
+ email: session.user.email,
+ projectId,
+ orgId: sessionProject.organization.id,
+ });
+ }
+
+ const validation = validateQuery(query, version);
+ if (!validation.valid) {
+ res.status(400).json({ message: "Invalid query", errors: validation });
+ return;
+ }
+
+ // SSE headers
+ res.writeHead(200, {
+ "Content-Type": "text/event-stream",
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no",
+ });
+ res.flushHeaders();
+
+ let aborted = false;
+ req.on("close", () => {
+ aborted = true;
+ });
+
+ try {
+ const prepared = await prepareExecuteQuery({
+ projectId,
+ query,
+ version,
+ enableSingleLevelOptimization: version === "v2",
+ });
+ const chOpts = toClickhouseQueryOpts(prepared);
+
+ for await (const event of queryClickhouseWithProgress<
+ Record<string, unknown>
+ >(chOpts)) {
+ if (aborted) break;
+
+ if (isProgressRow(event)) {
+ res.write(
+ formatSSEEvent({ type: "progress", progress: event.progress }),
+ );
+ } else if (isRow<Record<string, unknown>>(event)) {
+ res.write(formatSSEEvent({ type: "row", row: event.row }));
+ } else if (isException(event)) {
+ const isResource =
+ ClickHouseResourceError.wrapIfResourceError(
+ new Error(event.exception),
+ ) instanceof ClickHouseResourceError;
+ logger.error(
+ `[execute-query-stream] ClickHouse exception: ${event.exception}`,
+ { projectId },
+ );
+ const userMessage = isResource
+ ? RESOURCE_LIMIT_ERROR_MESSAGE
+ : event.exception;
+ res.write(formatSSEEvent({ type: "error", message: userMessage }));
+ return;
+ }
+ }
+
+ if (!aborted) {
+ res.write(formatSSEEvent({ type: "done" }));
+ }
+ } catch (error) {
+ if (!aborted) {
+ logger.error("[execute-query-stream] Query failed", {
+ error: error instanceof Error ? error.message : String(error),
+ projectId,
+ });
+ const message =
+ error instanceof ClickHouseResourceError
+ ? RESOURCE_LIMIT_ERROR_MESSAGE
+ : error instanceof Error
+ ? error.message
+ : "Internal server error";
+ res.write(formatSSEEvent({ type: "error", message }));
+ }
+ } finally {
+ res.end();
+ }
+}