🪢 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(blob-export): add configurable field groups for events export (#13493)
Niklas Semmler2e6c11f07b60
diff --git a/.gitignore b/.gitignoreindex acb7d3f8b6..17ef96368c 100644--- a/.gitignore+++ b/.gitignore@@ -94,3 +94,6 @@ web/test-results/*# Refactoring planning files (local only)**/.refactor/**/.pi-lens/++# Serena MCP server config (local only)+.serena/diff --git a/packages/shared/src/features/analytics-integrations/index.ts b/packages/shared/src/features/analytics-integrations/index.tsindex 796e5c90dd..e9a83bb328 100644--- a/packages/shared/src/features/analytics-integrations/index.ts+++ b/packages/shared/src/features/analytics-integrations/index.ts@@ -46,3 +46,62 @@ export const BLOB_EXPORT_FIELD_GROUPS = [] as const;export type BlobExportFieldGroup = (typeof BLOB_EXPORT_FIELD_GROUPS)[number];++// Keyed by BlobExportFieldGroup so TypeScript errors if a group is added to+// BLOB_EXPORT_FIELD_GROUPS without a corresponding label/description here.+const EXPORT_FIELD_GROUP_LABELS = {+ core: {+ label: "Core",+ description:+ "id, trace_id, start_time, end_time, project_id, parent_observation_id, type",+ },+ basic: {+ label: "Basic",+ description:+ "name, level, status_message, version, environment, bookmarked, public, user_id, session_id",+ },+ time: {+ label: "Time",+ description: "completion_start_time, created_at, updated_at",+ },+ io: {+ label: "Input / Output",+ description: "input, output",+ },+ metadata: {+ label: "Metadata",+ description: "metadata",+ },+ model: {+ label: "Model",+ description: "provided_model_name, model_id, model_parameters",+ },+ usage: {+ label: "Usage",+ description:+ "usage_details, cost_details, total_cost, input_price, output_price, total_price",+ },+ prompt: {+ label: "Prompt",+ description: "prompt_id, prompt_name, prompt_version",+ },+ metrics: {+ label: "Metrics",+ description: "latency, time_to_first_token",+ },+ tools: {+ label: "Tools",+ description: "tool_definitions, tool_calls, tool_call_names",+ },+ trace_context: {+ label: "Trace Context",+ description: "tags, release, trace_name, usage_pricing_tier_name",+ },+} satisfies Record<+ BlobExportFieldGroup,+ { label: string; description: string }+>;++export const EXPORT_FIELD_GROUP_OPTIONS = BLOB_EXPORT_FIELD_GROUPS.map(+ (value) => ({ value, ...EXPORT_FIELD_GROUP_LABELS[value] }),+);diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex 1e9d7d773e..94d7fc7259 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -226,6 +226,8 @@ const FIELD_SETS = {io: ["input", "output"],metadata: ["metadata"],tools: ["toolDefinitions", "toolCalls", "toolCallNames"],+ trace_context: ["tags", "release", "traceName", "usagePricingTierName"],+ model_export: ["providedModelName", "modelId", "modelParameters"],eventTs: ["eventTs"],// getById field sets (reuse the same fields - all queries use `FROM events_<type> e`)diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 8b742aa1da..804bf7dce2 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -72,6 +72,7 @@ import {buildEventsFullTableSplitQuery,type QueryWithParams,type SessionEventsMetricsRow,+ type FieldSetName,OrderByEntry,} from "../queries/clickhouse-sql/event-query-builder";import { type EventsObservationPublic } from "../queries/createGenerationsQuery";@@ -872,6 +873,8 @@ export const OBSERVATION_FIELD_GROUPS = ["usage", // usageDetails, costDetails, totalCost"prompt", // promptId, promptName, promptVersion"metrics", // latency, timeToFirstToken+ "tools", // toolDefinitions, toolCalls, toolCallNames+ "trace_context", // tags, release, traceName, usagePricingTierName] as const;export type ObservationFieldGroup = (typeof OBSERVATION_FIELD_GROUPS)[number];@@ -2981,11 +2984,36 @@ export const getEventsForBlobStorageExport = function (projectId: string,minTimestamp: Date,maxTimestamp: Date,+ fieldGroups: ObservationFieldGroup[] = [...OBSERVATION_FIELD_GROUPS],) {- const queryBuilder = new EventsQueryBuilder({ projectId })- .selectFieldSet("export")- .selectIO(false) // Full I/O, no truncation- .selectFieldSet("metadata")+ const queryBuilder = new EventsQueryBuilder({ projectId });++ // core is always required (provides id, trace_id, start/end_time used for cursor and deduplication)+ const effectiveGroups = fieldGroups.includes("core")+ ? fieldGroups+ : (["core", ...fieldGroups] as ObservationFieldGroup[]);++ // model_export must be selected whenever model or usage is requested:+ // - model group: include model identification fields in the output+ // - usage group (without model): pricing enrichment needs model_id for the+ // lookup; the field is dropped afterward by enrichObservationStream+ const needsModelFields =+ fieldGroups.includes("model") || fieldGroups.includes("usage");++ for (const group of effectiveGroups) {+ if (group === "io") {+ queryBuilder.selectIO(false); // Full I/O, no truncation+ } else if (group !== "model") {+ // model_export is selected below via needsModelFields to avoid double-selecting+ queryBuilder.selectFieldSet(group as FieldSetName);+ }+ }++ if (needsModelFields) {+ queryBuilder.selectFieldSet("model_export");+ }++ queryBuilder.whereRaw("e.start_time >= {minTimestamp: DateTime64(3)} AND e.start_time <= {maxTimestamp: DateTime64(3)}",{diff --git a/web/src/__tests__/blob-storage-form-field-groups.clienttest.ts b/web/src/__tests__/blob-storage-form-field-groups.clienttest.tsnew file mode 100644index 0000000000..58e54019dc--- /dev/null+++ b/web/src/__tests__/blob-storage-form-field-groups.clienttest.ts@@ -0,0 +1,86 @@+import { renderHook, act } from "@testing-library/react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ type BlobStorageIntegrationFormSchema,+ blobStorageIntegrationFormSchema,+} from "@/src/features/blobstorage-integration/types";+import {+ AnalyticsIntegrationExportSource,+ BLOB_EXPORT_FIELD_GROUPS,+ BlobStorageExportMode,+ BlobStorageIntegrationFileType,+ BlobStorageIntegrationType,+} from "@langfuse/shared";++const VALID_BASE: BlobStorageIntegrationFormSchema = {+ type: BlobStorageIntegrationType.S3,+ bucketName: "my-bucket",+ region: "us-east-1",+ exportFrequency: "daily",+ enabled: true,+ forcePathStyle: false,+ fileType: BlobStorageIntegrationFileType.JSONL,+ exportMode: BlobStorageExportMode.FULL_HISTORY,+ exportSource: AnalyticsIntegrationExportSource.EVENTS,+ exportFieldGroups: [...BLOB_EXPORT_FIELD_GROUPS],+ compressed: true,+ endpoint: null,+ accessKeyId: "",+ secretAccessKey: null,+ prefix: "",+ exportStartDate: null,+};++describe("blob storage form — exportFieldGroups validation", () => {+ it.each([+ [AnalyticsIntegrationExportSource.EVENTS, []],+ [AnalyticsIntegrationExportSource.EVENTS, ["basic", "io"]],+ [AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS, []],+ [+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,+ ["basic", "io"],+ ],+ ] as const)(+ "blocks submission when exportSource is %s and core is absent (groups: %s)",+ async (source, exportFieldGroups) => {+ const { result } = renderHook(() =>+ useForm({+ resolver: zodResolver(blobStorageIntegrationFormSchema),+ defaultValues: {+ ...VALID_BASE,+ exportSource: source,+ exportFieldGroups: [...exportFieldGroups],+ },+ }),+ );++ const onSubmit = vi.fn();+ await act(async () => {+ await result.current.handleSubmit(onSubmit)();+ });++ expect(onSubmit).not.toHaveBeenCalled();+ },+ );++ it("allows submission when exportSource is TRACES_OBSERVATIONS regardless of exportFieldGroups", async () => {+ const { result } = renderHook(() =>+ useForm({+ resolver: zodResolver(blobStorageIntegrationFormSchema),+ defaultValues: {+ ...VALID_BASE,+ exportSource: AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ exportFieldGroups: [],+ },+ }),+ );++ const onSubmit = vi.fn();+ await act(async () => {+ await result.current.handleSubmit(onSubmit)();+ });++ expect(onSubmit).toHaveBeenCalledOnce();+ });+});diff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.tsindex 2695aa70ea..d17eeaa57e 100644--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts@@ -367,6 +367,44 @@ describe("Blob Storage Integration tRPC Router", () => {]);});+ it("rejects submission when core group is absent (exportSource EVENTS)", async () => {+ const { caller, project } = await prepare();++ await expect(+ caller.blobStorageIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportFieldGroups: ["basic", "io"],+ }),+ ).rejects.toThrow();+ });++ it("rejects empty exportFieldGroups when exportSource is TRACES_OBSERVATIONS_EVENTS", async () => {+ const { caller, project } = await prepare();++ await expect(+ caller.blobStorageIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "TRACES_OBSERVATIONS_EVENTS" as const,+ exportFieldGroups: [],+ }),+ ).rejects.toThrow();+ });++ it("accepts empty exportFieldGroups when exportSource is TRACES_OBSERVATIONS", async () => {+ const { caller, project } = await prepare();++ await expect(+ caller.blobStorageIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "TRACES_OBSERVATIONS" as const,+ exportFieldGroups: [],+ }),+ ).resolves.not.toThrow();+ });+it("overwrites stored subset when a new subset is submitted", async () => {const { caller, project } = await prepare();diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex 3812491958..eed52769a5 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -7,7 +7,10 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import { blobStorageIntegrationFormSchemaBase } from "@/src/features/blobstorage-integration/types";-import { validateAzureContainerName } from "@/src/features/blobstorage-integration/validation";+import {+ validateAzureContainerName,+ validateExportFieldGroups,+} from "@/src/features/blobstorage-integration/validation";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";import { TRPCError } from "@trpc/server";import {@@ -70,7 +73,8 @@ export const blobStorageIntegrationRouter = createTRPCRouter({.input(blobStorageIntegrationFormSchemaBase.extend({ projectId: z.string() })- .superRefine(validateAzureContainerName),+ .superRefine(validateAzureContainerName)+ .superRefine(validateExportFieldGroups),).mutation(async ({ input, ctx }) => {try {diff --git a/web/src/features/blobstorage-integration/types.ts b/web/src/features/blobstorage-integration/types.tsindex 60744180af..93923189c2 100644--- a/web/src/features/blobstorage-integration/types.ts+++ b/web/src/features/blobstorage-integration/types.ts@@ -6,7 +6,10 @@ import {AnalyticsIntegrationExportSource,BLOB_EXPORT_FIELD_GROUPS,} from "@langfuse/shared";-import { validateAzureContainerName } from "@/src/features/blobstorage-integration/validation";+import {+ validateAzureContainerName,+ validateExportFieldGroups,+} from "@/src/features/blobstorage-integration/validation";export const blobStorageIntegrationFormSchemaBase = z.object({type: z.enum(BlobStorageIntegrationType),@@ -37,13 +40,14 @@ export const blobStorageIntegrationFormSchemaBase = z.object({.default(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),exportFieldGroups: z.array(z.enum(BLOB_EXPORT_FIELD_GROUPS))- .min(1, { message: "At least one field group must be selected" }).default([...BLOB_EXPORT_FIELD_GROUPS]),compressed: z.boolean().default(true),});export const blobStorageIntegrationFormSchema =- blobStorageIntegrationFormSchemaBase.superRefine(validateAzureContainerName);+ blobStorageIntegrationFormSchemaBase+ .superRefine(validateAzureContainerName)+ .superRefine(validateExportFieldGroups);export type BlobStorageIntegrationFormSchema = z.infer<typeof blobStorageIntegrationFormSchemadiff --git a/web/src/features/blobstorage-integration/validation.ts b/web/src/features/blobstorage-integration/validation.tsindex 7b5e460480..a4a78fa891 100644--- a/web/src/features/blobstorage-integration/validation.ts+++ b/web/src/features/blobstorage-integration/validation.ts@@ -1,4 +1,25 @@import type { z } from "zod";+import { AnalyticsIntegrationExportSource } from "@langfuse/shared";++export function validateExportFieldGroups(+ data: { exportSource: string; exportFieldGroups: unknown[] },+ ctx: z.RefinementCtx,+) {+ const requiresFieldGroups =+ data.exportSource === AnalyticsIntegrationExportSource.EVENTS ||+ data.exportSource ===+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS;++ if (!requiresFieldGroups) return;++ if (!data.exportFieldGroups.includes("core")) {+ ctx.addIssue({+ code: "custom",+ message: "The Core field group is required",+ path: ["exportFieldGroups"],+ });+ }+}/*** Azure container names must be 3-63 characters, lowercase letters, numbers,diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsxindex 8a31367c42..0c6f1c4c14 100644--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx@@ -14,6 +14,7 @@ import {import { Input } from "@/src/components/ui/input";import { PasswordInput } from "@/src/components/ui/password-input";import { Switch } from "@/src/components/ui/switch";+import { Checkbox } from "@/src/components/ui/checkbox";import {Select,SelectContent,@@ -51,6 +52,7 @@ import {AnalyticsIntegrationExportSource,type BlobStorageIntegration,EXPORT_SOURCE_OPTIONS,+ EXPORT_FIELD_GROUP_OPTIONS,BLOB_EXPORT_FIELD_GROUPS,type BlobExportFieldGroup,} from "@langfuse/shared";@@ -305,11 +307,17 @@ const BlobStorageIntegrationSettingsForm = ({// eslint-disable-next-line react-hooks/exhaustive-deps}, [state]);+ const watchedExportSource = blobStorageForm.watch("exportSource");+ const watchedExportMode = blobStorageForm.watch("exportMode");+const utils = api.useUtils();const mut = api.blobStorageIntegration.update.useMutation({onSuccess: () => {utils.blobStorageIntegration.invalidate();},+ onError: (error) => {+ showErrorToast("Failed to save integration", error.message);+ },});const mutDelete = api.blobStorageIntegration.delete.useMutation({onSuccess: () => {@@ -723,8 +731,96 @@ const BlobStorageIntegrationSettingsForm = ({/>)}- {blobStorageForm.watch("exportMode") ===- BlobStorageExportMode.FROM_CUSTOM_DATE && (+ {isBetaEnabled &&+ (watchedExportSource === AnalyticsIntegrationExportSource.EVENTS ||+ watchedExportSource ===+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS) && (+ <FormField+ control={blobStorageForm.control}+ name="exportFieldGroups"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Export Field Groups</FormLabel>+ <FormDescription>+ Choose which field groups to include in the enriched+ observations export. Deselect large groups (e.g. Input /+ Output) to reduce export size, or privacy-sensitive groups+ (e.g. Metadata) to avoid storing user data. Scores are+ always exported.+ {watchedExportSource ===+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS &&+ " Traces and legacy observations are also exported in full."}+ </FormDescription>+ <div className="mt-2 space-y-2">+ {EXPORT_FIELD_GROUP_OPTIONS.map((option) => {+ const isCore = option.value === "core";+ return (+ <div+ key={option.value}+ className="flex items-start gap-2"+ >+ <Checkbox+ id={`field-group-${option.value}`}+ checked={+ isCore+ ? true+ : (field.value ?? []).includes(option.value)+ }+ disabled={isCore}+ onCheckedChange={+ isCore+ ? undefined+ : (checked) => {+ const current = field.value ?? [];+ const next =+ checked === true+ ? current.includes(option.value)+ ? current+ : [...current, option.value]+ : current.filter(+ (v: BlobExportFieldGroup) =>+ v !== option.value,+ );+ field.onChange(next);+ }+ }+ />+ <label+ htmlFor={`field-group-${option.value}`}+ className={+ isCore+ ? "space-y-0.5"+ : "cursor-pointer space-y-0.5"+ }+ >+ <div className="text-sm leading-none font-medium">+ {option.label}+ {isCore && (+ <span className="text-muted-foreground ml-1 font-normal">+ (required)+ </span>+ )}+ </div>+ <div className="text-muted-foreground text-xs">+ {option.description}+ </div>+ </label>+ </div>+ );+ })}+ </div>+ <FormMessage>+ {+ blobStorageForm.formState.errors.exportFieldGroups+ ?.message+ }+ </FormMessage>+ </FormItem>+ )}+ />+ )}++ {watchedExportMode === BlobStorageExportMode.FROM_CUSTOM_DATE && (<FormFieldcontrol={blobStorageForm.control}name="exportStartDate"diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.tsindex e36069f374..3b18bad08a 100644--- a/worker/src/__tests__/batchExport.test.ts+++ b/worker/src/__tests__/batchExport.test.ts@@ -4277,4 +4277,135 @@ maybeDescribe("getEventsForBlobStorageExport", () => {// --- total_cost: ALIAS for cost_details['total'] → 0.03 (set in fixture) ---expect(row.total_cost).toBeCloseTo(0.03);});++ it("should return all columns when all field groups are selected", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const now = Date.now();+ const traceId = randomUUID();++ const event = createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "all-groups-event",+ start_time: now * 1000,+ });++ await createEventsCh([event]);++ const stream = getEventsForBlobStorageExport(+ projectId,+ new Date(now - 60 * 60 * 1000),+ new Date(now + 60 * 60 * 1000),+ [+ "core",+ "basic",+ "time",+ "io",+ "metadata",+ "model",+ "usage",+ "prompt",+ "metrics",+ "tools",+ "trace_context",+ ],+ );++ const rows: Record<string, unknown>[] = [];+ for await (const row of stream) {+ rows.push(row);+ }++ expect(rows).toHaveLength(1);+ const expectedColumns = [+ "id",+ "trace_id",+ "project_id",+ "start_time",+ "end_time",+ "name",+ "type",+ "environment",+ "version",+ "user_id",+ "session_id",+ "level",+ "status_message",+ "prompt_name",+ "prompt_id",+ "prompt_version",+ "model_id",+ "provided_model_name",+ "model_parameters",+ "usage_details",+ "cost_details",+ "total_cost",+ "completion_start_time",+ "latency",+ "time_to_first_token",+ "tags",+ "release",+ "trace_name",+ "parent_observation_id",+ "bookmarked",+ "public",+ "created_at",+ "updated_at",+ "tool_definitions",+ "tool_calls",+ "tool_call_names",+ "usage_pricing_tier_name",+ "input",+ "output",+ "metadata",+ ].sort();+ expect(Object.keys(rows[0]).sort()).toEqual(expectedColumns);+ });++ it("should return only columns for the requested field groups subset", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const now = Date.now();+ const traceId = randomUUID();++ const event = createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "SPAN",+ name: "subset-groups-event",+ start_time: now * 1000,+ input: "hello",+ output: "world",+ });++ await createEventsCh([event]);++ const stream = getEventsForBlobStorageExport(+ projectId,+ new Date(now - 60 * 60 * 1000),+ new Date(now + 60 * 60 * 1000),+ ["core", "io"],+ );++ const rows: Record<string, unknown>[] = [];+ for await (const row of stream) {+ rows.push(row);+ }++ expect(rows).toHaveLength(1);+ const expectedColumns = [+ "id",+ "trace_id",+ "start_time",+ "end_time",+ "project_id",+ "parent_observation_id",+ "type",+ "input",+ "output",+ ].sort();+ expect(Object.keys(rows[0]).sort()).toEqual(expectedColumns);+ expect(rows[0].input).toBe("hello");+ expect(rows[0].output).toBe("world");+ });});diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex b290139717..6cee6a1160 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -379,6 +379,86 @@ describe("BlobStorageIntegrationProcessingJob", () => {}});+ it("should exclude columns for deselected exportFieldGroups", async () => {+ // Regression test for two known ClickHouse/enrichment leaks:+ // 1. ClickHouse always returns {} for unselected Map columns (metadata)+ // 2. enrichObservationStream was writing latency:null even when metrics not selected+ 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;++ 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",+ exportFieldGroups: ["core", "io"],+ nextSyncAt: twoHoursAgo,+ lastSyncAt: twoHoursAgo,+ compressed: false,+ fileType: BlobStorageIntegrationFileType.JSONL,+ },+ });++ const traceId = randomUUID();+ const event = createEvent({+ project_id: projectId,+ trace_id: traceId,+ type: "GENERATION",+ name: "Test Event",+ start_time: dataTime * 1000,+ end_time: (dataTime + 5000) * 1000,+ metadata: { secret: "should-not-appear" },+ metadata_names: ["secret"],+ metadata_values: ["should-not-appear"],+ });++ await createEventsCh([event]);++ await handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job);++ const files = await s3StorageService.listFiles(s3Prefix);+ const eventFile = files.find((f) => f.file.includes("/observations_v2/"));+ expect(eventFile).toBeDefined();++ if (eventFile) {+ const content = await s3StorageService.download(eventFile.file);+ const row = JSON.parse(content.trim().split("\n")[0]);++ // core + io fields should be present+ expect(row).toHaveProperty("id");+ expect(row).toHaveProperty("trace_id");+ expect(row).toHaveProperty("input");+ expect(row).toHaveProperty("output");++ // metadata group not selected → must not leak even as {}+ expect(row).not.toHaveProperty("metadata");++ // metrics group not selected → latency/time_to_first_token must not appear+ expect(row).not.toHaveProperty("latency");+ expect(row).not.toHaveProperty("time_to_first_token");++ // non-selected groups must not appear+ expect(row).not.toHaveProperty("name");+ expect(row).not.toHaveProperty("level");+ expect(row).not.toHaveProperty("usage_details");+ }+ });+it("should respect export frequency when setting nextSyncAt", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/__tests__/enrichObservationStream.unit.test.ts b/worker/src/__tests__/enrichObservationStream.unit.test.tsnew file mode 100644index 0000000000..b378e76838--- /dev/null+++ b/worker/src/__tests__/enrichObservationStream.unit.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const mod =+ await importOriginal<typeof import("@langfuse/shared/src/server")>();+ return {+ ...mod,+ createModelCache: vi.fn().mockReturnValue({+ getModel: vi.fn().mockResolvedValue(null),+ }),+ enrichObservationWithModelData: vi.fn().mockReturnValue({+ modelId: null,+ inputPrice: null,+ outputPrice: null,+ totalPrice: null,+ }),+ };+});++import { enrichObservationStream } from "../features/blobstorage/handleBlobStorageIntegrationProjectJob";+import type { ObservationFieldGroup } from "@langfuse/shared/src/server";++async function* rowStream(+ rows: Record<string, unknown>[],+): AsyncGenerator<Record<string, unknown>> {+ for (const row of rows) yield row;+}++async function collect(+ gen: AsyncGenerator<Record<string, unknown>>,+): Promise<Record<string, unknown>[]> {+ const out: Record<string, unknown>[] = [];+ for await (const row of gen) out.push(row);+ return out;+}++describe("enrichObservationStream field group filtering", () => {+ it("does not add latency/time_to_first_token when row has no latency (metrics not selected)", async () => {+ // Simulates a row from ClickHouse where metrics group was not SELECTed —+ // latency and time_to_first_token are absent from the row entirely.+ const rows = [{ id: "obs-1" }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", true),+ );++ expect(results[0]).not.toHaveProperty("latency");+ expect(results[0]).not.toHaveProperty("time_to_first_token");+ });++ it("converts latency independently of time_to_first_token", async () => {+ // Guards are independent: a row with latency but no time_to_first_token+ // should convert latency and leave time_to_first_token out entirely.+ const rows = [{ id: "obs-1", latency: 2000 }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", true),+ );++ expect(results[0].latency).toBe(2);+ expect(results[0]).not.toHaveProperty("time_to_first_token");+ });++ it("removes metadata when ClickHouse returns empty map and metadata is not selected", async () => {+ // Simulates ClickHouse returning {} for an unselected Map column.+ const rows = [{ id: "obs-1", metadata: {} }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", false, [+ "core" as ObservationFieldGroup,+ ]),+ );++ expect(results[0]).not.toHaveProperty("metadata");+ });++ it("does not add pricing fields when usage group is not selected", async () => {+ const rows = [{ id: "obs-1" }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", false, [+ "core" as ObservationFieldGroup,+ ]),+ );++ expect(results[0]).not.toHaveProperty("model_id");+ expect(results[0]).not.toHaveProperty("input_price");+ expect(results[0]).not.toHaveProperty("output_price");+ expect(results[0]).not.toHaveProperty("total_price");+ });++ it("adds pricing fields but drops all model_export columns when usage is selected without model", async () => {+ // ClickHouse fetches model_export (model_id, provided_model_name,+ // model_parameters) whenever usage is requested so the pricing lookup has+ // data. All three must be removed from the output when model is not selected.+ const rows = [+ {+ id: "obs-1",+ model_id: "gpt-4",+ provided_model_name: "gpt-4",+ model_parameters: { temperature: 0.7 },+ },+ ];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", false, [+ "core" as ObservationFieldGroup,+ "usage" as ObservationFieldGroup,+ ]),+ );++ expect(results[0]).not.toHaveProperty("model_id");+ expect(results[0]).not.toHaveProperty("provided_model_name");+ expect(results[0]).not.toHaveProperty("model_parameters");+ expect(results[0]).toHaveProperty("input_price");+ expect(results[0]).toHaveProperty("output_price");+ expect(results[0]).toHaveProperty("total_price");+ });++ it("preserves model_id when both model and usage groups are selected", async () => {+ const rows = [{ id: "obs-1", model_id: "gpt-4" }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", false, [+ "core" as ObservationFieldGroup,+ "model" as ObservationFieldGroup,+ "usage" as ObservationFieldGroup,+ ]),+ );++ expect(results[0]).toHaveProperty("model_id");+ expect(results[0]).toHaveProperty("input_price");+ expect(results[0]).toHaveProperty("output_price");+ expect(results[0]).toHaveProperty("total_price");+ });++ it("adds model pricing fields when fieldGroups is undefined (legacy v3 path)", async () => {+ // Legacy path: fieldGroups undefined means all fields included; model_id+ // passes through from the source row unchanged.+ const rows = [{ id: "obs-1", model_id: "gpt-4" }];+ const results = await collect(+ enrichObservationStream(rowStream(rows), "project-1", "model_id", false),+ );++ expect(results[0]).toHaveProperty("model_id");+ expect(results[0]).toHaveProperty("input_price");+ expect(results[0]).toHaveProperty("output_price");+ expect(results[0]).toHaveProperty("total_price");+ });+});diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex addf60d9f0..a7af350408 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -13,6 +13,8 @@ import {getTracesForBlobStorageExport,getScoresForBlobStorageExport,getEventsForBlobStorageExport,+ OBSERVATION_FIELD_GROUPS,+ type ObservationFieldGroup,getCurrentSpan,BlobStorageIntegrationProcessingQueue,queryClickhouse,@@ -33,31 +35,53 @@ import { env } from "../../env";export const BLOB_STORAGE_LAG_BUFFER_MS = 20 * 60 * 1000; // 20-minute lag buffer-async function* enrichObservationStream(+export async function* enrichObservationStream(stream: AsyncGenerator<Record<string, unknown>>,projectId: string,modelIdField: string,convertLatencyToSeconds: boolean,+ fieldGroups?: ObservationFieldGroup[],): AsyncGenerator<Record<string, unknown>> {const { getModel } = createModelCache(projectId);+ const includePricing = !fieldGroups || fieldGroups.includes("usage");+ const includeModelId = !fieldGroups || fieldGroups.includes("model");+for await (const row of stream) {- const modelId = row[modelIdField] as string | null | undefined;- const model = await getModel(modelId);- const pricing = enrichObservationWithModelData(model);-- const enriched: Record<string, unknown> = {- ...row,- model_id: pricing.modelId ?? modelId ?? null,- input_price: pricing.inputPrice,- output_price: pricing.outputPrice,- total_price: pricing.totalPrice,- };+ const enriched: Record<string, unknown> = { ...row };++ if (includePricing) {+ const modelId = row[modelIdField] as string | null | undefined;+ const model = await getModel(modelId);+ const pricing = enrichObservationWithModelData(model);+ enriched.input_price = pricing.inputPrice;+ enriched.output_price = pricing.outputPrice;+ enriched.total_price = pricing.totalPrice;+ }++ // model_export (provided_model_name, model_id, model_parameters) is fetched+ // whenever usage OR model is requested — usage needs model_id for the+ // pricing lookup. Drop all three when the model group was not requested so+ // they don't leak into a usage-only export.+ if (!includeModelId) {+ delete enriched[modelIdField];+ delete enriched.provided_model_name;+ delete enriched.model_parameters;+ }++ // ClickHouse returns {} for Map columns even when not SELECTed — drop it+ // when the metadata group was not requested.+ if (fieldGroups && !fieldGroups.includes("metadata")) {+ delete enriched.metadata;+ }- if (convertLatencyToSeconds) {+ if (convertLatencyToSeconds && row.latency !== undefined) {const latency = row.latency as number | null;- const ttft = row.time_to_first_token as number | null;enriched.latency = latency != null ? latency / 1000 : null;+ }++ if (convertLatencyToSeconds && row.time_to_first_token !== undefined) {+ const ttft = row.time_to_first_token as number | null;enriched.time_to_first_token = ttft != null ? ttft / 1000 : null;}@@ -201,6 +225,7 @@ const processBlobStorageExport = async (config: {fileType: BlobStorageIntegrationFileType;compressed: boolean;convertV4LatencyToSeconds: boolean;+ exportFieldGroups?: ObservationFieldGroup[];}) => {logger.info(`[BLOB INTEGRATION] Processing ${config.table} export for project ${config.projectId}`,@@ -237,6 +262,11 @@ const processBlobStorageExport = async (config: {: blobStorageProps.contentType;// Fetch data based on table type+ const exportFieldGroups =+ config.exportFieldGroups && config.exportFieldGroups.length > 0+ ? config.exportFieldGroups+ : [...OBSERVATION_FIELD_GROUPS];+let dataStream: AsyncGenerator<Record<string, unknown>>;switch (config.table) {@@ -272,10 +302,12 @@ const processBlobStorageExport = async (config: {config.projectId,config.minTimestamp,config.maxTimestamp,+ exportFieldGroups,),config.projectId,"model_id",config.convertV4LatencyToSeconds,+ exportFieldGroups,);break;default:@@ -424,6 +456,8 @@ export const handleBlobStorageIntegrationProjectJob = async (fileType: blobStorageIntegration.fileType,compressed: blobStorageIntegration.compressed,convertV4LatencyToSeconds,+ exportFieldGroups:+ blobStorageIntegration.exportFieldGroups as ObservationFieldGroup[],};// Check if this project should only export traces (legacy behavior via env var)