Skip to content

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

chore(clickhouse): propagate query_id to streaming queries and log_comment to all queries (LFE-11043) (#15201)

Niklas Semmler5796c4333d9a
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index ad25648d18..a1ce7cf835 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -264,14 +264,17 @@ export async function* queryClickhouseStream<T>(
kind: SpanKind.CLIENT,
});
- let queryId: string | undefined;
+ // Client-generated so failures before/without a response still carry a
+ // query_id on errors and spans; system.query_log stays pollable by id.
+ const queryId = randomUUID();
try {
setSpanQueryAttributes(span, opts.query);
+ span.setAttribute("ch.queryId", queryId);
const res = await context
.with(trace.setSpan(context.active(), span), () =>
- sendClickhouseQuery({ ...opts, format: "JSONEachRow", span }),
+ sendClickhouseQuery({ ...opts, format: "JSONEachRow", span, queryId }),
)
.catch((error) => {
throw ClickHouseResourceError.wrapIfResourceError(
@@ -280,9 +283,6 @@ export async function* queryClickhouseStream<T>(
);
});
- queryId = res.query_id;
- span.setAttribute("ch.queryId", queryId);
-
for await (const rows of res.stream<T>()) {
for (const row of rows) {
yield handleExceptionRow(row.json());
@@ -335,14 +335,17 @@ export async function* queryClickhouseStreamRawText(
kind: SpanKind.CLIENT,
});
- let queryId: string | undefined;
+ // Client-generated so failures before/without a response still carry a
+ // query_id on errors and spans; system.query_log stays pollable by id.
+ const queryId = randomUUID();
try {
setSpanQueryAttributes(span, opts.query);
+ span.setAttribute("ch.queryId", queryId);
const res = await context
.with(trace.setSpan(context.active(), span), () =>
- sendClickhouseQuery({ ...opts, format: "JSONEachRow", span }),
+ sendClickhouseQuery({ ...opts, format: "JSONEachRow", span, queryId }),
)
.catch((error) => {
throw ClickHouseResourceError.wrapIfResourceError(
@@ -351,9 +354,6 @@ export async function* queryClickhouseStreamRawText(
);
});
- queryId = res.query_id;
- span.setAttribute("ch.queryId", queryId);
-
for await (const rows of res.stream()) {
for (const row of rows) {
yield row.text;
@@ -420,36 +420,32 @@ export async function queryClickhouseExecRaw(
kind: SpanKind.CLIENT,
});
- let queryId: string | undefined;
+ // Client-generated so failures before/without a response still carry a
+ // query_id on errors and spans; system.query_log stays pollable by id.
+ const queryId = randomUUID();
try {
const queryWithFormat = `${opts.query}\nFORMAT ${opts.format}`;
setSpanQueryAttributes(span, queryWithFormat);
-
- const res = await context
- .with(trace.setSpan(context.active(), span), () =>
- clickhouseClient(
- opts.clickhouseConfigs,
- opts.preferredClickhouseService,
- ).exec({
- query: queryWithFormat,
- query_params: opts.params,
- use_multipart_params_auto: opts.useMultipartParamsAuto,
- clickhouse_settings: {
- ...opts.clickhouseSettings,
- log_comment: JSON.stringify(normalizedTags),
- },
- }),
- )
- .catch((error) => {
- throw ClickHouseResourceError.wrapIfResourceError(
- enrichWithQueryId(error as Error, queryId),
- normalizedTags,
- );
- });
-
- queryId = res.query_id;
span.setAttribute("ch.queryId", queryId);
+
+ // Failures reject into the outer catch, which enriches with the query_id
+ // and wraps resource errors exactly once.
+ const res = await context.with(trace.setSpan(context.active(), span), () =>
+ clickhouseClient(
+ opts.clickhouseConfigs,
+ opts.preferredClickhouseService,
+ ).exec({
+ query: queryWithFormat,
+ query_params: opts.params,
+ use_multipart_params_auto: opts.useMultipartParamsAuto,
+ query_id: queryId,
+ clickhouse_settings: {
+ ...opts.clickhouseSettings,
+ log_comment: JSON.stringify(normalizedTags),
+ },
+ }),
+ );
for (const [key, value] of Object.entries(normalizedTags)) {
span.setAttribute(`ch.tag.${key}`, value);
}
@@ -475,8 +471,16 @@ export async function queryClickhouseExecRaw(
);
// The span outlives this function (it covers the consumer's read). Forward
- // source errors so the consumer sees them.
- res.stream.on("error", (error) => guardedStream.destroy(error));
+ // source errors (e.g. mid-transfer connection resets) so the consumer sees
+ // them, enriched like the other error paths of this function.
+ res.stream.on("error", (error) =>
+ guardedStream.destroy(
+ ClickHouseResourceError.wrapIfResourceError(
+ enrichWithQueryId(error, queryId),
+ normalizedTags,
+ ),
+ ),
+ );
// `.pipe()` only wires src→dest, so destroying guardedStream (e.g. the
// worker's pipeline aborting on an upload failure) would leave the live CH
// body streaming into an unread socket — pinning a connection slot and query
@@ -597,6 +601,7 @@ async function sendClickhouseQuery<F extends DataFormat>(opts: {
clickhouseSettings?: ClickHouseSettings;
format: F;
span: Span;
+ queryId?: string;
}) {
const normalizedTags = normalizeClickHouseQueryTags(opts.tags);
const res = await clickhouseClient(
@@ -607,6 +612,7 @@ async function sendClickhouseQuery<F extends DataFormat>(opts: {
format: opts.format,
query_params: opts.params,
use_multipart_params_auto: opts.useMultipartParamsAuto,
+ ...(opts.queryId ? { query_id: opts.queryId } : {}),
clickhouse_settings: {
...opts.clickhouseSettings,
log_comment: JSON.stringify(normalizedTags),
@@ -725,8 +731,13 @@ export async function* queryClickhouseWithProgress<T>(
kind: SpanKind.CLIENT,
});
+ // Client-generated so failures before/without a response still carry a
+ // query_id on errors and spans; system.query_log stays pollable by id.
+ const queryId = randomUUID();
+
try {
setSpanQueryAttributes(span, opts.query);
+ span.setAttribute("ch.queryId", queryId);
const res = await context
.with(trace.setSpan(context.active(), span), () =>
@@ -739,6 +750,7 @@ export async function* queryClickhouseWithProgress<T>(
},
format: "JSONEachRowWithProgress",
span,
+ queryId,
}),
)
.catch((error) => {
@@ -754,9 +766,18 @@ export async function* queryClickhouseWithProgress<T>(
}
}
} catch (error) {
- if (error instanceof ClickHouseResourceError) throw error;
+ if (error instanceof ClickHouseResourceError) {
+ const enriched = enrichWithQueryId(error, queryId);
+ throw enriched === error
+ ? error
+ : new ClickHouseResourceError(
+ error.errorType,
+ enriched,
+ normalizedTags,
+ );
+ }
throw ClickHouseResourceError.wrapIfResourceError(
- error as Error,
+ enrichWithQueryId(error as Error, queryId),
normalizedTags,
);
} finally {
diff --git a/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts
index 060bac321a..21e4b3dfd0 100644
--- a/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts
+++ b/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts
@@ -1,10 +1,16 @@
import {
queryClickhouse,
queryClickhouseStream,
+ queryClickhouseStreamRawText,
+ queryClickhouseExecRaw,
+ queryClickhouseWithProgress,
ClickHouseResourceError,
} from "@langfuse/shared/src/server";
import { fail } from "assert";
+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", () => {
@@ -133,6 +139,96 @@ describe("ClickHouse Resource Error Handling", () => {
expect(results[0]).toHaveProperty("number");
});
});
+
+ 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("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", () => {
diff --git a/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts b/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts
index ee5fef109d..aa5cb3fcb8 100644
--- a/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts
+++ b/worker/src/backgroundMigrations/backfillEventsFullFromDatasetRunItems.ts
@@ -570,7 +570,15 @@ export default class BackfillEventsFullFromDatasetRunItems implements IBackgroun
return predecessor;
}
- const tables = await clickhouseClient().query({ query: "SHOW TABLES" });
+ const tables = await clickhouseClient().query({
+ query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.backfillEventsFullFromDatasetRunItems",
+ }),
+ },
+ });
const tableNames = (await tables.json()).data as { name: string }[];
const requiredTables = [
diff --git a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts b/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts
index 90dafa8c88..a7c6db4bf7 100644
--- a/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts
+++ b/worker/src/backgroundMigrations/migrateDatasetRunItemsFromPostgresToClickhouseRmt.ts
@@ -1,5 +1,6 @@
import { IBackgroundMigration } from "./IBackgroundMigration";
import {
+ buildClickHouseLogComment,
clickhouseClient,
convertPostgresDatasetRunItemToInsert,
logger,
@@ -35,6 +36,13 @@ export default class MigrateDatasetRunItemsFromPostgresToClickhouseRmt implement
// Check if ClickHouse dataset_run_items_rmt table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route:
+ "background-migration.migrateDatasetRunItemsFromPostgresToClickhouseRmt",
+ }),
+ },
});
const tableNames = (await tables.json()).data as { name: string }[];
if (!tableNames.some((r) => r.name === "dataset_run_items_rmt")) {
@@ -162,6 +170,13 @@ export default class MigrateDatasetRunItemsFromPostgresToClickhouseRmt implement
table: "dataset_run_items_rmt",
values: datasetRunItems.map(convertPostgresDatasetRunItemToInsert),
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route:
+ "background-migration.migrateDatasetRunItemsFromPostgresToClickhouseRmt",
+ }),
+ },
});
logger.info(
diff --git a/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts b/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts
index 84187400f9..30ee276f35 100644
--- a/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts
+++ b/worker/src/backgroundMigrations/migrateEventLogToBlobStorageRefTable.ts
@@ -1,5 +1,6 @@
import { IBackgroundMigration } from "./IBackgroundMigration";
import {
+ buildClickHouseLogComment,
clickhouseClient,
findS3RefsByPrimaryKey,
getLastEventLogPrimaryKey,
@@ -42,6 +43,12 @@ export default class MigrateEventLogToBlobStorageRefTable implements IBackground
// Check if ClickHouse traces table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.migrateEventLogToBlobStorageRefTable",
+ }),
+ },
});
const tableNames = (await tables.json()).data as { name: string }[];
if (
diff --git a/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts
index e968ae9954..236fb3b238 100644
--- a/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts
+++ b/worker/src/backgroundMigrations/migrateObservationsFromPostgresToClickhouse.ts
@@ -1,5 +1,6 @@
import { IBackgroundMigration } from "./IBackgroundMigration";
import {
+ buildClickHouseLogComment,
clickhouseClient,
convertPostgresObservationToInsert,
logger,
@@ -70,6 +71,13 @@ export default class MigrateObservationsFromPostgresToClickhouse implements IBac
// Check if ClickHouse observations table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route:
+ "background-migration.migrateObservationsFromPostgresToClickhouse",
+ }),
+ },
});
const tableNames = (await tables.json()).data as { name: string }[];
if (!tableNames.some((r) => r.name === "observations")) {
@@ -143,6 +151,13 @@ export default class MigrateObservationsFromPostgresToClickhouse implements IBac
table: "observations",
values: observations.map(convertPostgresObservationToInsert),
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route:
+ "background-migration.migrateObservationsFromPostgresToClickhouse",
+ }),
+ },
});
logger.info(
diff --git a/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts
index b8a45f8421..2b60bfaab4 100644
--- a/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts
+++ b/worker/src/backgroundMigrations/migrateScoresFromPostgresToClickhouse.ts
@@ -1,5 +1,6 @@
import { IBackgroundMigration } from "./IBackgroundMigration";
import {
+ buildClickHouseLogComment,
clickhouseClient,
convertPostgresScoreToInsert,
logger,
@@ -35,6 +36,12 @@ export default class MigrateScoresFromPostgresToClickhouse implements IBackgroun
// Check if ClickHouse scores table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.migrateScoresFromPostgresToClickhouse",
+ }),
+ },
});
const tableNames = (await tables.json()).data as { name: string }[];
if (!tableNames.some((r) => r.name === "scores")) {
@@ -120,6 +127,12 @@ export default class MigrateScoresFromPostgresToClickhouse implements IBackgroun
table: "scores",
values: scores.map(convertPostgresScoreToInsert),
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.migrateScoresFromPostgresToClickhouse",
+ }),
+ },
});
logger.info(
diff --git a/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts b/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts
index 78edb23747..8b483d2bc1 100644
--- a/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts
+++ b/worker/src/backgroundMigrations/migrateTracesFromPostgresToClickhouse.ts
@@ -1,5 +1,6 @@
import { IBackgroundMigration } from "./IBackgroundMigration";
import {
+ buildClickHouseLogComment,
clickhouseClient,
convertPostgresTraceToInsert,
logger,
@@ -35,6 +36,12 @@ export default class MigrateTracesFromPostgresToClickhouse implements IBackgroun
// Check if ClickHouse traces table exists
const tables = await clickhouseClient().query({
query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.migrateTracesFromPostgresToClickhouse",
+ }),
+ },
});
const tableNames = (await tables.json()).data as { name: string }[];
if (!tableNames.some((r) => r.name === "traces")) {
@@ -120,6 +127,12 @@ export default class MigrateTracesFromPostgresToClickhouse implements IBackgroun
table: "traces",
values: traces.map(convertPostgresTraceToInsert),
format: "JSONEachRow",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: "background-migration.migrateTracesFromPostgresToClickhouse",
+ }),
+ },
});
logger.info(
diff --git a/worker/src/backgroundMigrations/utils/backfillBase.ts b/worker/src/backgroundMigrations/utils/backfillBase.ts
index 4560891823..4230fa9830 100644
--- a/worker/src/backgroundMigrations/utils/backfillBase.ts
+++ b/worker/src/backgroundMigrations/utils/backfillBase.ts
@@ -1,6 +1,7 @@
import { randomUUID } from "crypto";
import { parseArgs } from "node:util";
import {
+ buildClickHouseLogComment,
clickhouseClient,
commandClickhouse,
getQueryError,
@@ -570,7 +571,15 @@ export abstract class ChunkedClickhouseBackfillMigration<
}
private async findFirstMissingTable(): Promise<string | null> {
- const tables = await clickhouseClient().query({ query: "SHOW TABLES" });
+ const tables = await clickhouseClient().query({
+ query: "SHOW TABLES",
+ clickhouse_settings: {
+ log_comment: buildClickHouseLogComment({
+ surface: "worker",
+ route: `background-migration.${this.constructor.name}`,
+ }),
+ },
+ });
const tableNames = (await tables.json()).data as { name: string }[];
return (
this.requiredTables.find(