🪢 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
feat(worker): blob export raw-passthrough path (LFE-10402) (#14400)
Niklas Semmler7383c0787df1
diff --git a/packages/shared/prisma/migrations/20260619120000_add_blob_storage_export_tuning/migration.sql b/packages/shared/prisma/migrations/20260619120000_add_blob_storage_export_tuning/migration.sqlnew file mode 100644index 0000000000..8a19dd939d--- /dev/null+++ b/packages/shared/prisma/migrations/20260619120000_add_blob_storage_export_tuning/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "blob_storage_integrations" ADD COLUMN "export_tuning" JSONB;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 94b3ddc986..088998f68b 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1227,6 +1227,11 @@ model BlobStorageIntegration {exportFieldGroups String[] @default(["core", "basic", "time", "io", "metadata", "model", "usage", "prompt", "metrics", "tools", "trace_context"]) @map("export_field_groups")compressed Boolean @default(true) @map("compressed")+ // Per-project blob-export tuning (set via DB directly for now; no UI/tRPC+ // write path). Validated/clamped at job time; null/malformed → defaults.+ // Shared with LFE-10394; extend the zod schema, do not duplicate the column.+ exportTuning Json? @map("export_tuning")+// Error trackinglastError String? @map("last_error")lastErrorAt DateTime? @map("last_error_at")diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.tsnew file mode 100644index 0000000000..ce627d7498--- /dev/null+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.test.ts@@ -0,0 +1,64 @@+import { describe, it, expect } from "vitest";+import { resolveBlobExportTuning } from "./blob-export-tuning";++describe("resolveBlobExportTuning", () => {+ it("defaults to rawPassthrough=false for null/undefined", () => {+ expect(resolveBlobExportTuning(null)).toEqual({+ resolved: { rawPassthrough: false },+ warnings: [],+ });+ expect(resolveBlobExportTuning(undefined)).toEqual({+ resolved: { rawPassthrough: false },+ warnings: [],+ });+ });++ it("honors rawPassthrough=true", () => {+ expect(resolveBlobExportTuning({ rawPassthrough: true })).toEqual({+ resolved: { rawPassthrough: true },+ warnings: [],+ });+ });++ it("honors rawPassthrough=false explicitly", () => {+ expect(resolveBlobExportTuning({ rawPassthrough: false })).toEqual({+ resolved: { rawPassthrough: false },+ warnings: [],+ });+ });++ it("defaults rawPassthrough when the key is absent from a valid object", () => {+ expect(resolveBlobExportTuning({})).toEqual({+ resolved: { rawPassthrough: false },+ warnings: [],+ });+ });++ it("ignores unknown keys (forward-compat with LFE-10394 knobs)", () => {+ const result = resolveBlobExportTuning({+ rawPassthrough: true,+ partSizeBytes: 200,+ maxConcurrentParts: 8,+ skipEnrichment: true,+ });+ expect(result.resolved).toEqual({ rawPassthrough: true });+ expect(result.warnings).toEqual([]);+ });++ it("falls back to defaults and warns on a wrong-typed rawPassthrough", () => {+ const result = resolveBlobExportTuning({ rawPassthrough: "yes" });+ expect(result.resolved).toEqual({ rawPassthrough: false });+ expect(result.warnings.length).toBe(1);+ });++ it("falls back to defaults and warns on a non-object column", () => {+ const result = resolveBlobExportTuning("garbage");+ expect(result.resolved).toEqual({ rawPassthrough: false });+ expect(result.warnings.length).toBe(1);+ });++ it("never throws", () => {+ expect(() => resolveBlobExportTuning(12345)).not.toThrow();+ expect(() => resolveBlobExportTuning([])).not.toThrow();+ });+});diff --git a/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts b/packages/shared/src/features/analytics-integrations/blob-export-tuning.tsnew file mode 100644index 0000000000..9498143c68--- /dev/null+++ b/packages/shared/src/features/analytics-integrations/blob-export-tuning.ts@@ -0,0 +1,59 @@+// Per-project blob-export tuning, persisted as a nullable JSON column+// (`BlobStorageIntegration.exportTuning`) and set via the DB directly for now+// (no UI/tRPC write path yet). Validated and resolved at job time.+//+// This module is client-safe (no logger / server imports) so a future settings+// UI can reuse the schema for write-validation. The worker logs the warnings+// returned by the resolver.+//+// Shared with LFE-10394 (upload tuning knobs: partSizeBytes / maxConcurrentParts+// / maxPartAttempts / skipEnrichment). Extend this schema rather than forking+// it. Unknown keys are stripped (zod default) so a key written by a newer+// writer is harmless to an older worker.+import { z } from "zod";++export const BlobExportTuningSchema = z.object({+ // LFE-10402 raw-passthrough export path: stream ClickHouse JSONEachRow bytes+ // 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.+ rawPassthrough: z.boolean().optional(),+});++export type BlobExportTuning = z.infer<typeof BlobExportTuningSchema>;++export type ResolvedBlobExportTuning = {+ rawPassthrough: boolean;+};++/**+ * Resolve the persisted `exportTuning` JSON into concrete export settings.+ * Pure and total: never throws. A null / non-object / malformed column resolves+ * to the safe defaults (today's behaviour) and records a warning the caller can+ * log. Unknown keys are ignored.+ */+export function resolveBlobExportTuning(raw: unknown): {+ resolved: ResolvedBlobExportTuning;+ warnings: string[];+} {+ const defaults: ResolvedBlobExportTuning = { rawPassthrough: false };++ if (raw === null || raw === undefined) {+ return { resolved: defaults, warnings: [] };+ }++ const parsed = BlobExportTuningSchema.safeParse(raw);+ if (!parsed.success) {+ return {+ resolved: defaults,+ warnings: [+ `Malformed exportTuning column, falling back to defaults: ${parsed.error.message}`,+ ],+ };+ }++ return {+ resolved: { rawPassthrough: parsed.data.rawPassthrough ?? false },+ warnings: [],+ };+}diff --git a/packages/shared/src/features/analytics-integrations/index.ts b/packages/shared/src/features/analytics-integrations/index.tsindex c382c3b8d6..c87d65e9d6 100644--- a/packages/shared/src/features/analytics-integrations/index.ts+++ b/packages/shared/src/features/analytics-integrations/index.ts@@ -9,6 +9,7 @@ import {} from "../../domain/observation-field-groups";export * from "./blob-export-gate";+export * from "./blob-export-tuning";export const EXPORT_SOURCE_OPTIONS: Array<{value: AnalyticsIntegrationExportSource;diff --git a/packages/shared/src/server/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.tsindex 8a5fcb4269..e55448f6ad 100644--- a/packages/shared/src/server/clickhouse/queryTracking.ts+++ b/packages/shared/src/server/clickhouse/queryTracking.ts@@ -1,5 +1,6 @@import { env } from "../../env";import { queryClickhouse } from "../repositories";+import { convertDateToClickhouseDateTime } from "./client";// ============================================================================// Types@@ -15,6 +16,24 @@ 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@@ -40,6 +59,7 @@ function systemTableRef(export async function pollQueryStatus(queryId: string,tags?: Record<string, string>,+ since?: Date,): Promise<QueryStatus> {const tagsWithDefaults = {feature: "query-tracking",@@ -68,6 +88,7 @@ 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;@@ -76,10 +97,11 @@ 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 },+ params: { queryId, ...sinceBound.params },clickhouseConfigs: {request_timeout: 60_000,},@@ -113,12 +135,51 @@ 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@@ -126,10 +187,11 @@ 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 },+ params: { queryId, ...sinceBound.params },clickhouseSettings: {skip_unavailable_shards: 1,},diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 9337ecd1f9..1c41c5bb46 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -1,3 +1,4 @@+import { type Readable } from "stream";import { env } from "../../env";import {clickhouseClient,@@ -292,6 +293,94 @@ 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.+ *+ * 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.+ */+export async function queryClickhouseStreamRaw(+ opts: ClickhouseQueryOpts & { abortSignal?: AbortSignal },+): Promise<{ stream: Readable; queryId: string }> {+ if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const tracer = getTracer("clickhouse-query-stream-raw");+ const span = tracer.startSpan("clickhouse-query-stream-raw", {+ 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)),+ },+ }),+ )+ .catch((error) => {+ throw ClickHouseResourceError.wrapIfResourceError(+ error as Error,+ opts.tags,+ );+ });++ 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 };+ } catch (error) {+ span.end();+ if (error instanceof ClickHouseResourceError) {+ const enriched = enrichWithQueryId(error, queryId);+ throw enriched === error+ ? error+ : new ClickHouseResourceError(error.errorType, enriched, error.tags);+ }+ 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/events.ts b/packages/shared/src/server/repositories/events.tsindex 62130f3792..185d9650aa 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -80,6 +80,7 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,queryClickhouseStream,+ queryClickhouseStreamRaw,} from "./clickhouse";import {EventsObservationRecordReadType,@@ -3483,12 +3484,26 @@ export const hasAnyUserFromEventsTable = async (* Streams events from ClickHouse for blob storage export.* Uses EventsQueryBuilder for consistent query construction.*/-export const getEventsForBlobStorageExport = function (+// metrics field set emits latency / time_to_first_token in MILLISECONDS. The+// raw-passthrough path (LFE-10402) cannot convert ms→s in JS, so when requested+// it selects the seconds-converted expressions directly in SQL instead. The+// standard path keeps ms here and converts conditionally in JS, so it stays+// byte-for-byte unchanged.+const EVENTS_EXPORT_METRICS_SECONDS_SQL = [+ "if(isNull(e.end_time), NULL, date_diff('millisecond', e.start_time, e.end_time) / 1000) as latency",+ "if(isNull(e.completion_start_time), NULL, date_diff('millisecond', e.start_time, e.completion_start_time) / 1000) as \"time_to_first_token\"",+];++// Shared SQL+params builder for the events blob-export. `convertLatencyToSecondsInSql`+// is only set by the raw-passthrough path; the standard path leaves it false so+// its output is identical to today.+const buildEventsForBlobStorageExportQuery = (projectId: string,minTimestamp: Date,maxTimestamp: Date,- fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],-) {+ fieldGroups: ObservationFieldGroupFull[],+ convertLatencyToSecondsInSql: boolean,+) => {const queryBuilder = new EventsQueryBuilder({ projectId });// core is always required (provides id, trace_id, start/end_time used for cursor and deduplication)@@ -3501,6 +3516,8 @@ export const getEventsForBlobStorageExport = function (queryBuilder.selectIO(false); // Full I/O, no truncation} else if (group === "model") {queryBuilder.selectFieldSet("model_export"); // "model_export" is the SQL field set name for the "model" group+ } else if (group === "metrics" && convertLatencyToSecondsInSql) {+ queryBuilder.selectRaw(...EVENTS_EXPORT_METRICS_SECONDS_SQL);} else {queryBuilder.selectFieldSet(group);}@@ -3519,7 +3536,7 @@ export const getEventsForBlobStorageExport = function (const { query, params } = queryBuilder.buildWithParams();- return queryClickhouseStream<Record<string, unknown>>({+ return {query,params,tags: {@@ -3531,7 +3548,48 @@ export const getEventsForBlobStorageExport = function (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},- preferredClickhouseService: "EventsReadOnly",+ preferredClickhouseService: "EventsReadOnly" as const,+ };+};++export const getEventsForBlobStorageExport = function (+ projectId: string,+ minTimestamp: Date,+ maxTimestamp: Date,+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],+) {+ return queryClickhouseStream<Record<string, unknown>>(+ buildEventsForBlobStorageExportQuery(+ projectId,+ minTimestamp,+ maxTimestamp,+ fieldGroups,+ false, // standard path converts latency ms→s in JS+ ),+ );+};++// 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.+export const getEventsForBlobStorageExportRaw = function (+ projectId: string,+ minTimestamp: Date,+ maxTimestamp: Date,+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],+ convertLatencyToSeconds: boolean = false,+ abortSignal?: AbortSignal,+) {+ return queryClickhouseStreamRaw({+ ...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 ca86269c32..72561a0e21 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -3,6 +3,7 @@ import {parseClickhouseUTCDateTimeFormat,queryClickhouse,queryClickhouseStream,+ queryClickhouseStreamRaw,upsertClickhouse,} from "./clickhouse";import { logger } from "../logger";@@ -1831,12 +1832,17 @@ const LEGACY_OBSERVATION_EXPORT_SQL_OVERRIDES: Record<string, string> = {model_id: "internal_model_id as model_id",};-export const getObservationsForBlobStorageExport = function (+// Shared SQL+params builder for the observations blob-export. Both the parsed+// stream (standard path) and the raw-passthrough path (LFE-10402) run the+// SAME query, so the output is parsed-equal by construction. Note latency is+// already converted to seconds in the SELECT (no JS conversion needed), so this+// query is identical for both paths.+const buildObservationsForBlobStorageExportQuery = (projectId: string,minTimestamp: Date,maxTimestamp: Date,- fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],-) {+ fieldGroups: ObservationFieldGroupFull[],+) => {// core is always required (provides id, trace_id, start/end_time used for deduplication)const effectiveGroups = new Set<ObservationFieldGroupFull>(["core",@@ -1861,7 +1867,7 @@ export const getObservationsForBlobStorageExport = function (LIMIT 1 BY id, project_id, type`;- const records = queryClickhouseStream<Record<string, unknown>>({+ return {query,params: {projectId,@@ -1877,10 +1883,45 @@ export const getObservationsForBlobStorageExport = function (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},- preferredClickhouseService: "ReadOnly",- });+ preferredClickhouseService: "ReadOnly" as const,+ };+};++export const getObservationsForBlobStorageExport = function (+ projectId: string,+ minTimestamp: Date,+ maxTimestamp: Date,+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],+) {+ return queryClickhouseStream<Record<string, unknown>>(+ buildObservationsForBlobStorageExportQuery(+ projectId,+ minTimestamp,+ maxTimestamp,+ fieldGroups,+ ),+ );+};- return records;+// 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).+export const getObservationsForBlobStorageExportRaw = function (+ projectId: string,+ minTimestamp: Date,+ maxTimestamp: Date,+ fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],+ abortSignal?: AbortSignal,+) {+ return queryClickhouseStreamRaw({+ ...buildObservationsForBlobStorageExportQuery(+ projectId,+ minTimestamp,+ maxTimestamp,+ fieldGroups,+ ),+ abortSignal,+ });};export const getGenerationsForAnalyticsIntegrations = async function* (diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 3dc7763ddb..2fb7668c7d 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -1496,4 +1496,252 @@ describe("BlobStorageIntegrationProcessingJob", () => {},);});++ // LFE-10402: raw-passthrough streams ClickHouse JSONEachRow bytes straight to+ // gzip → upload, skipping the per-row JS parse/enrich/serialize pipeline. The+ // output must be parsed-equal to the standard path minus the dropped price+ // columns. Passthrough only applies to JSONL exports of observations /+ // observations_v2 and is gated behind the exportTuning.rawPassthrough flag.+ maybeDescribe("raw passthrough export (LFE-10402)", () => {+ const PRICE_COLUMNS = ["input_price", "output_price", "total_price"];+ const stripPrices = (row: Record<string, unknown>) => {+ const copy = { ...row };+ for (const col of PRICE_COLUMNS) delete copy[col];+ return copy;+ };+ const parseJsonl = (content: string): Record<string, unknown>[] =>+ content+ .trim()+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line));+ const byId = (rows: Record<string, unknown>[]) =>+ new Map(rows.map((r) => [r.id as string, r]));++ const downloadDir = async (prefix: string, dir: string) => {+ const files = await s3StorageService.listFiles(prefix);+ const file = files.find((f) => f.file.includes(`/${dir}/`));+ expect(file).toBeDefined();+ return parseJsonl(await s3StorageService.download(file!.file));+ };++ const seedModelWithPrices = async (projectId: string, modelId: string) =>+ prisma.model.create({+ data: {+ id: modelId,+ projectId,+ modelName: "gpt-4-passthrough",+ matchPattern: "gpt-4-passthrough",+ unit: "TOKENS",+ pricingTiers: {+ create: {+ name: "Standard",+ isDefault: true,+ conditions: [],+ priority: 0,+ prices: {+ createMany: {+ data: [+ { modelId, usageType: "input", price: "0.03" },+ { modelId, usageType: "output", price: "0.06" },+ { modelId, usageType: "total", price: "0.09" },+ ],+ },+ },+ },+ },+ },+ });++ it("produces output parsed-equal to the standard path (minus price columns) for observations + events", 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 modelId = randomUUID();+ const traceId = randomUUID();+ const observationId = randomUUID();+ const eventId = randomUUID();++ await seedModelWithPrices(projectId, modelId);++ 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: false,+ fileType: BlobStorageIntegrationFileType.JSONL,+ // default (full) field groups → metadata + model selected in both paths+ },+ });++ await Promise.all([+ createTracesCh([+ createTrace({+ id: traceId,+ project_id: projectId,+ timestamp: dataTime,+ name: "Passthrough Trace",+ }),+ ]),+ createObservationsCh([+ createObservation({+ id: observationId,+ trace_id: traceId,+ project_id: projectId,+ start_time: dataTime,+ end_time: dataTime + 5500, // 5.5s → non-round latency+ completion_start_time: dataTime + 1000,+ total_cost: 42.5,+ usage_details: { input: 100, output: 200, total: 300 },+ internal_model_id: modelId,+ name: "Passthrough Observation",+ metadata: { k: "v" },+ }),+ ]),+ createEventsCh([+ createEvent({+ id: eventId,+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "Passthrough Event",+ start_time: dataTime * 1000,+ end_time: (dataTime + 5500) * 1000,+ completion_start_time: (dataTime + 1000) * 1000,+ model_id: modelId,+ metadata: { k: "v" },+ metadata_names: ["k"],+ metadata_values: ["v"],+ }),+ ]),+ ]);++ // 1) Standard path+ await handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job);+ const standardObs = byId(await downloadDir(s3Prefix, "observations"));+ const standardEvents = byId(+ await downloadDir(s3Prefix, "observations_v2"),+ );++ // Sanity: the standard path enriches with price columns. Events export+ // is keyed by span_id (not the seeded event id), so grab the single row.+ const standardEventRow = [...standardEvents.values()][0];+ expect(standardObs.get(observationId)).toHaveProperty("input_price");+ expect(standardEventRow).toHaveProperty("total_price");++ // 2) Reset and re-run with rawPassthrough enabled.+ const filesToClear = await s3StorageService.listFiles(s3Prefix);+ await s3StorageService.deleteFiles(filesToClear.map((f) => f.file));+ await prisma.blobStorageIntegration.update({+ where: { projectId },+ data: {+ lastSyncAt: twoHoursAgo,+ nextSyncAt: twoHoursAgo,+ exportTuning: { rawPassthrough: true },+ },+ });++ await handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job);+ const passthroughObs = byId(await downloadDir(s3Prefix, "observations"));+ const passthroughEvents = byId(+ await downloadDir(s3Prefix, "observations_v2"),+ );++ // Passthrough drops the price columns…+ const passthroughEventRow = [...passthroughEvents.values()][0];+ expect(passthroughObs.get(observationId)).not.toHaveProperty(+ "input_price",+ );+ expect(passthroughEventRow).not.toHaveProperty("total_price");++ // …and is otherwise parsed-equal to the standard output.+ expect(passthroughObs.size).toBe(standardObs.size);+ expect(passthroughEvents.size).toBe(standardEvents.size);+ for (const [id, standardRow] of standardObs) {+ expect(passthroughObs.get(id)).toEqual(stripPrices(standardRow));+ }+ for (const [id, standardRow] of standardEvents) {+ expect(passthroughEvents.get(id)).toEqual(stripPrices(standardRow));+ }+ }, 60_000);++ it("falls back to the standard path when fileType is not JSONL", 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 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: "EVENTS",+ nextSyncAt: twoHoursAgo,+ lastSyncAt: twoHoursAgo,+ compressed: false,+ // CSV is ineligible for passthrough → standard path despite the flag+ fileType: BlobStorageIntegrationFileType.CSV,+ exportTuning: { rawPassthrough: true },+ },+ });++ await createEventsCh([+ createEvent({+ id: eventId,+ project_id: projectId,+ trace_id: randomUUID(),+ type: "GENERATION",+ name: "CSV Fallback Event",+ start_time: dataTime * 1000,+ end_time: (dataTime + 5000) * 1000,+ }),+ ]);++ await handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job);++ const eventRows = await s3StorageService.listFiles(s3Prefix);+ const eventFile = eventRows.find((f) =>+ f.file.includes("/observations_v2/"),+ );+ expect(eventFile).toBeDefined();+ const content = await s3StorageService.download(eventFile!.file);+ // CSV header row present → standard (CSV) path ran, not JSONL passthrough.+ // (Events export keys by span_id, so assert on the seeded event name.)+ expect(content.split("\n")[0]).toContain("id");+ expect(content).toContain("CSV Fallback Event");+ }, 30_000);+ });});diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 10eafecef5..4f77041069 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -1,4 +1,4 @@-import { pipeline, Transform } from "stream";+import { pipeline, Transform, type Readable } from "stream";import { createGzip } from "zlib";import { monitorEventLoopDelay } from "perf_hooks";import { Job } from "bullmq";@@ -11,9 +11,11 @@ import {StorageServiceFactory,streamTransformations,getObservationsForBlobStorageExport,+ getObservationsForBlobStorageExportRaw,getTracesForBlobStorageExport,getScoresForBlobStorageExport,getEventsForBlobStorageExport,+ getEventsForBlobStorageExportRaw,getCurrentSpan,instrumentAsync,recordGauge,@@ -27,6 +29,10 @@ import {createModelCache,blobStorageEndpointConnectionValidationOptions,validateBlobStorageEndpoint,+ pollQueryStatus,+ getQueryError,+ getQueryResultRows,+ sleep,} from "@langfuse/shared/src/server";import {registerInFlightBlobExport,@@ -43,6 +49,7 @@ import {type ObservationFieldGroupFull,isEnrichedBlobExportAvailable,isEnrichedBlobExportSource,+ resolveBlobExportTuning,} from "@langfuse/shared";import { decrypt } from "@langfuse/shared/encryption";import { randomUUID } from "crypto";@@ -239,6 +246,88 @@ 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,+ );+ }+};+const processBlobStorageExport = async (config: {projectId: string;minTimestamp: Date;@@ -256,6 +345,7 @@ const processBlobStorageExport = async (config: {compressed: boolean;convertV4LatencyToSeconds: boolean;exportFieldGroups?: ObservationFieldGroupFull[];+ rawPassthrough: boolean;bullmqJobId: string | undefined;bullmqAttemptsMade: number;}) => {@@ -350,57 +440,23 @@ const processBlobStorageExport = async (config: {? config.exportFieldGroups: [...OBSERVATION_FIELD_GROUPS_FULL];- let rawStream: AsyncGenerator<Record<string, unknown>>;-- switch (config.table) {- case "traces":- rawStream = getTracesForBlobStorageExport(- config.projectId,- config.minTimestamp,- config.maxTimestamp,- );- break;- case "observations":- rawStream = enrichObservationStream(- getObservationsForBlobStorageExport(- config.projectId,- config.minTimestamp,- config.maxTimestamp,- exportFieldGroups,- ),- config.projectId,- "model_id",- false, // v3 query already returns latency in seconds- exportFieldGroups,- );- break;- case "scores":- rawStream = getScoresForBlobStorageExport(- config.projectId,- config.minTimestamp,- config.maxTimestamp,- );- break;- case "observations_v2": // observations_v2 is the events table- rawStream = enrichObservationStream(- getEventsForBlobStorageExport(- config.projectId,- config.minTimestamp,- config.maxTimestamp,- exportFieldGroups,- ),- config.projectId,- "model_id",- config.convertV4LatencyToSeconds,- exportFieldGroups,- );- break;- default:- throw new Error(`Unsupported table type: ${config.table}`);- }-- const sourceStats = { rows: 0, sourceWaitMs: 0 };- const dataStream = countedStream(rawStream, sourceStats);+ // Raw passthrough (LFE-10402) is opt-in per project and only valid for+ // JSONL output of the enriched-observation tables — the only formats+ // where ClickHouse FORMAT JSONEachRow bytes map 1:1 to the file. Any+ // other request falls back to the standard path. The integration-level+ // ineligibility warning is emitted once by the dispatcher; here we just+ // 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 =+ config.rawPassthrough &&+ config.fileType === BlobStorageIntegrationFileType.JSONL &&+ (config.table === "observations" ||+ config.table === "observations_v2");++ span.setAttribute(+ "blob.path",+ passthroughEligible ? "passthrough" : "standard",+ );const pipelineCallback = (err: NodeJS.ErrnoException | null) => {if (err) {@@ -413,23 +469,118 @@ const processBlobStorageExport = async (config: {const serializedCounter = new ByteCounter();const compressedCounter = config.compressed ? new ByteCounter() : null;- const formatTransform = streamTransformations[config.fileType]();-- const fileStream = compressedCounter- ? pipeline(- dataStream,- formatTransform,- serializedCounter,- createGzip(),- compressedCounter,- pipelineCallback,- )- : pipeline(- dataStream,- formatTransform,- serializedCounter,- pipelineCallback,- );++ // Row count source: the standard path tallies rows in JS (countedStream);+ // the passthrough path reads result_rows from query_log after upload.+ 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 } =+ config.table === "observations"+ ? await getObservationsForBlobStorageExportRaw(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ exportFieldGroups,+ )+ : await getEventsForBlobStorageExportRaw(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ exportFieldGroups,+ config.convertV4LatencyToSeconds,+ );+ passthroughQueryId = queryId;++ fileStream = compressedCounter+ ? pipeline(+ stream,+ serializedCounter,+ createGzip(),+ compressedCounter,+ pipelineCallback,+ )+ : pipeline(stream, serializedCounter, pipelineCallback);+ } else {+ let rawStream: AsyncGenerator<Record<string, unknown>>;++ switch (config.table) {+ case "traces":+ rawStream = getTracesForBlobStorageExport(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ );+ break;+ case "observations":+ rawStream = enrichObservationStream(+ getObservationsForBlobStorageExport(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ exportFieldGroups,+ ),+ config.projectId,+ "model_id",+ false, // v3 query already returns latency in seconds+ exportFieldGroups,+ );+ break;+ case "scores":+ rawStream = getScoresForBlobStorageExport(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ );+ break;+ case "observations_v2": // observations_v2 is the events table+ rawStream = enrichObservationStream(+ getEventsForBlobStorageExport(+ config.projectId,+ config.minTimestamp,+ config.maxTimestamp,+ exportFieldGroups,+ ),+ config.projectId,+ "model_id",+ config.convertV4LatencyToSeconds,+ exportFieldGroups,+ );+ break;+ default:+ throw new Error(`Unsupported table type: ${config.table}`);+ }++ const dataStream = countedStream(rawStream, sourceStats);+ const formatTransform = streamTransformations[config.fileType]();++ fileStream = compressedCounter+ ? pipeline(+ dataStream,+ formatTransform,+ serializedCounter,+ createGzip(),+ compressedCounter,+ pipelineCallback,+ )+ : pipeline(+ dataStream,+ formatTransform,+ serializedCounter,+ pipelineCallback,+ );+ }// Upload the file to cloud storage// For CSV exports, use larger part size to handle big files@@ -454,18 +605,57 @@ 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} ` +- `rows=${sourceStats.rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` ++ `path=${passthroughEligible ? "passthrough" : "standard"} ` ++ `rows=${rows} sourceWaitMs=${Math.round(sourceStats.sourceWaitMs)} ` +`serializedBytes=${serializedCounter.bytes} uploadDurationMs=${Math.round(performance.now() - uploadStartMs)}`,);} finally {- span.setAttribute("blob.rows", sourceStats.rows);- span.setAttribute(- "blob.sourceWaitMs",- Math.round(sourceStats.sourceWaitMs),- );+ // 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.serializedBytes", serializedCounter.bytes);if (uploadStartMs !== undefined) {span.setAttribute(@@ -637,6 +827,16 @@ export const handleBlobStorageIntegrationProjectJob = async (const convertV4LatencyToSeconds =blobStorageIntegration.createdAt >= new Date("2026-04-01T00:00:00Z");+ // Per-project export tuning (set via DB directly; no UI/tRPC write path).+ // Malformed/absent column resolves to defaults — never throws.+ const { resolved: exportTuning, warnings: exportTuningWarnings } =+ resolveBlobExportTuning(blobStorageIntegration.exportTuning);+ for (const warning of exportTuningWarnings) {+ logger.warn(+ `[BLOB INTEGRATION] exportTuning for project ${projectId}: ${warning}`,+ );+ }+const executionConfig = {projectId,minTimestamp,@@ -656,6 +856,7 @@ export const handleBlobStorageIntegrationProjectJob = async (convertV4LatencyToSeconds,exportFieldGroups:blobStorageIntegration.exportFieldGroups as ObservationFieldGroupFull[],+ rawPassthrough: exportTuning.rawPassthrough,bullmqJobId: job.id,bullmqAttemptsMade: job.attemptsMade,};@@ -666,6 +867,25 @@ export const handleBlobStorageIntegrationProjectJob = async (projectId,);+ // Warn once per run if rawPassthrough is enabled but no table will actually+ // use it. Passthrough only applies to JSONL exports of observations /+ // observations_v2; every non-trace-only export source includes one of those,+ // so the only integration-level ineligibility is a non-JSONL file type or a+ // trace-only project. The per-table fallback for scores/traces is expected+ // dispatch and is intentionally not warned about (avoids ~hourly log noise).+ if (+ exportTuning.rawPassthrough &&+ (blobStorageIntegration.fileType !==+ BlobStorageIntegrationFileType.JSONL ||+ isTraceOnlyProject)+ ) {+ logger.warn(+ `[BLOB INTEGRATION] rawPassthrough enabled for project ${projectId} but no eligible table will use it ` ++ `(fileType=${blobStorageIntegration.fileType}, traceOnly=${isTraceOnlyProject}); exporting via the standard path. ` ++ `Passthrough requires JSONL output of observations or observations_v2.`,+ );+ }+if (isTraceOnlyProject) {// Only process traces table for projects in the trace-only list (legacy behavior)logger.info(