🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(worker): blob passthrough via row-text stream, drop query_log verification (LFE-10402) (#14425)
Niklas Semmler32f95faa21d2
diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.tsindex 9498143c68..e6b2e9d9f1 100644--- a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts@@ -12,11 +12,25 @@// writer is harmless to an older worker.import { z } from "zod";+// Minimum ClickHouse version for safe raw passthrough. The passthrough relies on+// ClickHouse's mid-stream exception tagging (the `x-clickhouse-exception-tag`+// response header + end-of-stream marker) so the client errors the stream when a+// query fails after a 200 response. That mechanism only exists in ClickHouse+// >= 25.11. On older servers a query that fails mid-stream is NOT detected and+// the passthrough can silently upload a truncated/garbage object — so operators+// MUST NOT enable `rawPassthrough` on self-hosted ClickHouse below this version.+// Langfuse Cloud runs a newer ClickHouse, so this only affects self-hosters.+export const RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION = "25.11";+export const BlobExportTuningSchema = z.object({- // LFE-10402 raw-passthrough export path: stream ClickHouse JSONEachRow bytes+ // LFE-10402 raw-passthrough export path: stream ClickHouse JSONEachRow row text// straight to gzip → upload, skipping the per-row JS parse/enrich/serialize// pipeline. Only honored for JSONL exports of the observations / events// tables; ignored (with a warning) otherwise. Drops the model price columns.+ //+ // EXPERIMENTAL + self-hosting caveat: requires ClickHouse+ // >= RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION (see above) for mid-stream failure+ // detection. Do not enable on older self-hosted ClickHouse.rawPassthrough: z.boolean().optional(),});diff --git a/packages/shared/src/server/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.tsindex e55448f6ad..8a5fcb4269 100644--- a/packages/shared/src/server/clickhouse/queryTracking.ts+++ b/packages/shared/src/server/clickhouse/queryTracking.ts@@ -1,6 +1,5 @@import { env } from "../../env";import { queryClickhouse } from "../repositories";-import { convertDateToClickhouseDateTime } from "./client";// ============================================================================// Types@@ -16,24 +15,6 @@ export function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}-/**- * system.query_log is partitioned by `toYYYYMM(event_date)`. Filtering only by- * query_id forces a scan of every retained partition (fanned across replicas on- * clusters). When the caller knows roughly when the query was issued, bound- * `event_date` so the planner can partition-prune. `since` should already- * include a safety margin for worker/ClickHouse clock skew.- */-function queryLogSinceBound(since: Date | undefined): {- clause: string;- params: Record<string, string>;-} {- if (!since) return { clause: "", params: {} };- return {- clause: "AND event_date >= toDate({since: DateTime64(6)})",- params: { since: convertDateToClickhouseDateTime(since) },- };-}-/*** Builds a system-table reference, optionally wrapped in clusterAllReplicas* when CH is deployed as a cluster. Single-node deployments (self-hosted) read@@ -59,7 +40,6 @@ function systemTableRef(export async function pollQueryStatus(queryId: string,tags?: Record<string, string>,- since?: Date,): Promise<QueryStatus> {const tagsWithDefaults = {feature: "query-tracking",@@ -88,7 +68,6 @@ export async function pollQueryStatus(return "running";}// Check query_log for completion status- const sinceBound = queryLogSinceBound(since);const result = await queryClickhouse<{type: string;exception_code: string;@@ -97,11 +76,10 @@ export async function pollQueryStatus(SELECT type, exception_codeFROM ${systemTableRef("system.query_log")}WHERE query_id = {queryId: String}- ${sinceBound.clause}ORDER BY event_time_microseconds DESCLIMIT 1`,- params: { queryId, ...sinceBound.params },+ params: { queryId },clickhouseConfigs: {request_timeout: 60_000,},@@ -135,51 +113,12 @@ export async function pollQueryStatus(throw new Error(`Unknown query log type: ${type}`);}-/**- * Reads the result row count for a completed query from system.query_log.- * Used by the blob-export raw-passthrough path (LFE-10402), where rows are- * never materialized in JS so the count can't be tallied client-side.- * Returns undefined if the query_log row isn't present yet.- */-export async function getQueryResultRows(- queryId: string,- since?: Date,-): Promise<number | undefined> {- const sinceBound = queryLogSinceBound(since);- const result = await queryClickhouse<{ result_rows: string }>({- query: `- SELECT result_rows- FROM ${systemTableRef("system.query_log")}- WHERE query_id = {queryId: String}- AND type = 'QueryFinish'- ${sinceBound.clause}- ORDER BY event_time_microseconds DESC- LIMIT 1- `,- params: { queryId, ...sinceBound.params },- clickhouseSettings: {- skip_unavailable_shards: 1,- },- tags: {- feature: "query-tracking",- operation: "getQueryResultRows",- },- });-- const raw = result[0]?.result_rows;- if (raw === undefined) return undefined;- const parsed = Number(raw);- return Number.isFinite(parsed) ? parsed : undefined;-}-/*** Gets the error message for a failed query from system.query_log.*/export async function getQueryError(queryId: string,- since?: Date,): Promise<string | undefined> {- const sinceBound = queryLogSinceBound(since);const result = await queryClickhouse<{ exception_message: string }>({query: `SELECT exception as exception_message@@ -187,11 +126,10 @@ export async function getQueryError(WHERE query_id = {queryId: String}AND type != 'QueryStart'AND exception != ''- ${sinceBound.clause}ORDER BY event_time_microseconds DESCLIMIT 1`,- params: { queryId, ...sinceBound.params },+ params: { queryId },clickhouseSettings: {skip_unavailable_shards: 1,},diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 1c41c5bb46..9df906aa46 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -1,4 +1,3 @@-import { type Readable } from "stream";import { env } from "../../env";import {clickhouseClient,@@ -294,50 +293,39 @@ export async function* queryClickhouseStream<T>(}/**- * Raw passthrough read: returns the unparsed ClickHouse HTTP response body as a- * byte stream, with `FORMAT JSONEachRow` appended to the query. Unlike- * {@link queryClickhouseStream} there is NO per-row JS work — no `.json()`- * parse, no iteration, no re-serialization — so the JSONL bytes can be piped- * straight into gzip → upload. Used by the blob-export raw-passthrough path- * (LFE-10402) for CPU-bound large exports.+ * Raw passthrough read for the blob-export path (LFE-10402): yields each row's+ * unparsed JSONEachRow text (no trailing newline) instead of its parsed object.+ * Skips the per-row `JSON.parse` (`row.json()`) and lets the caller skip the+ * re-serialize step — the dominant CPU cost on large exports — while reusing the+ * exact same client machinery as {@link queryClickhouseStream}, including its+ * built-in mid-stream exception detection. A failed query therefore throws here,+ * just like the parsed path, so the pipeline aborts instead of emitting a+ * truncated object — no out-of-band system.query_log check needed.*- * Because rows are never parsed, mid-stream ClickHouse exceptions are NOT- * detected here (see {@link handleExceptionRow}). The caller MUST verify the- * query completed cleanly after draining the stream — e.g. via- * `pollQueryStatus(queryId)` against system.query_log — otherwise a query that- * fails after a 200 + partial body silently yields a truncated/garbage file.- *- * Routes through the same `clickhouseClient` (service + settings) as the parsed- * path so serialization settings (e.g. 64-bit int quoting) match, keeping the- * output parsed-equal to the standard path.+ * IMPORTANT: that mid-stream detection only works on ClickHouse >= 25.11 (it+ * relies on the `x-clickhouse-exception-tag` response header). On older servers+ * a query that fails after a 200 response is NOT detected and this can silently+ * yield a truncated object. The only caller (blob raw-passthrough export) is an+ * experimental, per-project opt-in gated on that version — see+ * RAW_PASSTHROUGH_MIN_CLICKHOUSE_VERSION in features/analytics-integrations.*/-export async function queryClickhouseStreamRaw(- opts: ClickhouseQueryOpts & { abortSignal?: AbortSignal },-): Promise<{ stream: Readable; queryId: string }> {+export async function* queryClickhouseStreamRawText(+ opts: ClickhouseQueryOpts,+): AsyncGenerator<string> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);- const tracer = getTracer("clickhouse-query-stream-raw");- const span = tracer.startSpan("clickhouse-query-stream-raw", {+ const tracer = getTracer("clickhouse-query-stream-raw-text");+ const span = tracer.startSpan("clickhouse-query-stream-raw-text", {kind: SpanKind.CLIENT,});let queryId: string | undefined;+try {setSpanQueryAttributes(span, opts.query);const res = await context.with(trace.setSpan(context.active(), span), () =>- clickhouseClient(- opts.clickhouseConfigs,- opts.preferredClickhouseService,- ).exec({- query: `${opts.query}\nFORMAT JSONEachRow`,- query_params: opts.params,- abort_signal: opts.abortSignal,- clickhouse_settings: {- ...opts.clickhouseSettings,- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),- },- }),+ sendClickhouseQuery({ ...opts, format: "JSONEachRow", span }),).catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(@@ -348,26 +336,13 @@ export async function queryClickhouseStreamRaw(queryId = res.query_id;span.setAttribute("ch.queryId", queryId);- recordSummaryOnSpan(span, res.response_headers);-- const stream = res.stream as unknown as Readable;- // The span stays open until the byte stream is fully consumed so its- // duration reflects the read, not just the request handshake. Node emits- // 'close' after both 'end' and 'error' (autoDestroy), so guard against the- // double end() — otherwise the OTel SDK logs "end() called more than once".- let spanEnded = false;- const endSpan = () => {- if (spanEnded) return;- spanEnded = true;- span.end();- };- stream.once("end", endSpan);- stream.once("error", endSpan);- stream.once("close", endSpan);-- return { stream, queryId };++ for await (const rows of res.stream()) {+ for (const row of rows) {+ yield row.text;+ }+ }} catch (error) {- span.end();if (error instanceof ClickHouseResourceError) {const enriched = enrichWithQueryId(error, queryId);throw enriched === error@@ -378,6 +353,8 @@ export async function queryClickhouseStreamRaw(enrichWithQueryId(error as Error, queryId),opts.tags,);+ } finally {+ span.end();}}diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 185d9650aa..35125d5494 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -80,7 +80,7 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,queryClickhouseStream,- queryClickhouseStreamRaw,+ queryClickhouseStreamRawText,} from "./clickhouse";import {EventsObservationRecordReadType,@@ -3569,28 +3569,27 @@ export const getEventsForBlobStorageExport = function ();};-// Raw-passthrough variant (LFE-10402): returns the unparsed JSONEachRow byte-// stream + query_id. When `convertLatencyToSeconds` is set, latency/ttft are-// divided by 1000 in SQL (matching what the JS path would have done); otherwise-// they stay in ms (legacy integrations). Price columns are NOT added.+// Raw-passthrough variant (LFE-10402): yields each row's unparsed JSONEachRow+// text, skipping the per-row parse/enrich/serialize cycle. When+// `convertLatencyToSeconds` is set, latency/ttft are divided by 1000 in SQL+// (matching what the JS path would have done); otherwise they stay in ms (legacy+// integrations). Price columns are NOT added.export const getEventsForBlobStorageExportRaw = function (projectId: string,minTimestamp: Date,maxTimestamp: Date,fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],convertLatencyToSeconds: boolean = false,- abortSignal?: AbortSignal,) {- return queryClickhouseStreamRaw({- ...buildEventsForBlobStorageExportQuery(+ return queryClickhouseStreamRawText(+ buildEventsForBlobStorageExportQuery(projectId,minTimestamp,maxTimestamp,fieldGroups,convertLatencyToSeconds,),- abortSignal,- });+ );};/**diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 72561a0e21..31e67affc1 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -3,7 +3,7 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,queryClickhouseStream,- queryClickhouseStreamRaw,+ queryClickhouseStreamRawText,upsertClickhouse,} from "./clickhouse";import { logger } from "../logger";@@ -1903,25 +1903,23 @@ export const getObservationsForBlobStorageExport = function ();};-// Raw-passthrough variant (LFE-10402): returns the unparsed JSONEachRow byte-// stream + query_id. The caller must verify completion via the query_id (the-// price columns are NOT added here — that enrichment is dropped on this path).+// Raw-passthrough variant (LFE-10402): yields each row's unparsed JSONEachRow+// text, skipping the per-row parse/enrich/serialize cycle. Price columns are+// NOT added here — that enrichment is dropped on this path.export const getObservationsForBlobStorageExportRaw = function (projectId: string,minTimestamp: Date,maxTimestamp: Date,fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],- abortSignal?: AbortSignal,) {- return queryClickhouseStreamRaw({- ...buildObservationsForBlobStorageExportQuery(+ return queryClickhouseStreamRawText(+ buildObservationsForBlobStorageExportQuery(projectId,minTimestamp,maxTimestamp,fieldGroups,),- abortSignal,- });+ );};export const getGenerationsForAnalyticsIntegrations = async function* (diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 4f77041069..389c12a0c7 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -29,10 +29,6 @@ import {createModelCache,blobStorageEndpointConnectionValidationOptions,validateBlobStorageEndpoint,- pollQueryStatus,- getQueryError,- getQueryResultRows,- sleep,} from "@langfuse/shared/src/server";import {registerInFlightBlobExport,@@ -246,87 +242,16 @@ async function* countedStream<T>(}}-// Raw passthrough skips per-row parsing, so a ClickHouse query that fails after-// a 200 + partial body would otherwise be uploaded as a silently truncated-// file. After the stream drains and the upload completes, confirm the query-// finished cleanly via system.query_log. query_log flushes asynchronously-// (~7.5s default), so poll with bounded backoff. A non-completed status throws,-// which fails the job: lastSyncAt is not advanced and the deterministic-// filename is overwritten on the next successful run. Returns result_rows.-const PASSTHROUGH_QUERY_LOG_POLL_ATTEMPTS = 12;-const PASSTHROUGH_QUERY_LOG_POLL_DELAY_MS = 2_500; // ~30s total budget-// Lower bound passed to the system.query_log lookups so they can partition-prune-// instead of scanning every retained partition. query_log is partitioned by-// month (toYYYYMM(event_date)), so a generous buffer is effectively free — it-// only ever widens the scan to the current and (near a month boundary) previous-// partition. Sized to comfortably absorb worker/ClickHouse clock skew. Times are-// UTC end-to-end (convertDateToClickhouseDateTime emits UTC; CH runs UTC), so no-// timezone conversion is involved.-const PASSTHROUGH_QUERY_LOG_SKEW_BUFFER_MS = 24 * 60 * 60 * 1000; // 24h--const verifyRawPassthroughCompletion = async (- queryId: string,- table: string,- startedAt: Date,-): Promise<number | undefined> => {- const tags = { feature: "blobstorage", table };- const since = new Date(- startedAt.getTime() - PASSTHROUGH_QUERY_LOG_SKEW_BUFFER_MS,- );- let status = await pollQueryStatus(queryId, tags, since);- for (- let attempt = 0;- attempt < PASSTHROUGH_QUERY_LOG_POLL_ATTEMPTS &&- status !== "completed" &&- status !== "failed";- attempt++- ) {- await sleep(PASSTHROUGH_QUERY_LOG_POLL_DELAY_MS);- status = await pollQueryStatus(queryId, tags, since);- }-- if (status !== "completed") {- const chError =- status === "failed" ? await getQueryError(queryId, since) : undefined;- throw new Error(- `Raw passthrough export query did not complete cleanly ` +- `(query_id=${queryId} status=${status})` +- (chError ? `: ${chError}` : ""),- );- }-- // The upload is already verified clean (QueryFinish) at this point, so a- // failed row-count read must not invalidate it — treat the count as unknown.- try {- return await getQueryResultRows(queryId, since);- } catch (rowsError) {- logger.warn(- `[BLOB INTEGRATION] Failed to read result_rows for verified passthrough query ${queryId}`,- rowsError,- );- return undefined;- }-};--// Best-effort removal of an already-committed passthrough object whose source-// query did not verify as successful. A delete failure must not mask the-// original verification error, so it is logged and swallowed.-const deletePotentiallyCorruptExport = async (- storageService: StorageService,- filePath: string,-): Promise<void> => {- try {- await storageService.deleteFiles([filePath]);- logger.warn(- `[BLOB INTEGRATION] Deleted unverified passthrough export object ${filePath}`,- );- } catch (deleteError) {- logger.error(- `[BLOB INTEGRATION] Failed to delete unverified passthrough export object ${filePath}`,- deleteError,- );- }-};+// Appends a newline to each raw JSONEachRow line and emits it as bytes, so the+// passthrough path produces the same JSONL framing as the standard formatter+// without re-serializing (the line is already JSON from ClickHouse).+const createRawJsonlNewlineTransform = (): Transform =>+ new Transform({+ writableObjectMode: true,+ transform(line: string, _encoding, callback) {+ callback(null, Buffer.from(line + "\n"));+ },+ });const processBlobStorageExport = async (config: {projectId: string;@@ -470,48 +395,53 @@ const processBlobStorageExport = async (config: {const serializedCounter = new ByteCounter();const compressedCounter = config.compressed ? new ByteCounter() : null;- // Row count source: the standard path tallies rows in JS (countedStream);- // the passthrough path reads result_rows from query_log after upload.+ // 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 };- let passthroughRows: number | undefined;- let passthroughQueryId: string | undefined;- // Captured just before the query is issued, so the post-hoc query_log- // lookups can partition-prune on event_date instead of full scans.- let passthroughQueryStartedAt: Date | undefined;let fileStream: Readable;if (passthroughEligible) {- // Stream ClickHouse JSONEachRow bytes straight through: no row parse,- // no enrichment, no re-serialization. Shaping (latency→s, dropped- // price columns, field-group selection) is already baked into the SQL.- passthroughQueryStartedAt = new Date();- const { stream, queryId } =+ // 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.+ // The client's own mid-stream exception detection (CH ≥ 25.11) errors+ // the stream on a failed query, which aborts the upload — no committed+ // object and no out-of-band system.query_log check needed.+ const rawRows =config.table === "observations"- ? await getObservationsForBlobStorageExportRaw(+ ? getObservationsForBlobStorageExportRaw(config.projectId,config.minTimestamp,config.maxTimestamp,exportFieldGroups,)- : await getEventsForBlobStorageExportRaw(+ : getEventsForBlobStorageExportRaw(config.projectId,config.minTimestamp,config.maxTimestamp,exportFieldGroups,config.convertV4LatencyToSeconds,);- passthroughQueryId = queryId;++ const dataStream = countedStream(rawRows, sourceStats);+ const jsonlNewline = createRawJsonlNewlineTransform();fileStream = compressedCounter? pipeline(- stream,+ dataStream,+ jsonlNewline,serializedCounter,createGzip(),compressedCounter,pipelineCallback,)- : pipeline(stream, serializedCounter, pipelineCallback);+ : pipeline(+ dataStream,+ jsonlNewline,+ serializedCounter,+ pipelineCallback,+ );} else {let rawStream: AsyncGenerator<Record<string, unknown>>;@@ -605,57 +535,19 @@ const processBlobStorageExport = async (config: {projectId: config.projectId,});- // Passthrough skips parse-time exception detection, so confirm the- // ClickHouse query finished cleanly (and read its row count) before- // treating the uploaded object as valid. The object is already- // committed at this point, so if verification fails (query errored, or- // query_log is unreadable) delete it: the deterministic filename is- // only overwritten on retry in catch-up mode, not when caught up, so- // a corrupt object could otherwise linger as an orphan.- if (passthroughEligible && passthroughQueryId) {- try {- passthroughRows = await verifyRawPassthroughCompletion(- passthroughQueryId,- config.table,- passthroughQueryStartedAt ?? new Date(),- );- } catch (verifyError) {- await deletePotentiallyCorruptExport(storageService, filePath);- throw verifyError;- }- }-- // On passthrough the count comes from query_log; "unknown" (count not- // yet flushed) is distinct from a genuinely empty export.- const rows = passthroughEligible- ? (passthroughRows ?? "unknown")- : sourceStats.rows;-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"} ` +- `rows=${rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` ++ `rows=${sourceStats.rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` +`serializedBytes=${serializedCounter.bytes} uploadDurationMs=${Math.round(performance.now() - uploadStartMs)}`,);} finally {- // Omit blob.rows on the passthrough path when the count is unknown- // (query_log not yet flushed, or verification failed) so observability- // can tell "unknown" apart from a genuinely empty export.- if (passthroughEligible) {- if (passthroughRows !== undefined) {- span.setAttribute("blob.rows", passthroughRows);- }- } else {- span.setAttribute("blob.rows", sourceStats.rows);- }- // sourceWaitMs is a per-row JS metric; not meaningful for passthrough.- if (!passthroughEligible) {- span.setAttribute(- "blob.sourceWaitMs",- Math.round(sourceStats.sourceWaitMs),- );- }+ span.setAttribute("blob.rows", sourceStats.rows);+ span.setAttribute(+ "blob.sourceWaitMs",+ Math.round(sourceStats.sourceWaitMs),+ );span.setAttribute("blob.serializedBytes", serializedCounter.bytes);if (uploadStartMs !== undefined) {span.setAttribute(