Skip to content

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

feat(worker): stream ClickHouse-native Parquet blob exports (LFE-10463) (#14509)

Niklas Semmlerb46923e6613c
diff --git a/packages/shared/package.json b/packages/shared/package.json
index b62eb5ad00..cbaca03563 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -104,6 +104,7 @@
"@aws-sdk/s3-request-presigner": "^3.1013.0",
"@azure/storage-blob": "^12.26.0",
"@clickhouse/client": "^1.18.5",
+ "@clickhouse/client-common": "^1.18.5",
"@google-cloud/storage": "^7.19.0",
"@langchain/anthropic": "^1.3.26",
"@langchain/aws": "^1.3.4",
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index 9df906aa46..31414857d9 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -1,9 +1,12 @@
+import { type Readable } from "stream";
import { env } from "../../env";
import {
clickhouseClient,
convertDateToClickhouseDateTime,
PreferredClickhouseService,
} from "../clickhouse/client";
+import { EXCEPTION_TAG_HEADER_NAME } from "@clickhouse/client-common";
+import { ClickhouseExecExceptionTagTransform } from "./clickhouseExecExceptionTag";
import { logger } from "../logger";
import { getTracer, instrumentAsync } from "../instrumentation";
import { randomUUID } from "crypto";
@@ -358,6 +361,124 @@ export async function* queryClickhouseStreamRawText(
}
}
+// Blob-export Parquet settings (LFE-10463). CH buffers a row group in memory and
+// flushes at whichever cap hits first. The bytes cap is the real memory governor
+// (auto-adapts to row width); set below CH's 512 MiB default since the dispatcher
+// exports up to 4 tables concurrently (peak ≈ 4×). The row cap bounds narrow tables.
+export const BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS: ClickHouseSettings = {
+ output_format_parquet_row_group_size: "1000000",
+ output_format_parquet_row_group_size_bytes: String(128 * 1024 * 1024), // 128 MiB
+};
+
+export type ClickhouseExecRawResult = {
+ queryId: string;
+ // Raw response body, already wrapped by the exception-tag Transform so a
+ // mid-stream failure (CH >= 25.11) errors it instead of truncating.
+ stream: Readable;
+ responseHeaders: Record<string, string | string[] | undefined>;
+};
+
+/**
+ * Raw binary read for the blob-export Parquet path (LFE-10463). Runs the query
+ * via `clickhouseClient().exec()` (returns the unparsed HTTP body as a
+ * {@link Readable}) and appends `FORMAT <format>` to the SQL — exec has no
+ * `format` param. Streams ClickHouse-native Parquet bytes straight to upload,
+ * offloading columnar encoding + compression to ClickHouse.
+ *
+ * `exec()` skips the ResultSet machinery and its mid-stream exception detection,
+ * so we restore it by piping through {@link ClickhouseExecExceptionTagTransform}
+ * — the stream errors on a failed query, aborting the upload before any commit.
+ * Detection needs CH >= 25.11 (exception-tag header); the only caller is an
+ * experimental per-project opt-in with the same caveat as raw passthrough — see
+ * RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION. Pass Parquet tuning via `clickhouseSettings`.
+ */
+export async function queryClickhouseExecRaw(
+ opts: ClickhouseQueryOpts & { format: string },
+): Promise<ClickhouseExecRawResult> {
+ if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);
+ const tracer = getTracer("clickhouse-query-exec-raw");
+ const span = tracer.startSpan("clickhouse-query-exec-raw", {
+ kind: SpanKind.CLIENT,
+ });
+
+ let queryId: string | undefined;
+
+ 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,
+ clickhouse_settings: {
+ ...opts.clickhouseSettings,
+ log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),
+ },
+ }),
+ )
+ .catch((error) => {
+ throw ClickHouseResourceError.wrapIfResourceError(
+ enrichWithQueryId(error as Error, queryId),
+ opts.tags,
+ );
+ });
+
+ queryId = res.query_id;
+ span.setAttribute("ch.queryId", queryId);
+ recordSummaryOnSpan(span, res.response_headers);
+
+ if (env.NODE_ENV === "development") {
+ logger.info(`clickhouse:exec ${res.query_id} ${queryWithFormat}`);
+ }
+
+ const exceptionTag = res.response_headers[EXCEPTION_TAG_HEADER_NAME] as
+ | string
+ | undefined;
+
+ const guardedStream = res.stream.pipe(
+ new ClickhouseExecExceptionTagTransform({
+ exceptionTag,
+ wrapError: (error) =>
+ ClickHouseResourceError.wrapIfResourceError(
+ enrichWithQueryId(error, queryId),
+ opts.tags,
+ ),
+ }),
+ );
+
+ // 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));
+ // `.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
+ // thread until the request timeout. 'close' fires on every termination path
+ // (end, error, no-arg destroy); span.end() is idempotent.
+ guardedStream.once("close", () => {
+ span.end();
+ if (!res.stream.destroyed) res.stream.destroy();
+ });
+
+ return {
+ queryId,
+ stream: guardedStream,
+ responseHeaders: res.response_headers,
+ };
+ } catch (error) {
+ span.end();
+ if (error instanceof ClickHouseResourceError) throw error;
+ throw ClickHouseResourceError.wrapIfResourceError(
+ enrichWithQueryId(error as Error, queryId),
+ opts.tags,
+ );
+ }
+}
+
function enrichWithQueryId(error: Error, queryId: string | undefined): Error {
if (!queryId) return error;
const enriched = new Error(`${error.message} [query_id: ${queryId}]`, {
diff --git a/packages/shared/src/server/repositories/clickhouseExecExceptionTag.test.ts b/packages/shared/src/server/repositories/clickhouseExecExceptionTag.test.ts
new file mode 100644
index 0000000000..6a4d478e3b
--- /dev/null
+++ b/packages/shared/src/server/repositories/clickhouseExecExceptionTag.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from "vitest";
+import { Readable, pipeline } from "stream";
+import { promisify } from "util";
+import {
+ ClickhouseExecExceptionTagTransform,
+ EXCEPTION_TRAILER_MARKER,
+} from "./clickhouseExecExceptionTag";
+
+const pipelineAsync = promisify(pipeline);
+
+// Build a valid ClickHouse >= 25.11 end-of-stream exception trailer for a given
+// tag + single-line message, matching the layout that the client's
+// extractErrorAtTheEndOfChunk parses:
+// `\r\n__exception__\r\n<tag>` <message> `\n<len> __exception__\r\n<tag>\r\n`
+// where <len> is the byte length of `<message>\n`. The leading marker is what
+// the Transform scans for; the trailing portion is what the parser reads.
+function buildExceptionTrailer(tag: string, message: string): Buffer {
+ const messageWithNewline = message + "\n";
+ const len = Buffer.byteLength(messageWithNewline, "utf-8");
+ return Buffer.concat([
+ Buffer.from(`\r\n__exception__\r\n${tag}`, "utf-8"),
+ Buffer.from(messageWithNewline, "utf-8"),
+ Buffer.from(`${len} __exception__\r\n${tag}\r\n`, "utf-8"),
+ ]);
+}
+
+async function collect(
+ chunks: Buffer[],
+ options: ConstructorParameters<typeof ClickhouseExecExceptionTagTransform>[0],
+): Promise<Buffer> {
+ const transform = new ClickhouseExecExceptionTagTransform(options);
+ const out: Buffer[] = [];
+ transform.on("data", (c: Buffer) => out.push(c));
+ await pipelineAsync(Readable.from(chunks), transform);
+ return Buffer.concat(out);
+}
+
+describe("ClickhouseExecExceptionTagTransform", () => {
+ const TAG = "FOOBAR";
+
+ it("passes clean binary data through unchanged when no marker is present", async () => {
+ const data = Buffer.from([0x50, 0x41, 0x52, 0x31, 0x00, 0xff, 0x0d, 0x0a]); // includes a stray \r\n
+ const result = await collect([data], { exceptionTag: TAG });
+ expect(result.equals(data)).toBe(true);
+ });
+
+ it("passes data through unchanged when detection is disabled (no exception tag)", async () => {
+ // A chunk that happens to contain the marker bytes must NOT be treated as an
+ // error when the tag header is absent (CH < 25.11): pure passthrough.
+ const data = Buffer.concat([
+ Buffer.from("real-parquet-bytes"),
+ EXCEPTION_TRAILER_MARKER,
+ Buffer.from("more"),
+ ]);
+ const result = await collect([data], { exceptionTag: undefined });
+ expect(result.equals(data)).toBe(true);
+ });
+
+ it("passes through the bare marker when NOT followed by the tag (adversarial footer bytes)", async () => {
+ // A Parquet footer min/max stat is uncompressed and can carry a raw user
+ // string starting with the literal 17-byte marker. Scanning for marker+tag
+ // (not the bare marker) means such input must pass through, not false-
+ // positive into a per-window export DoS. The per-query tag is unguessable.
+ const data = Buffer.concat([
+ Buffer.from("PAR1...row-group..."),
+ EXCEPTION_TRAILER_MARKER,
+ Buffer.from("attacker-suffix-not-the-real-tag"),
+ Buffer.from("...footer...PAR1"),
+ ]);
+ const result = await collect([data], { exceptionTag: "server-random-tag" });
+ expect(result.equals(data)).toBe(true);
+ });
+
+ it("errors the stream with the parsed message when the trailer is present", async () => {
+ const message = "Code: 241. DB::Exception: Memory limit exceeded";
+ const chunk = Buffer.concat([
+ Buffer.from("clean-data-before-error"),
+ buildExceptionTrailer(TAG, message),
+ ]);
+ await expect(collect([chunk], { exceptionTag: TAG })).rejects.toThrow(
+ /Memory limit exceeded/,
+ );
+ });
+
+ it("does not emit the trailer bytes downstream, only the clean prefix", async () => {
+ const prefix = Buffer.from("PAR1-clean-leading-bytes-PAR1");
+ const chunk = Buffer.concat([
+ prefix,
+ buildExceptionTrailer(TAG, "Code: 159. DB::Exception: Timeout exceeded"),
+ ]);
+
+ const transform = new ClickhouseExecExceptionTagTransform({
+ exceptionTag: TAG,
+ });
+ const out: Buffer[] = [];
+ transform.on("data", (c: Buffer) => out.push(c));
+ await expect(
+ pipelineAsync(Readable.from([chunk]), transform),
+ ).rejects.toThrow();
+ // Whatever was emitted before the error must be a prefix of the clean data,
+ // and must never include the marker.
+ const emitted = Buffer.concat(out);
+ expect(emitted.length).toBeLessThanOrEqual(prefix.length);
+ expect(prefix.subarray(0, emitted.length).equals(emitted)).toBe(true);
+ expect(emitted.indexOf(EXCEPTION_TRAILER_MARKER)).toBe(-1);
+ });
+
+ it("detects a marker split across chunk boundaries (1-byte chunks)", async () => {
+ const full = Buffer.concat([
+ Buffer.from("leading"),
+ buildExceptionTrailer(TAG, "Code: 241. DB::Exception: boundary split"),
+ ]);
+ const singleBytes = Array.from(full).map((b) => Buffer.from([b]));
+ await expect(collect(singleBytes, { exceptionTag: TAG })).rejects.toThrow(
+ /boundary split/,
+ );
+ });
+
+ it("preserves trailing data that resembles the marker prefix but is clean", async () => {
+ // Stream ends with the first 16 bytes of the marker but never completes it —
+ // must be flushed intact, not swallowed.
+ const partialMarker = EXCEPTION_TRAILER_MARKER.subarray(
+ 0,
+ EXCEPTION_TRAILER_MARKER.length - 1,
+ );
+ const data = Buffer.concat([Buffer.from("body"), partialMarker]);
+ const result = await collect([data], { exceptionTag: TAG });
+ expect(result.equals(data)).toBe(true);
+ });
+
+ it("applies wrapError to the emitted error", async () => {
+ class WrappedError extends Error {}
+ const chunk = buildExceptionTrailer(
+ TAG,
+ "Code: 241. DB::Exception: wrap me",
+ );
+ await expect(
+ collect([chunk], {
+ exceptionTag: TAG,
+ wrapError: (e) => new WrappedError(e.message),
+ }),
+ ).rejects.toBeInstanceOf(WrappedError);
+ });
+});
diff --git a/packages/shared/src/server/repositories/clickhouseExecExceptionTag.ts b/packages/shared/src/server/repositories/clickhouseExecExceptionTag.ts
new file mode 100644
index 0000000000..7128965de0
--- /dev/null
+++ b/packages/shared/src/server/repositories/clickhouseExecExceptionTag.ts
@@ -0,0 +1,124 @@
+// Replicates @clickhouse/client's mid-stream exception detection for the
+// `exec()` binary export path (LFE-10463 Parquet): exec() returns the raw body
+// with no scan, so a query failing after a 200 would truncate silently. On CH
+// >= 25.11 a failure appends `\r\n__exception__\r\n<tag>` … to the body. We scan
+// for marker+tag (not the bare marker): the literal prefix can occur in a
+// successful Parquet footer's uncompressed min/max stats (raw user strings), so
+// scanning the prefix alone lets an adversarial trace value false-positive every
+// export of a window — a per-window DoS. The per-query tag is unguessable.
+// Caveat (like rawPassthrough): pre-25.11 the tag header is absent → detection off.
+
+import { Transform } from "stream";
+import { extractErrorAtTheEndOfChunk } from "@clickhouse/client-common";
+
+// Literal prefix of the error trailer; the per-query tag is appended at runtime.
+export const EXCEPTION_TRAILER_MARKER = Buffer.from("\r\n__exception__\r\n");
+
+export interface ClickhouseExecExceptionTagTransformOptions {
+ // `x-clickhouse-exception-tag` response header; undefined pre-25.11 → detection off.
+ exceptionTag: string | undefined;
+ // Lets the caller classify the error (e.g. ClickHouseResourceError). Identity
+ // by default, keeping this module free of server-only imports and unit-testable.
+ wrapError?: (error: Error) => Error;
+}
+
+/**
+ * Passes `exec()` bytes through until the exception trailer appears, then errors
+ * the stream (aborting any downstream upload before commit). Withholds the last
+ * (scanMarker length - 1) bytes between chunks to catch a marker split across a
+ * boundary, flushing them on clean end. Memory is bounded — the stream is never
+ * fully buffered.
+ */
+export class ClickhouseExecExceptionTagTransform extends Transform {
+ private readonly exceptionTag: string | undefined;
+ private readonly wrapError: (error: Error) => Error;
+ // Full opening sequence we scan for: `\r\n__exception__\r\n` + the per-query tag.
+ private readonly scanMarker: Buffer;
+ // Bytes withheld between chunks so a scanMarker straddling a boundary is caught.
+ private readonly markerStraddleBytes: number;
+ // Tail of the previous chunk withheld to catch a marker spanning the boundary.
+ private pendingTail: Buffer = Buffer.alloc(0);
+ // Non-null once past the marker: downstream output stops and the trailer
+ // accumulates here for the final extractErrorAtTheEndOfChunk call.
+ private trailerBuffer: Buffer | null = null;
+
+ constructor(options: ClickhouseExecExceptionTagTransformOptions) {
+ super();
+ this.exceptionTag = options.exceptionTag;
+ this.wrapError = options.wrapError ?? ((error) => error);
+ this.scanMarker =
+ options.exceptionTag !== undefined
+ ? Buffer.concat([
+ EXCEPTION_TRAILER_MARKER,
+ Buffer.from(options.exceptionTag, "utf-8"),
+ ])
+ : EXCEPTION_TRAILER_MARKER;
+ this.markerStraddleBytes = this.scanMarker.length - 1;
+ }
+
+ _transform(
+ chunk: Buffer,
+ _encoding: BufferEncoding,
+ callback: (error?: Error | null, data?: Buffer) => void,
+ ): void {
+ // Detection off (pre-25.11): pure passthrough.
+ if (this.exceptionTag === undefined) {
+ callback(null, chunk);
+ return;
+ }
+
+ // Past the marker: accumulate the trailer, emit nothing.
+ if (this.trailerBuffer !== null) {
+ this.trailerBuffer = Buffer.concat([this.trailerBuffer, chunk]);
+ callback();
+ return;
+ }
+
+ const buf =
+ this.pendingTail.length > 0
+ ? Buffer.concat([this.pendingTail, chunk])
+ : chunk;
+ const trailerStart = buf.indexOf(this.scanMarker);
+
+ if (trailerStart !== -1) {
+ // Bytes before the marker are clean file data; the rest is the trailer.
+ if (trailerStart > 0) this.push(buf.subarray(0, trailerStart));
+ this.trailerBuffer = Buffer.from(buf.subarray(trailerStart));
+ callback();
+ return;
+ }
+
+ // No marker: emit everything but the tail that could start a split marker.
+ const keepFrom = buf.length - this.markerStraddleBytes;
+ if (keepFrom > 0) {
+ this.push(buf.subarray(0, keepFrom));
+ this.pendingTail = Buffer.from(buf.subarray(keepFrom));
+ } else {
+ this.pendingTail = Buffer.from(buf);
+ }
+ callback();
+ }
+
+ _flush(callback: (error?: Error | null, data?: Buffer) => void): void {
+ if (this.trailerBuffer !== null) {
+ // The marker was seen, so this is a real failure — never finish cleanly.
+ // extractErrorAtTheEndOfChunk can fail to parse a truncated trailer; a
+ // falsy return would collapse callback(error) into callback() and commit a
+ // corrupt Parquet artifact, so fall back to a generic error.
+ const parsed: Error | null | undefined = extractErrorAtTheEndOfChunk(
+ this.trailerBuffer,
+ this.exceptionTag as string,
+ );
+ const error =
+ parsed ??
+ new Error(
+ "ClickHouse mid-stream failure: exception trailer detected but could not be parsed",
+ );
+ callback(this.wrapError(error));
+ return;
+ }
+ // No error: flush the withheld tail so clean data is complete.
+ if (this.pendingTail.length > 0) this.push(this.pendingTail);
+ callback();
+ }
+}
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index cf103fd702..af9d618c25 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -81,6 +81,8 @@ import {
queryClickhouse,
queryClickhouseStream,
queryClickhouseStreamRawText,
+ queryClickhouseExecRaw,
+ BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
} from "./clickhouse";
import {
EventsObservationRecordReadType,
@@ -3592,6 +3594,29 @@ export const getEventsForBlobStorageExportRaw = function (
);
};
+// LFE-10463: FORMAT Parquet export — reuses the field-group-aware builder and
+// streams raw binary bytes to upload. No JS enrichment, so latency ms→s must run
+// in SQL (`convertLatencyToSeconds`) and price columns are NOT added.
+export const getEventsForBlobStorageExportParquet = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],
+ convertLatencyToSeconds = false,
+) {
+ return queryClickhouseExecRaw({
+ ...buildEventsForBlobStorageExportQuery(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ fieldGroups,
+ convertLatencyToSeconds,
+ ),
+ format: "Parquet",
+ clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+ });
+};
+
/**
* Streams events from ClickHouse for analytics integrations (PostHog, Mixpanel).
* Uses EventsQueryBuilder for consistent query construction.
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 1e9a6b403b..1f73bc3a42 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -4,6 +4,8 @@ import {
queryClickhouse,
queryClickhouseStream,
queryClickhouseStreamRawText,
+ queryClickhouseExecRaw,
+ BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
upsertClickhouse,
} from "./clickhouse";
import { logger } from "../logger";
@@ -1922,6 +1924,27 @@ export const getObservationsForBlobStorageExportRaw = function (
);
};
+// LFE-10463: FORMAT Parquet export — reuses the field-group-aware builder and
+// streams raw binary bytes to upload. Like raw passthrough, no JS enrichment, so
+// price columns are NOT added.
+export const getObservationsForBlobStorageExportParquet = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],
+) {
+ return queryClickhouseExecRaw({
+ ...buildObservationsForBlobStorageExportQuery(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ fieldGroups,
+ ),
+ format: "Parquet",
+ clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+ });
+};
+
export const getGenerationsForAnalyticsIntegrations = async function* (
projectId: string,
projectName: string,
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 7dfaa1d6b4..1d53662e7f 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -18,6 +18,8 @@ import {
commandClickhouse,
queryClickhouse,
queryClickhouseStream,
+ queryClickhouseExecRaw,
+ BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
upsertClickhouse,
parseClickhouseUTCDateTimeFormat,
clickhouseCompliantRandomCharacters,
@@ -2038,11 +2040,13 @@ export const getDistinctScoreNames = async (p: {
return rows.map((row) => row.name);
};
-export const getScoresForBlobStorageExport = function (
+// Shared query for both the standard (parsed) and Parquet (`exec` binary)
+// score export paths.
+const buildScoresForBlobStorageExportQuery = (
projectId: string,
minTimestamp: Date,
maxTimestamp: Date,
-) {
+) => {
const query = `
SELECT
id,
@@ -2068,7 +2072,7 @@ export const getScoresForBlobStorageExport = function (
AND data_type IN ({dataTypes: Array(String)})
`;
- const records = queryClickhouseStream<Record<string, unknown>>({
+ return {
query,
params: {
projectId,
@@ -2085,9 +2089,35 @@ export const getScoresForBlobStorageExport = function (
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
},
- });
+ };
+};
- return records;
+export const getScoresForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ return queryClickhouseStream<Record<string, unknown>>(
+ buildScoresForBlobStorageExportQuery(projectId, minTimestamp, maxTimestamp),
+ );
+};
+
+// LFE-10463: ClickHouse-native `FORMAT Parquet` export of scores. Reuses the
+// standard query SQL and streams the raw binary body straight to upload.
+export const getScoresForBlobStorageExportParquet = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ return queryClickhouseExecRaw({
+ ...buildScoresForBlobStorageExportQuery(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ ),
+ format: "Parquet",
+ clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+ });
};
export const getScoresForAnalyticsIntegrations = async function* (
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 67b225e43f..4b13a001f6 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -3,6 +3,8 @@ import {
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
queryClickhouseStream,
+ queryClickhouseExecRaw,
+ BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
upsertClickhouse,
} from "./clickhouse";
import {
@@ -1393,11 +1395,13 @@ export const getUserMetrics = async (
});
};
-export const getTracesForBlobStorageExport = function (
+// Shared query for both the standard (parsed) and Parquet (`exec` binary)
+// trace export paths, so the SELECT/WHERE stays in one place.
+const buildTracesForBlobStorageExportQuery = (
projectId: string,
minTimestamp: Date,
maxTimestamp: Date,
-) {
+) => {
const traceTable = "traces";
const query = `
@@ -1425,7 +1429,7 @@ export const getTracesForBlobStorageExport = function (
AND timestamp <= {maxTimestamp: DateTime64(3)}
`;
- return queryClickhouseStream<Record<string, unknown>>({
+ return {
query,
params: {
projectId,
@@ -1441,6 +1445,34 @@ export const getTracesForBlobStorageExport = function (
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
},
+ };
+};
+
+export const getTracesForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ return queryClickhouseStream<Record<string, unknown>>(
+ buildTracesForBlobStorageExportQuery(projectId, minTimestamp, maxTimestamp),
+ );
+};
+
+// LFE-10463: FORMAT Parquet export — reuses the standard SQL, streams raw binary
+// bytes to upload (no JS parse/enrich/serialize) via queryClickhouseExecRaw.
+export const getTracesForBlobStorageExportParquet = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ return queryClickhouseExecRaw({
+ ...buildTracesForBlobStorageExportQuery(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ ),
+ format: "Parquet",
+ clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
});
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b62701222d..7deff1c24d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -69,7 +69,7 @@ importers:
next-auth:
specifier: ^4.24.13
- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
zod:
specifier: 4.3.6
version: 4.3.6
@@ -193,6 +193,9 @@ importers:
'@clickhouse/client':
specifier: ^1.18.5
version: 1.18.5
+ '@clickhouse/client-common':
+ specifier: ^1.18.5
+ version: 1.18.5
'@google-cloud/storage':
specifier: ^7.19.0
version: 7.19.0
@@ -201,7 +204,7 @@ importers:
version: 1.3.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@langchain/aws':
specifier: ^1.3.4
- version: 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ version: 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))
'@langchain/core':
specifier: ^1.1.48
version: 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
@@ -210,7 +213,7 @@ importers:
version: 0.1.11(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@langchain/openai':
specifier: ^1.4.2
+ version: 1.4.2(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))([email protected])
'@opentelemetry/api':
specifier: '>=1.0.0 <1.10.0'
version: 1.9.1
@@ -288,7 +291,7 @@ importers:
version: 11.2.7
next-auth:
specifier: ^4.24.13
- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
nodemailer:
specifier: ^7.0.11
version: 7.0.13
@@ -700,7 +703,7 @@ importers:
next-auth:
specifier: ^4.24.13
- version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
+ version: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
next-query-params:
specifier: ^5.1.0
@@ -12797,9 +12800,9 @@ snapshots:
zod: 4.3.6
optionalDependencies:
- '@langchain/aws': 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/aws': 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))
'@langchain/langgraph-sdk': 1.9.10(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))([email protected]([email protected]))([email protected])
- '@langchain/openai': 1.4.2(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))([email protected])
+ '@langchain/openai': 1.4.2(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))([email protected])
transitivePeerDependencies:
- '@ag-ui/encoder'
@@ -13622,7 +13625,7 @@ snapshots:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
zod: 4.3.6
+ '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))':
dependencies:
'@aws-sdk/client-bedrock-agent-runtime': 3.1024.0
'@aws-sdk/client-bedrock-runtime': 3.1013.0
@@ -13657,12 +13660,12 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))':
dependencies:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
uuid: 10.0.0
dependencies:
'@types/json-schema': 7.0.15
p-queue: 9.3.0
@@ -13685,11 +13688,11 @@ snapshots:
react: 19.2.4
react-dom: 19.2.4([email protected])
dependencies:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))
+ '@langchain/langgraph-sdk': 1.8.7(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))([email protected]([email protected]))([email protected])
'@standard-schema/spec': 1.1.0
uuid: 10.0.0
zod: 4.3.6
@@ -13701,7 +13704,7 @@ snapshots:
- svelte
- vue
+ '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))([email protected])':
dependencies:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
js-tiktoken: 1.0.21
@@ -13933,7 +13936,7 @@ snapshots:
dependencies:
- next-auth: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
+ next-auth: 4.24.13(patch_hash=7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66)([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])
'@next/[email protected]': {}
@@ -18584,7 +18587,7 @@ snapshots:
tinyglobby: 0.2.16
unrs-resolver: 1.11.1
optionalDependencies:
- eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
@@ -20067,8 +20070,8 @@ snapshots:
dependencies:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]))
langsmith: 0.7.1(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
uuid: 11.1.1
zod: 4.3.6
@@ -20820,7 +20823,7 @@ snapshots:
dependencies:
type-fest: 2.19.0
dependencies:
'@babel/runtime': 7.29.2
'@panva/hkdf': 1.2.1
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index 2fb7668c7d..6c74db32eb 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -1744,4 +1744,119 @@ describe("BlobStorageIntegrationProcessingJob", () => {
expect(content).toContain("CSV Fallback Event");
}, 30_000);
});
+
+ maybeDescribe("Parquet export (LFE-10463)", () => {
+ // E2e: exportTuning.parquet runs the real handler → MinIO. Parquet magic is
+ // ASCII, so it survives the string download at both ends of the body.
+ const PARQUET_MAGIC = "PAR1";
+
+ it("exports valid .parquet files for all tables, ignoring compressed, and survives an adversarial trace name", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ s3Prefix = projectId;
+ const now = new Date();
+ const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
+ const dataTime = now.getTime() - 90 * 60 * 1000;
+ const traceId = randomUUID();
+ const adversarialTraceId = randomUUID();
+ const observationId = randomUUID();
+ const scoreId = randomUUID();
+ const eventId = randomUUID();
+
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: s3Prefix,
+ accessKeyId: minioAccessKeyId,
+ secretAccessKey: encrypt(minioAccessKeySecret),
+ region: region ? region : "auto",
+ endpoint: minioEndpoint,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ exportSource: "TRACES_OBSERVATIONS_EVENTS",
+ nextSyncAt: twoHoursAgo,
+ lastSyncAt: twoHoursAgo,
+ // compressed must be ignored on the parquet path (no .gz suffix).
+ compressed: true,
+ fileType: BlobStorageIntegrationFileType.JSONL,
+ exportTuning: { parquet: true },
+ },
+ });
+
+ await Promise.all([
+ createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: dataTime,
+ name: "Parquet Trace",
+ }),
+ // Name starting with the exception marker lands in the uncompressed
+ // footer min-stat; the per-query-tag scan must not false-positive
+ // (footer-DoS regression — export must still succeed).
+ createTrace({
+ id: adversarialTraceId,
+ project_id: projectId,
+ timestamp: dataTime,
+ name: "\r\n__exception__\r\n adversarial",
+ }),
+ ]),
+ createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: dataTime,
+ end_time: dataTime + 5000,
+ name: "Parquet Observation",
+ }),
+ ]),
+ createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ trace_id: traceId,
+ project_id: projectId,
+ timestamp: dataTime,
+ name: "Parquet Score",
+ value: 0.5,
+ }),
+ ]),
+ createEventsCh([
+ createEvent({
+ id: eventId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "Parquet Event",
+ start_time: dataTime * 1000,
+ end_time: (dataTime + 5000) * 1000,
+ }),
+ ]),
+ ]);
+
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ const files = await s3StorageService.listFiles(s3Prefix);
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
+
+ // traces, observations, scores, observations_v2 (events).
+ expect(projectFiles).toHaveLength(4);
+ for (const f of projectFiles) {
+ expect(f.file.endsWith(".parquet")).toBe(true);
+ expect(f.file).not.toContain(".gz");
+ }
+
+ // Every object is a valid Parquet file (magic at both ends).
+ for (const f of projectFiles) {
+ const content = await s3StorageService.download(f.file);
+ expect(content.startsWith(PARQUET_MAGIC)).toBe(true);
+ expect(content.endsWith(PARQUET_MAGIC)).toBe(true);
+ }
+ }, 30_000);
+ });
});
diff --git a/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts b/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts
index 2055a0ede3..eb65c856f2 100644
--- a/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts
+++ b/worker/src/__tests__/blobStorageTuningWiring.unit.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
+import { Readable } from "stream";
// Records of every uploadFileBuffered call so we can assert the resolved tuning
// was threaded through. Hoisted so the module mock can close over it.
@@ -39,6 +40,28 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
getObservationsForBlobStorageExport: () => empty(),
getScoresForBlobStorageExport: () => empty(),
getEventsForBlobStorageExport: () => empty(),
+ // LFE-10463 Parquet path: each returns an already-resolved
+ // { stream } (the binary body) — a tiny Readable with the Parquet magic.
+ getTracesForBlobStorageExportParquet: async () => ({
+ queryId: "q",
+ stream: Readable.from([Buffer.from("PAR1")]),
+ responseHeaders: {},
+ }),
+ getScoresForBlobStorageExportParquet: async () => ({
+ queryId: "q",
+ stream: Readable.from([Buffer.from("PAR1")]),
+ responseHeaders: {},
+ }),
+ getObservationsForBlobStorageExportParquet: async () => ({
+ queryId: "q",
+ stream: Readable.from([Buffer.from("PAR1")]),
+ responseHeaders: {},
+ }),
+ getEventsForBlobStorageExportParquet: async () => ({
+ queryId: "q",
+ stream: Readable.from([Buffer.from("PAR1")]),
+ responseHeaders: {},
+ }),
createModelCache: () => ({ getModel: async () => null }),
blobStorageEndpointConnectionValidationOptions: () => undefined,
};
@@ -129,4 +152,54 @@ describe("handleBlobStorageIntegrationProjectJob tuning wiring", () => {
expect(call.maxPartAttempts).toBeUndefined();
}
});
+
+ // LFE-10463: parquet tuning routes every table through the Parquet path,
+ // overriding fileType (CSV here) and the .gz suffix.
+ it("produces .parquet files with the parquet content type when parquet is enabled", async () => {
+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue(
+ baseRow({ parquet: true }),
+ );
+
+ await handleBlobStorageIntegrationProjectJob(makeJob());
+
+ // exportSource TRACES_OBSERVATIONS → scores, traces, observations.
+ expect(uploadCalls.length).toBe(3);
+ for (const call of uploadCalls) {
+ expect(call.fileName.endsWith(".parquet")).toBe(true);
+ expect(call.fileName.endsWith(".gz")).toBe(false);
+ expect(call.fileType).toBe("application/vnd.apache.parquet");
+ }
+ });
+
+ it("ignores the compressed flag on the parquet path (no .gz suffix)", async () => {
+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue({
+ ...baseRow({ parquet: true }),
+ compressed: true,
+ fileType: "JSONL",
+ });
+
+ await handleBlobStorageIntegrationProjectJob(makeJob());
+
+ expect(uploadCalls.length).toBe(3);
+ for (const call of uploadCalls) {
+ expect(call.fileName.endsWith(".parquet")).toBe(true);
+ expect(call.fileName).not.toContain(".gz");
+ expect(call.fileType).toBe("application/vnd.apache.parquet");
+ }
+ });
+
+ it("parquet takes precedence over rawPassthrough", async () => {
+ (prisma.blobStorageIntegration.findUnique as any).mockResolvedValue({
+ ...baseRow({ parquet: true, rawPassthrough: true }),
+ fileType: "JSONL",
+ });
+
+ await handleBlobStorageIntegrationProjectJob(makeJob());
+
+ expect(uploadCalls.length).toBe(3);
+ for (const call of uploadCalls) {
+ expect(call.fileName.endsWith(".parquet")).toBe(true);
+ expect(call.fileType).toBe("application/vnd.apache.parquet");
+ }
+ });
});
diff --git a/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts b/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts
new file mode 100644
index 0000000000..8c5b3f5f4c
--- /dev/null
+++ b/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect } from "vitest";
+import {
+ queryClickhouseExecRaw,
+ BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+} from "@langfuse/shared/src/server";
+
+// Integration tests for the FORMAT Parquet exec path against a live ClickHouse.
+// Lives in worker (not shared) because the shared test job runs without a
+// ClickHouse service — these need a real server. Validates valid Parquet bytes
+// on success and a hard error (not a silent/truncated success) on failure.
+// Mid-stream exception-tag parsing is unit-tested separately in shared
+// (clickhouseExecExceptionTag.test.ts) and does not depend on CH version here.
+
+const PARQUET_MAGIC = Buffer.from("PAR1");
+
+async function collect(stream: NodeJS.ReadableStream): Promise<Buffer> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) {
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return Buffer.concat(chunks);
+}
+
+describe("queryClickhouseExecRaw — FORMAT Parquet", () => {
+ it("streams valid Parquet bytes (PAR1 magic at both ends)", async () => {
+ const { stream } = await queryClickhouseExecRaw({
+ query: "SELECT number AS n FROM numbers(1000)",
+ format: "Parquet",
+ clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+ tags: { feature: "test", kind: "analytic" },
+ });
+
+ const buffer = await collect(stream);
+
+ expect(buffer.length).toBeGreaterThan(8);
+ expect(buffer.subarray(0, 4).equals(PARQUET_MAGIC)).toBe(true);
+ expect(buffer.subarray(buffer.length - 4).equals(PARQUET_MAGIC)).toBe(true);
+ });
+
+ it("surfaces a failing query as an error instead of a silent/truncated success", async () => {
+ // A query that throwIf-fails must never yield a clean stream. The error
+ // surfaces either as a pre-200 exec() rejection or, once 200 has been sent,
+ // via the end-of-stream exception-tag trailer the Transform scans for (CH
+ // >= 25.11). Both are acceptable — the invariant is that the failure is
+ // never swallowed. (Trailer parsing is unit-tested with synthetic chunks in
+ // shared's clickhouseExecExceptionTag.test.ts.)
+ const run = async () => {
+ const { stream } = await queryClickhouseExecRaw({
+ query:
+ "SELECT throwIf(number = 5000, 'mid-stream boom') AS n FROM numbers(100000)",
+ format: "Parquet",
+ clickhouseSettings: {
+ ...BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
+ output_format_parquet_row_group_size: "256",
+ },
+ tags: { feature: "test", kind: "analytic" },
+ });
+ return collect(stream);
+ };
+
+ await expect(run()).rejects.toThrow(/boom/);
+ });
+});
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index e73a84eca0..1e6d832ebf 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -11,10 +11,14 @@ import {
streamTransformations,
getObservationsForBlobStorageExport,
getObservationsForBlobStorageExportRaw,
+ getObservationsForBlobStorageExportParquet,
getTracesForBlobStorageExport,
+ getTracesForBlobStorageExportParquet,
getScoresForBlobStorageExport,
+ getScoresForBlobStorageExportParquet,
getEventsForBlobStorageExport,
getEventsForBlobStorageExportRaw,
+ getEventsForBlobStorageExportParquet,
getCurrentSpan,
instrumentAsync,
recordGauge,
@@ -63,6 +67,9 @@ export const BlobExportFormat = {
CSV_GZIP: "csv-gzip",
JSONL_RAW: "jsonl-raw",
JSONL_GZIP: "jsonl-gzip",
+ // LFE-10463: ClickHouse-native columnar export; compression is internal to
+ // Parquet, so there is no separate raw/gzip split.
+ PARQUET: "parquet",
} as const;
export type BlobExportFormat =
(typeof BlobExportFormat)[keyof typeof BlobExportFormat];
@@ -273,6 +280,32 @@ class ByteCounter extends Transform {
}
}
+// ByteCounter that also tallies inter-chunk gaps into `stats.sourceWaitMs`, so
+// the Parquet path (piped binary stream, no per-row generator) reuses the
+// standard chReadMs/uploadWaitMs derivation. Coarse: source wait conflates CH
+// delivery with S3 backpressure (same as countedStream).
+class TimedByteCounter extends ByteCounter {
+ private readonly stats: { sourceWaitMs: number };
+ // Clock starts at construction (like countedStream, before its loop) so the
+ // first gap captures time-to-first-byte — the dominant CH wait, since Parquet
+ // composes a row group before any bytes. Guarding it would drop TTFB from chReadMs.
+ private lastChunkDoneAt: number = performance.now();
+ constructor(stats: { sourceWaitMs: number }) {
+ super();
+ this.stats = stats;
+ }
+ _transform(
+ chunk: Buffer,
+ _encoding: string,
+ callback: (error: Error | null, data?: Buffer) => void,
+ ) {
+ this.stats.sourceWaitMs += performance.now() - this.lastChunkDoneAt;
+ this.bytes += chunk.length;
+ this.lastChunkDoneAt = performance.now();
+ callback(null, chunk);
+ }
+}
+
async function* countedStream<T>(
source: AsyncGenerator<T>,
stats: { rows: number; sourceWaitMs: number },
@@ -318,6 +351,9 @@ const processBlobStorageExport = async (config: {
convertV4LatencyToSeconds: boolean;
exportFieldGroups?: ObservationFieldGroupFull[];
rawPassthrough: boolean;
+ // LFE-10463: when true, export via ClickHouse-native `FORMAT Parquet`,
+ // overriding `fileType` and `compressed`. Takes precedence over rawPassthrough.
+ parquet: boolean;
// undefined concurrency/attempts => backend keeps its native default.
partSizeBytes: number;
maxConcurrentParts: number | undefined;
@@ -419,22 +455,12 @@ const processBlobStorageExport = async (config: {
try {
const blobStorageProps = getFileTypeProperties(config.fileType);
- const timestamp = config.maxTimestamp
- .toISOString()
- .replace(/:/g, "-")
- .substring(0, 19);
- const extension = config.compressed
- ? `${blobStorageProps.extension}.gz`
- : blobStorageProps.extension;
- const filePath = `${config.prefix ?? ""}${config.projectId}/${config.table}/${timestamp}.${extension}`;
- const uploadContentType = config.compressed
- ? "application/gzip"
- : blobStorageProps.contentType;
-
- const exportFieldGroups =
- config.exportFieldGroups && config.exportFieldGroups.length > 0
- ? config.exportFieldGroups
- : [...OBSERVATION_FIELD_GROUPS_FULL];
+ // LFE-10463: per-project opt-in spanning all tables/file types. Overrides
+ // fileType and compressed (Parquet compresses internally) and outranks
+ // rawPassthrough (enforced in resolveBlobExportTuning). It isn't a
+ // BlobStorageIntegrationFileType member, so extension/content-type are set
+ // inline below rather than via getFileTypeProperties.
+ const parquetEligible = config.parquet;
// Raw passthrough (LFE-10402) is opt-in per project and only valid for
// JSONL output of the enriched-observation tables — the only formats
@@ -444,15 +470,43 @@ const processBlobStorageExport = async (config: {
// select the path per table (scores/traces always use the standard path,
// so per-table fallback is expected and not worth a warning).
const passthroughEligible =
+ !parquetEligible &&
config.rawPassthrough &&
config.fileType === BlobStorageIntegrationFileType.JSONL &&
(config.table === "observations" ||
config.table === "observations_v2");
- span.setAttribute(
- "blob.path",
- passthroughEligible ? "passthrough" : "standard",
- );
+ const exportPath = parquetEligible
+ ? "parquet"
+ : passthroughEligible
+ ? "passthrough"
+ : "standard";
+
+ const timestamp = config.maxTimestamp
+ .toISOString()
+ .replace(/:/g, "-")
+ .substring(0, 19);
+ // Parquet: fixed `.parquet` extension (no `.gz`) and Parquet content type.
+ const extension = parquetEligible
+ ? "parquet"
+ : config.compressed
+ ? `${blobStorageProps.extension}.gz`
+ : blobStorageProps.extension;
+ const filePath = `${config.prefix ?? ""}${config.projectId}/${config.table}/${timestamp}.${extension}`;
+ const uploadContentType = parquetEligible
+ ? "application/vnd.apache.parquet"
+ : config.compressed
+ ? "application/gzip"
+ : blobStorageProps.contentType;
+
+ const exportFieldGroups =
+ config.exportFieldGroups && config.exportFieldGroups.length > 0
+ ? config.exportFieldGroups
+ : [...OBSERVATION_FIELD_GROUPS_FULL];
+
+ // blob.path already encodes parquet (no per-table fallback), so no
+ // separate blob.config.parquet attribute is needed.
+ span.setAttribute("blob.path", exportPath);
const pipelineCallback = (err: NodeJS.ErrnoException | null) => {
if (err) {
@@ -463,8 +517,23 @@ const processBlobStorageExport = async (config: {
}
};
- const serializedCounter = new ByteCounter();
- const compressedCounter = config.compressed ? new ByteCounter() : null;
+ // Tracks ClickHouse read wait. Declared before the counters so the
+ // parquet TimedByteCounter can write into it (the parquet path has no
+ // per-row generator, so countedStream does not run).
+ const sourceStats = { rows: 0, sourceWaitMs: 0 };
+ // When enrichment is active, chStats isolates ClickHouse read wait from
+ // enrichment CPU. enrichMs = sourceStats.sourceWaitMs - chStats.sourceWaitMs.
+ let chStats: { rows: number; sourceWaitMs: number } | null = null;
+
+ // Parquet feeds sourceStats.sourceWaitMs from the piped binary stream so
+ // the shared metrics derivation works without a per-row generator.
+ const serializedCounter = parquetEligible
+ ? new TimedByteCounter(sourceStats)
+ : new ByteCounter();
+ // No worker-side gzip on the parquet path (compression is internal to
+ // Parquet), so the parquet path never allocates a compressed counter.
+ const compressedCounter =
+ !parquetEligible && config.compressed ? new ByteCounter() : null;
// Paired with compressedCounter: both exist iff compression is on.
const gzipStats: GzipStats | null = compressedCounter
? {
@@ -474,13 +543,6 @@ const processBlobStorageExport = async (config: {
}
: null;
- // Both paths tally rows in JS via countedStream (the passthrough yields
- // raw row text rather than parsed objects, but still iterates).
- const sourceStats = { rows: 0, sourceWaitMs: 0 };
- // When enrichment is active, chStats isolates ClickHouse read wait from
- // enrichment CPU. enrichMs = sourceStats.sourceWaitMs - chStats.sourceWaitMs.
- let chStats: { rows: number; sourceWaitMs: number } | null = null;
-
const HEARTBEAT_INTERVAL_MS = 5 * 60 * 1000;
const heartbeatTags = {
table: config.table,
@@ -501,7 +563,64 @@ const processBlobStorageExport = async (config: {
let fileStream: Readable;
- if (passthroughEligible) {
+ if (parquetEligible) {
+ // LFE-10463: stream raw FORMAT Parquet bytes straight to upload — no JS
+ // parse/enrich/serialize, no gzip, no row counting (binary has no row
+ // boundaries, so sourceStats.rows stays 0). Field-group projection,
+ // latency ms→s, and dropped price columns are baked into the SQL. The
+ // exception-tag Transform in queryClickhouseExecRaw aborts the upload
+ // before commit on a mid-stream failure — same guarantee as passthrough.
+ let parquetSource: Readable;
+ switch (config.table) {
+ case "traces":
+ parquetSource = (
+ await getTracesForBlobStorageExportParquet(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ )
+ ).stream;
+ break;
+ case "scores":
+ parquetSource = (
+ await getScoresForBlobStorageExportParquet(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ )
+ ).stream;
+ break;
+ case "observations":
+ parquetSource = (
+ await getObservationsForBlobStorageExportParquet(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ exportFieldGroups,
+ )
+ ).stream;
+ break;
+ case "observations_v2": // observations_v2 is the events table
+ parquetSource = (
+ await getEventsForBlobStorageExportParquet(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ exportFieldGroups,
+ config.convertV4LatencyToSeconds,
+ )
+ ).stream;
+ break;
+ default:
+ throw new Error(`Unsupported table type: ${config.table}`);
+ }
+
+ fileStream = pipeline(
+ parquetSource,
+ serializedCounter,
+ pipelineCallback,
+ );
+ } else if (passthroughEligible) {
// Stream ClickHouse JSONEachRow row text straight through: skip the
// per-row JSON.parse, enrichment, and re-serialize. Shaping (latency→s,
// dropped price columns, field-group selection) is baked into the SQL.
@@ -663,14 +782,13 @@ const processBlobStorageExport = async (config: {
projectId: config.projectId,
});
- const exportFormat = resolveBlobExportFormat(
- config.fileType,
- config.compressed,
- );
+ const exportFormat = parquetEligible
+ ? BlobExportFormat.PARQUET
+ : resolveBlobExportFormat(config.fileType, config.compressed);
const byteTags = {
table: config.table,
projectId: config.projectId,
- path: passthroughEligible ? "passthrough" : "standard",
+ path: exportPath,
source: exportFormat,
// Integration type (S3 / S3_COMPATIBLE / AZURE_BLOB_STORAGE) as the
// destination, so export volume can be split by data-transfer cost
@@ -713,7 +831,7 @@ const processBlobStorageExport = async (config: {
logger.info(
`[BLOB INTEGRATION] Successfully exported ${config.table} for project ${config.projectId}: ` +
`jobId=${config.bullmqJobId} attemptsMade=${config.bullmqAttemptsMade} host=${WORKER_HOST_ID} ` +
- `path=${passthroughEligible ? "passthrough" : "standard"} ` +
+ `path=${exportPath} ` +
`rows=${sourceStats.rows} chReadMs=${chReadMs} enrichMs=${enrichMs} ` +
`gzipCpuMs=${gzipCpuMs} uploadWaitMs=${uploadWaitMs} ` +
`serializedBytes=${serializedCounter.bytes} uploadDurationMs=${uploadDurationMs} ` +
@@ -759,13 +877,12 @@ const processBlobStorageExport = async (config: {
: Math.max(0, totalUploadMs - finalChReadMs - finalEnrichMs);
span.setAttribute("blob.gzipCpuMs", finalGzipCpuMs);
span.setAttribute("blob.uploadWaitMs", finalUploadWaitMs);
- const finalExportFormat = resolveBlobExportFormat(
- config.fileType,
- config.compressed,
- );
+ const finalExportFormat = parquetEligible
+ ? BlobExportFormat.PARQUET
+ : resolveBlobExportFormat(config.fileType, config.compressed);
const stageTags = {
table: config.table,
- path: passthroughEligible ? "passthrough" : "standard",
+ path: exportPath,
source: finalExportFormat,
};
recordHistogram(
@@ -823,7 +940,7 @@ const processBlobStorageExport = async (config: {
const metricTags = {
table: config.table,
- path: passthroughEligible ? "passthrough" : "standard",
+ path: exportPath,
gzipLevel: gzipStats.level,
};
recordHistogram(
@@ -1055,6 +1172,7 @@ export const handleBlobStorageIntegrationProjectJob = async (
exportFieldGroups:
blobStorageIntegration.exportFieldGroups as ObservationFieldGroupFull[],
rawPassthrough: exportTuning.rawPassthrough,
+ parquet: exportTuning.parquet,
partSizeBytes: exportTuning.partSizeBytes,
maxConcurrentParts: exportTuning.maxConcurrentParts,
maxPartAttempts: exportTuning.maxPartAttempts,