Skip to content

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

feat: add events table to integration exports (#11659) (#11968)

Hassieb Pakzad8475328e23ca
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 6e5e038130..e26bd3b3e5 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -136,6 +136,13 @@ export const BlobStorageExportMode = {
} as const;
export type BlobStorageExportMode =
(typeof BlobStorageExportMode)[keyof typeof BlobStorageExportMode];
+export const AnalyticsIntegrationExportSource = {
+ TRACES_OBSERVATIONS: "TRACES_OBSERVATIONS",
+ TRACES_OBSERVATIONS_EVENTS: "TRACES_OBSERVATIONS_EVENTS",
+ EVENTS: "EVENTS",
+} as const;
+export type AnalyticsIntegrationExportSource =
+ (typeof AnalyticsIntegrationExportSource)[keyof typeof AnalyticsIntegrationExportSource];
export const DashboardWidgetViews = {
TRACES: "TRACES",
OBSERVATIONS: "OBSERVATIONS",
@@ -360,6 +367,7 @@ export type BlobStorageIntegration = {
file_type: Generated<BlobStorageIntegrationFileType>;
export_mode: Generated<BlobStorageExportMode>;
export_start_date: Timestamp | null;
+ export_source: Generated<AnalyticsIntegrationExportSource>;
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
@@ -675,6 +683,7 @@ export type MixpanelIntegration = {
last_sync_at: Timestamp | null;
enabled: boolean;
created_at: Generated<Timestamp>;
+ export_source: Generated<AnalyticsIntegrationExportSource>;
};
export type Model = {
id: string;
@@ -748,6 +757,7 @@ export type PosthogIntegration = {
last_sync_at: Timestamp | null;
enabled: boolean;
created_at: Generated<Timestamp>;
+ export_source: Generated<AnalyticsIntegrationExportSource>;
};
export type Price = {
id: string;
diff --git a/packages/shared/prisma/migrations/20260122124934_add_export_source_to_analytics_integrations/migration.sql b/packages/shared/prisma/migrations/20260122124934_add_export_source_to_analytics_integrations/migration.sql
new file mode 100644
index 0000000000..5a6c258cca
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260122124934_add_export_source_to_analytics_integrations/migration.sql
@@ -0,0 +1,11 @@
+-- CreateEnum
+CREATE TYPE "AnalyticsIntegrationExportSource" AS ENUM ('TRACES_OBSERVATIONS', 'TRACES_OBSERVATIONS_EVENTS', 'EVENTS');
+
+-- AlterTable
+ALTER TABLE "blob_storage_integrations" ADD COLUMN "export_source" "AnalyticsIntegrationExportSource" NOT NULL DEFAULT 'TRACES_OBSERVATIONS';
+
+-- AlterTable
+ALTER TABLE "mixpanel_integrations" ADD COLUMN "export_source" "AnalyticsIntegrationExportSource" NOT NULL DEFAULT 'TRACES_OBSERVATIONS';
+
+-- AlterTable
+ALTER TABLE "posthog_integrations" ADD COLUMN "export_source" "AnalyticsIntegrationExportSource" NOT NULL DEFAULT 'TRACES_OBSERVATIONS';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 6083edf283..0686f8c123 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1063,25 +1063,27 @@ model SsoConfig {
}
model PosthogIntegration {
- projectId String @id @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- encryptedPosthogApiKey String @map("encrypted_posthog_api_key")
- posthogHostName String @map("posthog_host_name")
- lastSyncAt DateTime? @map("last_sync_at")
+ projectId String @id @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ encryptedPosthogApiKey String @map("encrypted_posthog_api_key")
+ posthogHostName String @map("posthog_host_name")
+ lastSyncAt DateTime? @map("last_sync_at")
enabled Boolean
- createdAt DateTime @default(now()) @map("created_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ exportSource AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
@@map("posthog_integrations")
}
model MixpanelIntegration {
- projectId String @id @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- encryptedMixpanelProjectToken String @map("encrypted_mixpanel_project_token")
- mixpanelRegion String @map("mixpanel_region")
- lastSyncAt DateTime? @map("last_sync_at")
+ projectId String @id @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ encryptedMixpanelProjectToken String @map("encrypted_mixpanel_project_token")
+ mixpanelRegion String @map("mixpanel_region")
+ lastSyncAt DateTime? @map("last_sync_at")
enabled Boolean
- createdAt DateTime @default(now()) @map("created_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ exportSource AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
@@map("mixpanel_integrations")
}
@@ -1101,13 +1103,14 @@ model BlobStorageIntegration {
forcePathStyle Boolean @map("force_path_style")
// Integration Config
- nextSyncAt DateTime? @map("next_sync_at")
- lastSyncAt DateTime? @map("last_sync_at")
+ nextSyncAt DateTime? @map("next_sync_at")
+ lastSyncAt DateTime? @map("last_sync_at")
enabled Boolean
- exportFrequency String @map("export_frequency")
- fileType BlobStorageIntegrationFileType @default(CSV) @map("file_type")
- exportMode BlobStorageExportMode @default(FULL_HISTORY) @map("export_mode")
- exportStartDate DateTime? @map("export_start_date")
+ exportFrequency String @map("export_frequency")
+ fileType BlobStorageIntegrationFileType @default(CSV) @map("file_type")
+ exportMode BlobStorageExportMode @default(FULL_HISTORY) @map("export_mode")
+ exportStartDate DateTime? @map("export_start_date")
+ exportSource AnalyticsIntegrationExportSource @default(TRACES_OBSERVATIONS) @map("export_source")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
@@ -1139,6 +1142,14 @@ enum BlobStorageExportMode {
@@map("BlobStorageExportMode")
}
+enum AnalyticsIntegrationExportSource {
+ TRACES_OBSERVATIONS
+ TRACES_OBSERVATIONS_EVENTS
+ EVENTS
+
+ @@map("AnalyticsIntegrationExportSource")
+}
+
model BatchExport {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
diff --git a/packages/shared/src/features/analytics-integrations/index.ts b/packages/shared/src/features/analytics-integrations/index.ts
new file mode 100644
index 0000000000..596c6610be
--- /dev/null
+++ b/packages/shared/src/features/analytics-integrations/index.ts
@@ -0,0 +1,32 @@
+// Export source options for analytics integrations (PostHog, Mixpanel, Blob Storage)
+// This is a client-safe file that can be imported from @langfuse/shared
+
+import { AnalyticsIntegrationExportSource } from "@prisma/client";
+
+export const EXPORT_SOURCE_OPTIONS: Array<{
+ value: AnalyticsIntegrationExportSource;
+ label: string;
+ description: string;
+}> = [
+ {
+ value: "TRACES_OBSERVATIONS" as const,
+ label: "Traces and observations (legacy)",
+ description:
+ "Export traces, observations and scores. This is the legacy behavior prior to tracking traces and observations in separate tables. It is recommended to use the enriched observations option instead.",
+ },
+ {
+ value: "TRACES_OBSERVATIONS_EVENTS" as const,
+ label: "Traces and observations (legacy) and enriched observations",
+ description:
+ "Export traces, observations, scores and enriched observations. This exports both the legacy data source (traces, observations) and the new one (enriched observations) and essentially exports duplicate data. Therefore, it should only be used to migrate existing integrations to the new recommended enriched observations and check validity of the data for downstream consumers of the export data.",
+ },
+ {
+ value: "EVENTS" as const,
+ label: "Enriched observations (recommended)",
+ description:
+ "Export enriched observations and scores. This is the recommended data source for integrations and will be the default for new integrations.",
+ },
+] as const;
+
+export type ExportSourceOption = (typeof EXPORT_SOURCE_OPTIONS)[number];
+export type ExportSourceValue = ExportSourceOption["value"];
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index a54c31793f..a7405b8981 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -93,3 +93,6 @@ export * from "./domain";
// io representation
export * from "./utils/IORepresentation";
+
+// analytics integrations (client-safe)
+export * from "./features/analytics-integrations";
diff --git a/packages/shared/src/interfaces/tableNames.ts b/packages/shared/src/interfaces/tableNames.ts
index 1f4e3ba994..d5a884cb0d 100644
--- a/packages/shared/src/interfaces/tableNames.ts
+++ b/packages/shared/src/interfaces/tableNames.ts
@@ -8,6 +8,7 @@ export enum BatchTableNames {
Sessions = "sessions",
Traces = "traces",
Observations = "observations",
+ Events = "events",
DatasetRunItems = "dataset_run_items",
DatasetItems = "dataset_items",
AuditLogs = "audit_logs",
diff --git a/packages/shared/src/server/analytics-integrations/types.ts b/packages/shared/src/server/analytics-integrations/types.ts
index 6a0b6204e3..53474b7b62 100644
--- a/packages/shared/src/server/analytics-integrations/types.ts
+++ b/packages/shared/src/server/analytics-integrations/types.ts
@@ -74,3 +74,32 @@ export type AnalyticsScoreEvent = {
posthog_session_id?: unknown;
mixpanel_session_id?: unknown;
};
+
+export type AnalyticsObservationEvent = {
+ langfuse_id: unknown;
+ timestamp: unknown;
+ langfuse_observation_name?: unknown;
+ langfuse_trace_name?: unknown;
+ langfuse_trace_id?: unknown;
+ langfuse_url?: unknown;
+ langfuse_user_url?: unknown;
+ langfuse_cost_usd?: unknown;
+ langfuse_input_units?: unknown;
+ langfuse_output_units?: unknown;
+ langfuse_total_units?: unknown;
+ langfuse_session_id?: unknown;
+ langfuse_project_id?: unknown;
+ langfuse_user_id?: unknown;
+ langfuse_latency?: unknown;
+ langfuse_time_to_first_token?: unknown;
+ langfuse_release?: unknown;
+ langfuse_version?: unknown;
+ langfuse_model?: unknown;
+ langfuse_level?: unknown;
+ langfuse_type?: unknown;
+ langfuse_tags?: unknown;
+ langfuse_environment?: unknown;
+ langfuse_event_version?: unknown;
+ posthog_session_id?: unknown;
+ mixpanel_session_id?: unknown;
+};
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.ts
index 6ac022f472..c22d3c3b89 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
@@ -65,6 +65,14 @@ const EVENTS_FIELDS = {
input: "e.input",
output: "e.output",
metadata: "mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadata",
+ metadataDirect: "e.metadata as metadata", // Direct JSON column access for exports
+
+ // Trace-level denormalized fields
+ tags: "e.tags as tags",
+ release: "e.release as release",
+
+ // Model ID with different alias for exports
+ modelId: 'e.model_id as "model_id"',
// Calculated fields
latency:
@@ -181,6 +189,39 @@ const FIELD_SETS = {
usage: ["usageDetails", "costDetails", "totalCost"],
prompt: ["promptId", "promptName", "promptVersion"],
metrics: ["latency", "timeToFirstToken"],
+
+ // Batch export field set (all fields needed for CSV/JSON exports)
+ export: [
+ "id",
+ "traceId",
+ "projectId",
+ "startTime",
+ "endTime",
+ "name",
+ "type",
+ "environment",
+ "version",
+ "userId",
+ "sessionId",
+ "level",
+ "statusMessage",
+ "promptName",
+ "promptId",
+ "promptVersion",
+ "modelId",
+ "providedModelName",
+ "modelParameters",
+ "usageDetails",
+ "costDetails",
+ "totalCost",
+ "completionStartTime",
+ "latency",
+ "timeToFirstToken",
+ "tags",
+ "release",
+ "traceName",
+ "parentObservationId",
+ ],
} as const;
export type FieldSetName = keyof typeof FIELD_SETS;
@@ -262,6 +303,7 @@ export type NoProjectIdType = typeof NoProjectId;
abstract class AbstractQueryBuilder {
protected whereClauses: string[] = [];
protected orderByClause: string = "";
+ protected limitByClause: string = "";
protected limitClause: string = "";
protected params: Record<string, any> = {};
@@ -321,6 +363,22 @@ abstract class AbstractQueryBuilder {
return this;
}
+ /**
+ * Add LIMIT 1 BY for ClickHouse deduplication
+ * This is applied before the regular LIMIT clause
+ *
+ * @param columns - Columns to deduplicate by
+ * @example
+ * .limitBy("e.span_id", "e.project_id")
+ */
+ limitBy(...columns: string[]): this {
+ if (columns.length > 0) {
+ this.limitByClause = `LIMIT 1 BY ${columns.join(", ")}`;
+ }
+
+ return this;
+ }
+
/**
* Conditionally apply builder operations
*/
@@ -344,10 +402,19 @@ abstract class AbstractQueryBuilder {
}
/**
- * Helper to build LIMIT section
+ * Helper to build LIMIT section (includes LIMIT BY if set)
*/
protected buildLimitSection(): string {
- return this.limitClause;
+ const parts: string[] = [];
+
+ if (this.limitByClause) {
+ parts.push(this.limitByClause);
+ }
+ if (this.limitClause) {
+ parts.push(this.limitClause);
+ }
+
+ return parts.join("\n");
}
/**
@@ -551,6 +618,10 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
private ioFields: { truncated: boolean; charLimit?: number } | null = null;
// Metadata expansion config: null = use truncated (default), string[] = expand specific keys, empty array = expand all
private metadataExpansionKeys: string[] | null = null;
+ // Flag to use direct metadata JSON column instead of array-based metadata
+ private useDirectMetadata: boolean = false;
+ // Raw SELECT expressions for custom columns (e.g., from CTEs)
+ private rawSelectExpressions: string[] = [];
/**
* Constructor
@@ -584,6 +655,34 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
return this;
}
+ /**
+ * Select metadata using direct JSON column access instead of array-based reconstruction.
+ * Use this for exports where full metadata values are needed without truncation.
+ *
+ * @example
+ * builder.selectMetadataDirect()
+ */
+ selectMetadataDirect(): this {
+ this.useDirectMetadata = true;
+ this.selectFields.add("metadataDirect");
+
+ return this;
+ }
+
+ /**
+ * Add raw SELECT expressions for custom columns (e.g., from CTEs).
+ * These are appended after the field set columns.
+ *
+ * @param expressions - Raw SQL expressions to add to SELECT
+ * @example
+ * builder.selectRaw("s.scores_avg as scores_avg", "s.score_categories as score_categories")
+ */
+ selectRaw(...expressions: string[]): this {
+ this.rawSelectExpressions.push(...expressions);
+
+ return this;
+ }
+
/**
* Add SELECT fields from predefined field sets
*/
@@ -616,10 +715,11 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
if (this.ioFields) {
fieldsToExclude.push("input", "output");
}
- // Only exclude metadata if we have actual keys to expand
+ // Exclude array-based metadata if using direct JSON metadata or expanded metadata
if (
- this.metadataExpansionKeys !== null &&
- this.metadataExpansionKeys.length > 0
+ this.useDirectMetadata ||
+ (this.metadataExpansionKeys !== null &&
+ this.metadataExpansionKeys.length > 0)
) {
fieldsToExclude.push("metadata");
}
@@ -668,6 +768,11 @@ export class EventsQueryBuilder extends BaseEventsQueryBuilder<
) as metadata`);
}
+ // Add raw SELECT expressions (e.g., from CTE joins)
+ if (this.rawSelectExpressions.length > 0) {
+ fieldExpressions.push(...this.rawSelectExpressions);
+ }
+
return `SELECT\n ${fieldExpressions.join(",\n ")}`;
}
diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
index cbeee24d73..0a880489f2 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
@@ -76,7 +76,7 @@ const buildScoresAggregationCTE = (
trace_id,
${primaryKey},
${additionalOuterCols.length > 0 ? additionalOuterCols.join(",\n ") + "," : ""}
- groupArrayIf(tuple(name, avg_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
+ groupArrayIf(tuple(name, avg_value, data_type, string_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories
FROM (
SELECT
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 319ba965b6..a802cf1f15 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -35,6 +35,12 @@ export {
CTEQueryBuilder,
EventsAggQueryBuilder,
EventsAggregationQueryBuilder,
+ EventsQueryBuilder,
type CTESchema,
type CTEWithSchema,
} from "./clickhouse-sql/event-query-builder";
+export {
+ eventsScoresAggregation,
+ eventsTracesAggregation,
+ eventsTracesScoresAggregation,
+} from "./clickhouse-sql/query-fragments";
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 25a9238d6f..380c973f3b 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -47,8 +47,10 @@ import {
commandClickhouse,
parseClickhouseUTCDateTimeFormat,
queryClickhouse,
+ queryClickhouseStream,
} from "./clickhouse";
import { ObservationRecordReadType, TraceRecordReadType } from "./definitions";
+import type { AnalyticsObservationEvent } from "../analytics-integrations/types";
import {
ObservationsTableQueryResult,
ObservationTableQuery,
@@ -2434,6 +2436,131 @@ export const hasAnyUserFromEventsTable = async (
};
/**
+ * Streams events from ClickHouse for blob storage export.
+ * Uses EventsQueryBuilder for consistent query construction.
+ */
+export const getEventsForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ const queryBuilder = new EventsQueryBuilder({ projectId })
+ .selectFieldSet("export")
+ .selectIO(false) // Full I/O, no truncation
+ .selectFieldSet("metadata")
+ .whereRaw(
+ "e.start_time >= {minTimestamp: DateTime64(3)} AND e.start_time <= {maxTimestamp: DateTime64(3)}",
+ {
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ )
+ .whereRaw("e.is_deleted = 0")
+ .limitBy("e.span_id", "e.project_id");
+
+ const { query, params } = queryBuilder.buildWithParams();
+
+ return queryClickhouseStream<Record<string, unknown>>({
+ query,
+ params,
+ tags: {
+ feature: "blobstorage",
+ type: "event",
+ kind: "analytic",
+ projectId,
+ },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
+ },
+ });
+};
+
+/**
+ * Streams events from ClickHouse for analytics integrations (PostHog, Mixpanel).
+ * Uses EventsQueryBuilder for consistent query construction.
+ * All fields come directly from the events table (which has denormalized trace-level data).
+ */
+export const getEventsForAnalyticsIntegrations = async function* (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ const queryBuilder = new EventsQueryBuilder({ projectId })
+ // Use export field set for most fields (id, traceId, name, type, level, version,
+ // environment, userId, sessionId, tags, release, traceName, totalCost, latency, etc.)
+ .selectFieldSet("export")
+ // Add analytics-specific computed fields
+ .selectRaw(
+ // Token counts from usage/cost details
+ "e.usage_details['input'] as input_tokens",
+ "e.usage_details['output'] as output_tokens",
+ "e.usage_details['total'] as total_tokens",
+ // Analytics integration session IDs from metadata (constructed from array columns)
+ "mapFromArrays(e.metadata_names, e.metadata_prefixes)['$posthog_session_id'] as posthog_session_id",
+ "mapFromArrays(e.metadata_names, e.metadata_prefixes)['$mixpanel_session_id'] as mixpanel_session_id",
+ )
+ .whereRaw(
+ "e.start_time >= {minTimestamp: DateTime64(3)} AND e.start_time <= {maxTimestamp: DateTime64(3)}",
+ {
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ )
+ .whereRaw("e.is_deleted = 0")
+ .limitBy("e.span_id", "e.project_id");
+
+ const { query, params } = queryBuilder.buildWithParams();
+
+ const records = queryClickhouseStream<Record<string, unknown>>({
+ query,
+ params,
+ tags: {
+ feature: "analytics-integration",
+ type: "event",
+ kind: "analytic",
+ projectId,
+ },
+ clickhouseConfigs: {
+ request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
+ },
+ });
+
+ const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
+ for await (const record of records) {
+ yield {
+ timestamp: record.start_time,
+ langfuse_observation_name: record.name,
+ langfuse_trace_name: record.trace_name,
+ langfuse_trace_id: record.trace_id,
+ langfuse_url: `${baseUrl}/project/${projectId}/traces/${encodeURIComponent(record.trace_id as string)}?observation=${encodeURIComponent(record.id as string)}`,
+ langfuse_user_url: record.user_id
+ ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.user_id as string)}`
+ : undefined,
+ langfuse_id: record.id,
+ langfuse_cost_usd: record.total_cost,
+ langfuse_input_units: record.input_tokens,
+ langfuse_output_units: record.output_tokens,
+ langfuse_total_units: record.total_tokens,
+ langfuse_session_id: record.session_id,
+ langfuse_project_id: projectId,
+ langfuse_user_id: record.user_id || null,
+ langfuse_latency: record.latency,
+ langfuse_time_to_first_token: record.time_to_first_token,
+ langfuse_release: record.release,
+ langfuse_version: record.version,
+ langfuse_model: record.provided_model_name,
+ langfuse_level: record.level,
+ langfuse_type: record.type,
+ langfuse_tags: record.tags,
+ langfuse_environment: record.environment,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: record.posthog_session_id ?? null,
+ mixpanel_session_id: record.mixpanel_session_id ?? null,
+ } satisfies AnalyticsObservationEvent;
+ }
+};
+
+/*
* Check if any session exists in events table
* Filters for non-empty session_id
*/
diff --git a/packages/shared/src/server/tableMappings/index.ts b/packages/shared/src/server/tableMappings/index.ts
index f303819d69..4c263f6c68 100644
--- a/packages/shared/src/server/tableMappings/index.ts
+++ b/packages/shared/src/server/tableMappings/index.ts
@@ -1,5 +1,6 @@
export * from "./mapObservationsTable";
export * from "./mapTracesTable";
+export * from "./mapEventsTable";
export * from "../../tableDefinitions/mapDashboards";
export * from "./mapScoresTable";
export * from "./mapDatasetRunItemsTable";
diff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsx
index f38112ef85..6504b18d7d 100644
--- a/web/src/components/BatchExportTableButton.tsx
+++ b/web/src/components/BatchExportTableButton.tsx
@@ -79,6 +79,8 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (
return "Note: Filters on observation-level columns (Level, Tokens, Cost, Latency) and Comments are not included in trace exports. You may receive more data than expected.";
case BatchTableNames.Observations:
return "Note: Filters on trace-level columns (Trace Name, Trace Tags, User ID, Trace Environment) and Comments are not included in observation exports. You may receive more data than expected.";
+ case BatchTableNames.Events:
+ return "Note: Filters on Comments are not included in event exports. You may receive more data than expected.";
case BatchTableNames.Sessions:
return "Note: Filters on Comments are not included in session exports. You may receive more data than expected.";
case BatchTableNames.AuditLogs:
diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
index 7bd95482e1..d648815950 100644
--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
@@ -88,6 +88,7 @@ export const blobStorageIntegrationRouter = createTRPCRouter({
fileType,
exportMode,
exportStartDate,
+ exportSource,
} = input;
const isSelfHosted = !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
@@ -125,6 +126,7 @@ export const blobStorageIntegrationRouter = createTRPCRouter({
fileType,
exportMode,
exportStartDate: finalExportStartDate,
+ exportSource,
};
// Use a transaction to check if record exists, then create or update
diff --git a/web/src/features/blobstorage-integration/types.ts b/web/src/features/blobstorage-integration/types.ts
index f01bbb95e7..fdf91018d9 100644
--- a/web/src/features/blobstorage-integration/types.ts
+++ b/web/src/features/blobstorage-integration/types.ts
@@ -3,6 +3,7 @@ import {
BlobStorageIntegrationType,
BlobStorageIntegrationFileType,
BlobStorageExportMode,
+ AnalyticsIntegrationExportSource,
} from "@langfuse/shared";
export const blobStorageIntegrationFormSchema = z.object({
@@ -29,6 +30,9 @@ export const blobStorageIntegrationFormSchema = z.object({
.enum(BlobStorageExportMode)
.default(BlobStorageExportMode.FULL_HISTORY),
exportStartDate: z.coerce.date().optional().nullable(),
+ exportSource: z
+ .enum(AnalyticsIntegrationExportSource)
+ .default(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
export type BlobStorageIntegrationFormSchema = z.infer<
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index f6ea07fb05..779863a4e7 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -1293,7 +1293,7 @@ export default function ObservationsEventsTable({
searchQuery,
searchType,
}}
- tableName={BatchExportTableName.Observations}
+ tableName={BatchExportTableName.Events}
key="batchExport"
/>,
Object.keys(selectedRows).filter((observationId) =>
diff --git a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
index e1a755340a..214209a5f3 100644
--- a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts
@@ -31,10 +31,12 @@ export const mixpanelIntegrationRouter = createTRPCRouter({
return null;
}
- const { encryptedMixpanelProjectToken, ...config } = dbConfig;
+ const { encryptedMixpanelProjectToken, exportSource, ...config } =
+ dbConfig;
return {
...config,
+ exportSource,
mixpanelProjectToken: decrypt(encryptedMixpanelProjectToken),
};
} catch (e) {
@@ -86,11 +88,13 @@ export const mixpanelIntegrationRouter = createTRPCRouter({
mixpanelRegion: config.mixpanelRegion,
encryptedMixpanelProjectToken,
enabled: config.enabled,
+ exportSource: config.exportSource,
},
update: {
encryptedMixpanelProjectToken,
mixpanelRegion: config.mixpanelRegion,
enabled: config.enabled,
+ exportSource: config.exportSource,
},
});
}),
diff --git a/web/src/features/mixpanel-integration/types.ts b/web/src/features/mixpanel-integration/types.ts
index a0aa2a409e..e119393795 100644
--- a/web/src/features/mixpanel-integration/types.ts
+++ b/web/src/features/mixpanel-integration/types.ts
@@ -1,3 +1,4 @@
+import { AnalyticsIntegrationExportSource } from "@langfuse/shared";
import { z } from "zod/v4";
export const MIXPANEL_REGIONS = [
@@ -27,4 +28,7 @@ export const mixpanelIntegrationFormSchema = z.object({
"Mixpanel Project Token is required. You can find it in your Mixpanel project settings.",
),
enabled: z.boolean(),
+ exportSource: z
+ .enum(AnalyticsIntegrationExportSource)
+ .default(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.ts
index bf7419d894..e63bb6ac9f 100644
--- a/web/src/features/posthog-integration/posthog-integration-router.ts
+++ b/web/src/features/posthog-integration/posthog-integration-router.ts
@@ -32,10 +32,11 @@ export const posthogIntegrationRouter = createTRPCRouter({
return null;
}
- const { encryptedPosthogApiKey, ...config } = dbConfig;
+ const { encryptedPosthogApiKey, exportSource, ...config } = dbConfig;
return {
...config,
+ exportSource,
posthogApiKey: decrypt(encryptedPosthogApiKey),
};
} catch (e) {
@@ -101,11 +102,13 @@ export const posthogIntegrationRouter = createTRPCRouter({
posthogHostName: config.posthogHostname,
encryptedPosthogApiKey,
enabled: config.enabled,
+ exportSource: config.exportSource,
},
update: {
encryptedPosthogApiKey,
posthogHostName: config.posthogHostname,
enabled: config.enabled,
+ exportSource: config.exportSource,
},
});
}),
diff --git a/web/src/features/posthog-integration/types.ts b/web/src/features/posthog-integration/types.ts
index dd8dfaf904..9d6c5a72f1 100644
--- a/web/src/features/posthog-integration/types.ts
+++ b/web/src/features/posthog-integration/types.ts
@@ -1,3 +1,4 @@
+import { AnalyticsIntegrationExportSource } from "@langfuse/shared";
import { z } from "zod/v4";
export const posthogIntegrationFormSchema = z.object({
@@ -7,4 +8,7 @@ export const posthogIntegrationFormSchema = z.object({
"PostHog 'Project API Key' must start with 'phc_'. You can find it in the PostHog project settings.",
}),
enabled: z.boolean(),
+ exportSource: z
+ .enum(AnalyticsIntegrationExportSource)
+ .default(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
index 630d3e6748..5d66efc6fa 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
@@ -21,6 +21,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
+import {
+ Tooltip,
+ TooltipTrigger,
+ TooltipContent,
+} from "@/src/components/ui/tooltip";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
blobStorageIntegrationFormSchema,
@@ -40,9 +45,13 @@ import {
BlobStorageIntegrationType,
BlobStorageIntegrationFileType,
BlobStorageExportMode,
+ AnalyticsIntegrationExportSource,
type BlobStorageIntegration,
+ EXPORT_SOURCE_OPTIONS,
} from "@langfuse/shared";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+import { Info, ExternalLink } from "lucide-react";
export default function BlobStorageIntegrationSettings() {
const router = useRouter();
@@ -163,6 +172,7 @@ const BlobStorageIntegrationSettingsForm = ({
}) => {
const capture = usePostHogClientCapture();
const { isLangfuseCloud } = useLangfuseCloudRegion();
+ const { isBetaEnabled } = useV4Beta();
const [integrationType, setIntegrationType] =
useState<BlobStorageIntegrationType>(BlobStorageIntegrationType.S3);
@@ -188,6 +198,11 @@ const BlobStorageIntegrationSettingsForm = ({
fileType: state?.fileType || BlobStorageIntegrationFileType.JSONL,
exportMode: state?.exportMode || BlobStorageExportMode.FULL_HISTORY,
exportStartDate: state?.exportStartDate || null,
+ exportSource:
+ state?.exportSource ||
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
},
disabled: isLoading,
});
@@ -211,6 +226,11 @@ const BlobStorageIntegrationSettingsForm = ({
fileType: state?.fileType || BlobStorageIntegrationFileType.JSONL,
exportMode: state?.exportMode || BlobStorageExportMode.FULL_HISTORY,
exportStartDate: state?.exportStartDate || null,
+ exportSource:
+ state?.exportSource ||
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
@@ -568,6 +588,68 @@ const BlobStorageIntegrationSettingsForm = ({
)}
/>
+ {isBetaEnabled && (
+ <FormField
+ control={blobStorageForm.control}
+ name="exportSource"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="flex items-center gap-1.5 pt-2">
+ Export Source
+ <Tooltip>
+ <TooltipTrigger>
+ <Info className="h-3.5 w-3.5 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="max-w-[350px] space-y-2 p-3"
+ >
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <div key={option.value} className="space-y-0.5">
+ <div className="font-medium">{option.label}</div>
+ <div className="text-xs text-muted-foreground">
+ {option.description}
+ </div>
+ </div>
+ ))}
+ <div className="border-t pt-2">
+ <a
+ href="https://langfuse.com/docs/integrations/export-sources"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-primary hover:underline"
+ >
+ For further information see
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FormLabel>
+ <Select onValueChange={field.onChange} value={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select data to export" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ Choose which data sources to export to blob storage. Scores
+ are always included.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
{blobStorageForm.watch("exportMode") ===
BlobStorageExportMode.FROM_CUSTOM_DATE && (
<FormField
diff --git a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx
index 0d0ecf9c69..dada65eccb 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx
@@ -21,12 +21,22 @@ import {
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
+import {
+ Tooltip,
+ TooltipTrigger,
+ TooltipContent,
+} from "@/src/components/ui/tooltip";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
mixpanelIntegrationFormSchema,
MIXPANEL_REGIONS,
type MixpanelRegion,
} from "@/src/features/mixpanel-integration/types";
+import {
+ AnalyticsIntegrationExportSource,
+ EXPORT_SOURCE_OPTIONS,
+} from "@langfuse/shared";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
@@ -37,6 +47,7 @@ import { useRouter } from "next/router";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { type z } from "zod/v4";
+import { Info, ExternalLink } from "lucide-react";
export default function MixpanelIntegrationSettings() {
const router = useRouter();
@@ -132,6 +143,7 @@ const MixpanelIntegrationSettingsForm = ({
isLoading: boolean;
}) => {
const capture = usePostHogClientCapture();
+ const { isBetaEnabled } = useV4Beta();
const mixpanelForm = useForm({
resolver: zodResolver(mixpanelIntegrationFormSchema),
defaultValues: {
@@ -140,6 +152,11 @@ const MixpanelIntegrationSettingsForm = ({
MIXPANEL_REGIONS[0].subdomain,
mixpanelProjectToken: state?.mixpanelProjectToken ?? "",
enabled: state?.enabled ?? false,
+ exportSource:
+ state?.exportSource ??
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
},
disabled: isLoading,
});
@@ -151,6 +168,11 @@ const MixpanelIntegrationSettingsForm = ({
MIXPANEL_REGIONS[0].subdomain,
mixpanelProjectToken: state?.mixpanelProjectToken ?? "",
enabled: state?.enabled ?? false,
+ exportSource:
+ state?.exportSource ??
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
@@ -227,6 +249,67 @@ const MixpanelIntegrationSettingsForm = ({
</FormItem>
)}
/>
+ {isBetaEnabled && (
+ <FormField
+ control={mixpanelForm.control}
+ name="exportSource"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="flex items-center gap-1.5 pt-2">
+ Export Source
+ <Tooltip>
+ <TooltipTrigger>
+ <Info className="h-3.5 w-3.5 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="max-w-[350px] space-y-2 p-3"
+ >
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <div key={option.value} className="space-y-0.5">
+ <div className="font-medium">{option.label}</div>
+ <div className="text-xs text-muted-foreground">
+ {option.description}
+ </div>
+ </div>
+ ))}
+ <div className="border-t pt-2">
+ <a
+ href="https://langfuse.com/docs/integrations/export-sources"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-primary hover:underline"
+ >
+ For further information see
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FormLabel>
+ <Select onValueChange={field.onChange} value={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select data to export" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ Choose which data sources to export to Mixpanel. Scores are
+ always included.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
<FormField
control={mixpanelForm.control}
name="enabled"
diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
index 21cb9d54a7..f53f528368 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
@@ -15,8 +15,25 @@ import {
import { Input } from "@/src/components/ui/input";
import { PasswordInput } from "@/src/components/ui/password-input";
import { Switch } from "@/src/components/ui/switch";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import {
+ Tooltip,
+ TooltipTrigger,
+ TooltipContent,
+} from "@/src/components/ui/tooltip";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";
+import {
+ AnalyticsIntegrationExportSource,
+ EXPORT_SOURCE_OPTIONS,
+} from "@langfuse/shared";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
@@ -27,6 +44,7 @@ import { useRouter } from "next/router";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { type z } from "zod/v4";
+import { Info, ExternalLink } from "lucide-react";
export default function PosthogIntegrationSettings() {
const router = useRouter();
@@ -122,12 +140,18 @@ const PostHogIntegrationSettings = ({
isLoading: boolean;
}) => {
const capture = usePostHogClientCapture();
+ const { isBetaEnabled } = useV4Beta();
const posthogForm = useForm({
resolver: zodResolver(posthogIntegrationFormSchema),
defaultValues: {
posthogHostname: state?.posthogHostName ?? "",
posthogProjectApiKey: state?.posthogApiKey ?? "",
enabled: state?.enabled ?? false,
+ exportSource:
+ state?.exportSource ??
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
},
disabled: isLoading,
});
@@ -137,6 +161,11 @@ const PostHogIntegrationSettings = ({
posthogHostname: state?.posthogHostName ?? "",
posthogProjectApiKey: state?.posthogApiKey ?? "",
enabled: state?.enabled ?? false,
+ exportSource:
+ state?.exportSource ??
+ (isBetaEnabled
+ ? AnalyticsIntegrationExportSource.EVENTS
+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [state]);
@@ -196,6 +225,67 @@ const PostHogIntegrationSettings = ({
</FormItem>
)}
/>
+ {isBetaEnabled && (
+ <FormField
+ control={posthogForm.control}
+ name="exportSource"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel className="flex items-center gap-1.5 pt-2">
+ Export Source
+ <Tooltip>
+ <TooltipTrigger>
+ <Info className="h-3.5 w-3.5 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent
+ side="bottom"
+ className="max-w-[350px] space-y-2 p-3"
+ >
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <div key={option.value} className="space-y-0.5">
+ <div className="font-medium">{option.label}</div>
+ <div className="text-xs text-muted-foreground">
+ {option.description}
+ </div>
+ </div>
+ ))}
+ <div className="border-t pt-2">
+ <a
+ href="https://langfuse.com/docs/integrations/export-sources"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-primary hover:underline"
+ >
+ For further information see
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ </FormLabel>
+ <Select onValueChange={field.onChange} value={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select data to export" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {EXPORT_SOURCE_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ Choose which data sources to export to PostHog. Scores are
+ always included.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
<FormField
control={posthogForm.control}
name="enabled"
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 15b59c7f60..417439a375 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -10,17 +10,26 @@ import {
createTracesCh,
createManyDatasetItems,
applyCommentFilters,
+ createEvent,
+ createEventsCh,
+ getEventsForBlobStorageExport,
} from "@langfuse/shared/src/server";
import { BatchExportTableName, DatasetStatus } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { getDatabaseReadStreamPaginated } from "../features/database-read-stream/getDatabaseReadStream";
import { getObservationStream } from "../features/database-read-stream/observation-stream";
import { getTraceStream } from "../features/database-read-stream/trace-stream";
+import { getEventsStream } from "../features/database-read-stream/event-stream";
// Set environment variable before any imports to ensure it's picked up by env module
process.env.LANGFUSE_DATASET_SERVICE_READ_FROM_VERSIONED_IMPLEMENTATION =
"true";
process.env.LANGFUSE_DATASET_SERVICE_WRITE_TO_VERSIONED_IMPLEMENTATION = "true";
+const maybeDescribe =
+ process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
+ ? describe
+ : describe.skip;
+
describe("batch export test suite", () => {
it("should export observations", async () => {
const { projectId } = await createOrgProjectAndApiKey();
@@ -2260,4 +2269,1635 @@ describe("batch export test suite", () => {
expect(rows[0].id).toBe(traceWithComments);
expect(rows[0].name).toBe("trace-with-comments");
});
+
+ // ==================== EVENTS TABLE EXPORT TESTS ====================
+
+ maybeDescribe("events table export tests", () => {
+ it("should export events from events table", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000; // Events use microseconds
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "span-event",
+ start_time: now,
+ end_time: now + 1000000, // 1 second later in microseconds
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-event",
+ provided_model_name: "gpt-4",
+ start_time: now,
+ end_time: now + 2000000, // 2 seconds later
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "EVENT",
+ name: "simple-event",
+ start_time: now,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(3);
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: events[0].span_id,
+ name: "span-event",
+ type: "SPAN",
+ }),
+ expect.objectContaining({
+ id: events[1].span_id,
+ name: "generation-event",
+ type: "GENERATION",
+ providedModelName: "gpt-4",
+ }),
+ expect.objectContaining({
+ id: events[2].span_id,
+ name: "simple-event",
+ type: "EVENT",
+ }),
+ ]),
+ );
+ });
+
+ it("should export events with filters", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-1",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-2",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ name: "span-1",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter by type
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "type",
+ value: ["GENERATION"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.type === "GENERATION")).toBe(true);
+
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(
+ expect.arrayContaining(["generation-1", "generation-2"]),
+ );
+ });
+
+ it("should export events with name filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "api-call",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "database-query",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "api-call",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "name",
+ value: ["api-call"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.name === "api-call")).toBe(true);
+ });
+
+ it("should export events with scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create scores linked to this event
+ const score = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "quality",
+ value: 0.95,
+ data_type: "NUMERIC",
+ });
+
+ await createScoresCh([score]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("scored-event");
+ // Verify score is included
+ expect(rows[0].quality).toEqual([0.95]);
+ });
+
+ it("should export events with categorical scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "categorically-scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create categorical score
+ const score = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "sentiment",
+ value: undefined,
+ string_value: "positive",
+ data_type: "CATEGORICAL",
+ });
+
+ await createScoresCh([score]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("categorically-scored-event");
+ // Verify categorical score is included
+ expect(rows[0].sentiment).toEqual(["positive"]);
+ });
+
+ it("should handle empty events export", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(0);
+ });
+
+ it("should export events with environment filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "prod-event",
+ environment: "production",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "staging-event",
+ environment: "staging",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "another-prod-event",
+ environment: "production",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "environment",
+ value: ["production"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.environment === "production")).toBe(true);
+
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(
+ expect.arrayContaining(["prod-event", "another-prod-event"]),
+ );
+ });
+
+ it("should export events with date range filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create events with different timestamps
+ const jan1 = new Date("2024-01-01T10:00:00Z").getTime() * 1000;
+ const jan15 = new Date("2024-01-15T10:00:00Z").getTime() * 1000;
+ const jan30 = new Date("2024-01-30T10:00:00Z").getTime() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "early-january-event",
+ start_time: jan1,
+ created_at: jan1,
+ updated_at: jan1,
+ event_ts: jan1,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "mid-january-event",
+ start_time: jan15,
+ created_at: jan15,
+ updated_at: jan15,
+ event_ts: jan15,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "late-january-event",
+ start_time: jan30,
+ created_at: jan30,
+ updated_at: jan30,
+ event_ts: jan30,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter for mid-January only
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date("2024-02-01T00:00:00Z"),
+ filter: [
+ {
+ type: "datetime",
+ operator: ">=",
+ column: "startTime",
+ value: new Date("2024-01-10T00:00:00Z"),
+ },
+ {
+ type: "datetime",
+ operator: "<",
+ column: "startTime",
+ value: new Date("2024-01-20T00:00:00Z"),
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("mid-january-event");
+ });
+
+ it("should export events with usage details and cost details", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "event-with-usage",
+ usage_details: { input: 100, output: 200, total: 300 },
+ cost_details: { input: 0.01, output: 0.02, total: 0.03 },
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("event-with-usage");
+ expect(rows[0].usageDetails).toEqual({
+ input: 100,
+ output: 200,
+ total: 300,
+ });
+ expect(rows[0].costDetails).toEqual({
+ input: 0.01,
+ output: 0.02,
+ total: 0.03,
+ });
+ });
+
+ it("should export events with searchQuery filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "searchable-generation",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "other-generation",
+ start_time: now + 1000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ searchQuery: "searchable",
+ searchType: ["id"],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("searchable-generation");
+ });
+
+ it("should export events with trace metadata (denormalized fields)", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const userId = randomUUID();
+ const sessionId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ trace_name: "parent-trace",
+ user_id: userId,
+ session_id: sessionId,
+ type: "GENERATION",
+ name: "event-with-trace-data",
+ tags: ["tag1", "tag2"],
+ release: "v1.2.3",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ name: "event-with-trace-data",
+ traceId: traceId,
+ traceName: "parent-trace",
+ userId: userId,
+ sessionId: sessionId,
+ tags: ["tag1", "tag2"],
+ release: "v1.2.3",
+ });
+ });
+
+ it("should export events respecting row limit", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ // Create 10 events
+ const events = Array.from({ length: 10 }, (_, i) =>
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: `event-${i}`,
+ start_time: now + i * 1000000,
+ }),
+ );
+
+ await createEventsCh(events);
+
+ // Limit to 5 rows
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ rowLimit: 5,
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(5);
+ });
+
+ it("should export events with multiple score types", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "multi-scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create multiple scores of different types
+ const scores = [
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "accuracy",
+ value: 0.95,
+ data_type: "NUMERIC",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "category",
+ value: undefined,
+ string_value: "excellent",
+ data_type: "CATEGORICAL",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "is_correct",
+ value: 1,
+ data_type: "BOOLEAN",
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("multi-scored-event");
+ expect(rows[0].accuracy).toEqual([0.95]);
+ expect(rows[0].category).toEqual(["excellent"]);
+ expect(rows[0].is_correct).toEqual([1]);
+ });
+
+ it("should export events with filter and sorting", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create events with different timestamps and types
+ const jan1 = new Date("2024-01-01T10:00:00Z").getTime() * 1000;
+ const jan2 = new Date("2024-01-02T10:00:00Z").getTime() * 1000;
+ const jan3 = new Date("2024-01-03T10:00:00Z").getTime() * 1000;
+ const jan4 = new Date("2024-01-04T10:00:00Z").getTime() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-1",
+ environment: "production",
+ start_time: jan1,
+ created_at: jan1,
+ updated_at: jan1,
+ event_ts: jan1,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ name: "span-event-1",
+ environment: "production",
+ start_time: jan2,
+ created_at: jan2,
+ updated_at: jan2,
+ event_ts: jan2,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-2",
+ environment: "staging",
+ start_time: jan3,
+ created_at: jan3,
+ updated_at: jan3,
+ event_ts: jan3,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-3",
+ environment: "production",
+ start_time: jan4,
+ created_at: jan4,
+ updated_at: jan4,
+ event_ts: jan4,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter by type=GENERATION AND environment=production
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date("2024-01-05T00:00:00Z"),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "type",
+ value: ["GENERATION"],
+ },
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "environment",
+ value: ["production"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ // Should only return GENERATION events in production environment
+ expect(rows).toHaveLength(2);
+
+ // Verify all results match filters
+ expect(rows.every((r) => r.type === "GENERATION")).toBe(true);
+ expect(rows.every((r) => r.environment === "production")).toBe(true);
+
+ // Results should be sorted by start_time DESC (default)
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(["gen-event-3", "gen-event-1"]);
+ });
+
+ // ==================== EVENTS TABLE EXPORT TESTS ====================
+
+ it("should export events from events table", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000; // Events use microseconds
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "span-event",
+ start_time: now,
+ end_time: now + 1000000, // 1 second later in microseconds
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-event",
+ provided_model_name: "gpt-4",
+ start_time: now,
+ end_time: now + 2000000, // 2 seconds later
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "EVENT",
+ name: "simple-event",
+ start_time: now,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(3);
+ expect(rows).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: events[0].span_id,
+ name: "span-event",
+ type: "SPAN",
+ }),
+ expect.objectContaining({
+ id: events[1].span_id,
+ name: "generation-event",
+ type: "GENERATION",
+ providedModelName: "gpt-4",
+ }),
+ expect.objectContaining({
+ id: events[2].span_id,
+ name: "simple-event",
+ type: "EVENT",
+ }),
+ ]),
+ );
+ });
+
+ it("should export events with filters", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-1",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "generation-2",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ name: "span-1",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter by type
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "type",
+ value: ["GENERATION"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.type === "GENERATION")).toBe(true);
+
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(
+ expect.arrayContaining(["generation-1", "generation-2"]),
+ );
+ });
+
+ it("should export events with name filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "api-call",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "database-query",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "api-call",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "name",
+ value: ["api-call"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.name === "api-call")).toBe(true);
+ });
+
+ it("should export events with scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create scores linked to this event
+ const score = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "quality",
+ value: 0.95,
+ data_type: "NUMERIC",
+ });
+
+ await createScoresCh([score]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("scored-event");
+ // Verify score is included
+ expect(rows[0].quality).toEqual([0.95]);
+ });
+
+ it("should export events with categorical scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "categorically-scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create categorical score
+ const score = createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "sentiment",
+ value: undefined,
+ string_value: "positive",
+ data_type: "CATEGORICAL",
+ });
+
+ await createScoresCh([score]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("categorically-scored-event");
+ // Verify categorical score is included
+ expect(rows[0].sentiment).toEqual(["positive"]);
+ });
+
+ it("should handle empty events export", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(0);
+ });
+
+ it("should export events with environment filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "prod-event",
+ environment: "production",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "staging-event",
+ environment: "staging",
+ start_time: now + 1000000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "another-prod-event",
+ environment: "production",
+ start_time: now + 2000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "environment",
+ value: ["production"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+ expect(rows.every((r) => r.environment === "production")).toBe(true);
+
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(
+ expect.arrayContaining(["prod-event", "another-prod-event"]),
+ );
+ });
+
+ it("should export events with date range filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create events with different timestamps
+ const jan1 = new Date("2024-01-01T10:00:00Z").getTime() * 1000;
+ const jan15 = new Date("2024-01-15T10:00:00Z").getTime() * 1000;
+ const jan30 = new Date("2024-01-30T10:00:00Z").getTime() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "early-january-event",
+ start_time: jan1,
+ created_at: jan1,
+ updated_at: jan1,
+ event_ts: jan1,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "mid-january-event",
+ start_time: jan15,
+ created_at: jan15,
+ updated_at: jan15,
+ event_ts: jan15,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "late-january-event",
+ start_time: jan30,
+ created_at: jan30,
+ updated_at: jan30,
+ event_ts: jan30,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter for mid-January only
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date("2024-02-01T00:00:00Z"),
+ filter: [
+ {
+ type: "datetime",
+ operator: ">=",
+ column: "startTime",
+ value: new Date("2024-01-10T00:00:00Z"),
+ },
+ {
+ type: "datetime",
+ operator: "<",
+ column: "startTime",
+ value: new Date("2024-01-20T00:00:00Z"),
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("mid-january-event");
+ });
+
+ it("should export events with usage details and cost details", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "event-with-usage",
+ usage_details: { input: 100, output: 200, total: 300 },
+ cost_details: { input: 0.01, output: 0.02, total: 0.03 },
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("event-with-usage");
+ expect(rows[0].usageDetails).toEqual({
+ input: 100,
+ output: 200,
+ total: 300,
+ });
+ expect(rows[0].costDetails).toEqual({
+ input: 0.01,
+ output: 0.02,
+ total: 0.03,
+ });
+ });
+
+ it("should export events with searchQuery filter", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "searchable-generation",
+ start_time: now,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "other-generation",
+ start_time: now + 1000000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ searchQuery: "searchable",
+ searchType: ["id"],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("searchable-generation");
+ });
+
+ it("should export events with trace metadata (denormalized fields)", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const userId = randomUUID();
+ const sessionId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ trace_name: "parent-trace",
+ user_id: userId,
+ session_id: sessionId,
+ type: "GENERATION",
+ name: "event-with-trace-data",
+ tags: ["tag1", "tag2"],
+ release: "v1.2.3",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ name: "event-with-trace-data",
+ traceId: traceId,
+ traceName: "parent-trace",
+ userId: userId,
+ sessionId: sessionId,
+ tags: ["tag1", "tag2"],
+ release: "v1.2.3",
+ });
+ });
+
+ it("should export events respecting row limit", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const now = Date.now() * 1000;
+
+ // Create 10 events
+ const events = Array.from({ length: 10 }, (_, i) =>
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: `event-${i}`,
+ start_time: now + i * 1000000,
+ }),
+ );
+
+ await createEventsCh(events);
+
+ // Limit to 5 rows
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ rowLimit: 5,
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(5);
+ });
+
+ it("should export events with multiple score types", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = randomUUID();
+ const now = Date.now() * 1000;
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "multi-scored-event",
+ start_time: now,
+ });
+
+ await createEventsCh([event]);
+
+ // Create multiple scores of different types
+ const scores = [
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "accuracy",
+ value: 0.95,
+ data_type: "NUMERIC",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "category",
+ value: undefined,
+ string_value: "excellent",
+ data_type: "CATEGORICAL",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: event.span_id,
+ name: "is_correct",
+ value: 1,
+ data_type: "BOOLEAN",
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("multi-scored-event");
+ expect(rows[0].accuracy).toEqual([0.95]);
+ expect(rows[0].category).toEqual(["excellent"]);
+ expect(rows[0].is_correct).toEqual([1]);
+ });
+
+ it("should export events with filter and sorting", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create events with different timestamps and types
+ const jan1 = new Date("2024-01-01T10:00:00Z").getTime() * 1000;
+ const jan2 = new Date("2024-01-02T10:00:00Z").getTime() * 1000;
+ const jan3 = new Date("2024-01-03T10:00:00Z").getTime() * 1000;
+ const jan4 = new Date("2024-01-04T10:00:00Z").getTime() * 1000;
+
+ const events = [
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-1",
+ environment: "production",
+ start_time: jan1,
+ created_at: jan1,
+ updated_at: jan1,
+ event_ts: jan1,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "SPAN",
+ name: "span-event-1",
+ environment: "production",
+ start_time: jan2,
+ created_at: jan2,
+ updated_at: jan2,
+ event_ts: jan2,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-2",
+ environment: "staging",
+ start_time: jan3,
+ created_at: jan3,
+ updated_at: jan3,
+ event_ts: jan3,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: randomUUID(),
+ type: "GENERATION",
+ name: "gen-event-3",
+ environment: "production",
+ start_time: jan4,
+ created_at: jan4,
+ updated_at: jan4,
+ event_ts: jan4,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Filter by type=GENERATION AND environment=production
+ const stream = await getEventsStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date("2024-01-05T00:00:00Z"),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "type",
+ value: ["GENERATION"],
+ },
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "environment",
+ value: ["production"],
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ // Should only return GENERATION events in production environment
+ expect(rows).toHaveLength(2);
+
+ // Verify all results match filters
+ expect(rows.every((r) => r.type === "GENERATION")).toBe(true);
+ expect(rows.every((r) => r.environment === "production")).toBe(true);
+
+ // Results should be sorted by start_time DESC (default)
+ const exportedNames = rows.map((row) => row.name);
+ expect(exportedNames).toEqual(["gen-event-3", "gen-event-1"]);
+ });
+ });
+});
+
+maybeDescribe("getEventsForBlobStorageExport", () => {
+ it("should stream events for blob storage export", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = Date.now();
+ const traceId = randomUUID();
+
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-blob-event",
+ start_time: now * 1000, // microseconds
+ });
+
+ await createEventsCh([event]);
+
+ const stream = getEventsForBlobStorageExport(
+ projectId,
+ new Date(now - 60 * 60 * 1000), // 1 hour ago
+ new Date(now + 60 * 60 * 1000), // 1 hour from now
+ );
+
+ const rows: Record<string, unknown>[] = [];
+ for await (const row of stream) {
+ rows.push(row);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe(event.span_id);
+ expect(rows[0].name).toBe("test-blob-event");
+ expect(rows[0].type).toBe("GENERATION");
+ });
+
+ it("should filter events by time range", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = Date.now();
+ const traceId = randomUUID();
+
+ // Create events at different times
+ const oldEvent = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "old-event",
+ start_time: (now - 3 * 60 * 60 * 1000) * 1000, // 3 hours ago (microseconds)
+ });
+
+ const recentEvent = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "recent-event",
+ start_time: now * 1000, // now (microseconds)
+ });
+
+ await createEventsCh([oldEvent, recentEvent]);
+
+ // Query for events in the last 2 hours only
+ const stream = getEventsForBlobStorageExport(
+ projectId,
+ new Date(now - 2 * 60 * 60 * 1000), // 2 hours ago
+ new Date(now + 60 * 60 * 1000), // 1 hour from now
+ );
+
+ const rows: Record<string, unknown>[] = [];
+ for await (const row of stream) {
+ rows.push(row);
+ }
+
+ // Should only include the recent event (old event is outside time range)
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe(recentEvent.span_id);
+ expect(rows[0].name).toBe("recent-event");
+ });
+
+ it("should return empty stream when no events match time range", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = Date.now();
+ const traceId = randomUUID();
+
+ // Create event in the past
+ const pastEvent = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "past-event",
+ start_time: (now - 5 * 60 * 60 * 1000) * 1000, // 5 hours ago (microseconds)
+ });
+
+ await createEventsCh([pastEvent]);
+
+ // Query for events in the last hour only (event is older)
+ const stream = getEventsForBlobStorageExport(
+ projectId,
+ new Date(now - 60 * 60 * 1000), // 1 hour ago
+ new Date(now + 60 * 60 * 1000), // 1 hour from now
+ );
+
+ const rows: Record<string, unknown>[] = [];
+ for await (const row of stream) {
+ rows.push(row);
+ }
+
+ expect(rows).toHaveLength(0);
+ });
});
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
index c2abf86767..c44f9941c2 100644
--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -9,6 +9,8 @@ import {
createScoresCh,
createTrace,
createTracesCh,
+ createEvent,
+ createEventsCh,
StorageService,
StorageServiceFactory,
} from "@langfuse/shared/src/server";
@@ -26,6 +28,10 @@ import { encrypt } from "@langfuse/shared/encryption";
// Unfortunately, this is necessary as we don't have a good way to skip empty file uploads
// and at least azurite doesn't handle them gracefully.
const maybeIt = env.LANGFUSE_USE_AZURE_BLOB === "true" ? it.skip : it;
+const maybeDescribe =
+ process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"
+ ? describe
+ : describe.skip;
describe("BlobStorageIntegrationProcessingJob", () => {
let storageService: StorageService;
@@ -104,307 +110,235 @@ describe("BlobStorageIntegrationProcessingJob", () => {
expect(files.filter((f) => f.file.includes(projectId))).toHaveLength(0);
});
- it("should export traces, generations, and scores to S3", async () => {
- // Setup
- const { projectId } = await createOrgProjectAndApiKey();
- s3Prefix = projectId;
- const now = new Date();
- // Set lastSyncAt to 2 hours ago so the chunked export (1 hour window) covers recent data
- const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
+ maybeDescribe("events table export tests", () => {
+ it("should export traces, generations, and scores to S3", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ s3Prefix = projectId;
+ const now = new Date();
+ // Set lastSyncAt to 2 hours ago so the chunked export (1 hour window) covers recent data
+ const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
- // Create integration
- 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",
- nextSyncAt: twoHoursAgo,
- lastSyncAt: twoHoursAgo,
- },
- });
+ // Create integration
+ 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,
+ },
+ });
- // Create test data within the export window (2 hours ago to 1 hour ago)
- // With 30-min lag buffer, actual window is 2h ago to (1h ago or now-30min, whichever is earlier)
- const traceId = randomUUID();
- const observationId = randomUUID();
- const scoreId = randomUUID();
+ // Create test data within the export window (2 hours ago to 1 hour ago)
+ // With 30-min lag buffer, actual window is 2h ago to (1h ago or now-30min, whichever is earlier)
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const scoreId = randomUUID();
- // Create trace, observation, and score in Clickhouse
- // Data is at 90 minutes ago, which falls within the chunked export window
- await Promise.all([
- createTracesCh([
- createTrace({
- id: traceId,
- project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 min before now
- name: "Test Trace",
- }),
- ]),
- createObservationsCh([
- createObservation({
- id: observationId,
- trace_id: traceId,
- project_id: projectId,
- start_time: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
- name: "Test Observation",
- }),
- ]),
- createScoresCh([
- createTraceScore({
- id: scoreId,
- trace_id: traceId,
- project_id: projectId,
- timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
- name: "Test Score",
- value: 0.95,
- }),
- ]),
- ]);
+ // Create event data for events table export
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "Test Event",
+ start_time: (now.getTime() - 90 * 60 * 1000) * 1000, // 90 minutes before now (microseconds)
+ });
- // When
- await handleBlobStorageIntegrationProjectJob({
- data: { payload: { projectId } },
- } as Job);
+ // Create trace, observation, score, and event in Clickhouse
+ // Data is at 90 minutes ago, which falls within the chunked export window
+ await Promise.all([
+ createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 90 * 60 * 1000, // 90 min before now
+ name: "Test Trace",
+ }),
+ ]),
+ createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ name: "Test Observation",
+ }),
+ ]),
+ createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ trace_id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 90 * 60 * 1000, // 90 minutes before now
+ name: "Test Score",
+ value: 0.95,
+ }),
+ ]),
+ createEventsCh([event]),
+ ]);
- // Then
- const files = await s3StorageService.listFiles(s3Prefix);
- const projectFiles = files.filter((f) => f.file.includes(projectId));
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
- // Should have 3 files (traces, observations, scores)
- expect(projectFiles).toHaveLength(3);
+ // Then
+ const files = await s3StorageService.listFiles(s3Prefix);
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
- // Check file paths follow the expected pattern
- const traceFile = projectFiles.find((f) => f.file.includes("/traces/"));
- const observationFile = projectFiles.find((f) =>
- f.file.includes("/observations/"),
- );
- const scoreFile = projectFiles.find((f) => f.file.includes("/scores/"));
-
- expect(traceFile).toBeDefined();
- expect(observationFile).toBeDefined();
- expect(scoreFile).toBeDefined();
-
- // Check file contents
- if (traceFile) {
- const content = await s3StorageService.download(traceFile.file);
- expect(content).toContain(traceId);
- expect(content).toContain("Test Trace");
- }
-
- if (observationFile) {
- const content = await s3StorageService.download(observationFile.file);
- expect(content).toContain(observationId);
- expect(content).toContain("Test Observation");
- }
-
- if (scoreFile) {
- const content = await s3StorageService.download(scoreFile.file);
- expect(content).toContain(scoreId);
- expect(content).toContain("Test Score");
- expect(content).toContain("0.95");
- }
-
- // Check integration lastSyncAt and nextSyncAt are updated
- const updatedIntegration = await prisma.blobStorageIntegration.findUnique({
- where: { projectId },
- });
+ // Should have 4 files (traces, observations, scores, events)
+ expect(projectFiles).toHaveLength(4);
- if (updatedIntegration?.lastSyncAt && updatedIntegration?.nextSyncAt) {
- expect(updatedIntegration.lastSyncAt.getTime()).toBeGreaterThan(
- twoHoursAgo.getTime(),
+ // Check file paths follow the expected pattern
+ const traceFile = projectFiles.find((f) => f.file.includes("/traces/"));
+ const observationFile = projectFiles.find((f) =>
+ f.file.includes("/observations/"),
);
- expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
- now.getTime(),
+ const scoreFile = projectFiles.find((f) => f.file.includes("/scores/"));
+ const eventFile = projectFiles.find((f) =>
+ f.file.includes("/observations_v2/"),
);
- } else {
- expect.fail("Integration should have lastSyncAt and nextSyncAt set");
- }
- });
-
- it("should respect export frequency when setting nextSyncAt", async () => {
- const { projectId } = await createOrgProjectAndApiKey();
-
- // Setup for weekly export
- const now = new Date();
- const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
- await prisma.blobStorageIntegration.create({
- data: {
- projectId,
- type: BlobStorageIntegrationType.S3,
- bucketName,
- prefix: "",
- accessKeyId: minioAccessKeyId,
- secretAccessKey: encrypt(minioAccessKeySecret),
- region: region,
- endpoint: minioEndpoint,
- forcePathStyle:
- env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
- enabled: true,
- exportFrequency: "weekly",
- lastSyncAt: oneHourAgo,
- },
- });
-
- // Create test data
- const traceId = randomUUID();
- await createTracesCh([
- createTrace({
- id: traceId,
- project_id: projectId,
- timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
- }),
- ]);
+ expect(traceFile).toBeDefined();
+ expect(observationFile).toBeDefined();
+ expect(scoreFile).toBeDefined();
+ expect(eventFile).toBeDefined();
- // When
- await handleBlobStorageIntegrationProjectJob({
- data: { payload: { projectId } },
- } as Job);
+ // Check file contents
+ if (traceFile) {
+ const content = await s3StorageService.download(traceFile.file);
+ expect(content).toContain(traceId);
+ expect(content).toContain("Test Trace");
+ }
- // Then
- const updatedIntegration = await prisma.blobStorageIntegration.findUnique({
- where: { projectId },
- });
+ if (observationFile) {
+ const content = await s3StorageService.download(observationFile.file);
+ expect(content).toContain(observationId);
+ expect(content).toContain("Test Observation");
+ }
- // Should be set to 7 days in the future from maxTimestamp (now - 30min)
- const expectedNextSync = new Date(
- now.getTime() - 30 * 60 * 1000 + 7 * 24 * 60 * 60 * 1000,
- );
+ if (scoreFile) {
+ const content = await s3StorageService.download(scoreFile.file);
+ expect(content).toContain(scoreId);
+ expect(content).toContain("Test Score");
+ expect(content).toContain("0.95");
+ }
- if (updatedIntegration?.nextSyncAt) {
- // Use a tolerance value in milliseconds instead of numeric precision
- const tolerance = 1000; // 1 second tolerance
- expect(
- Math.abs(
- updatedIntegration.nextSyncAt.getTime() - expectedNextSync.getTime(),
- ),
- ).toBeLessThan(tolerance);
- } else {
- expect.fail("Integration should have nextSyncAt set");
- }
- });
+ if (eventFile) {
+ const content = await s3StorageService.download(eventFile.file);
+ expect(content).toContain(event.span_id);
+ expect(content).toContain("Test Event");
+ }
- it("should use prefix in file path when specified", async () => {
- // Setup
- const { projectId } = await createOrgProjectAndApiKey();
- s3Prefix = "test-prefix";
- const now = new Date();
- const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+ // Check integration lastSyncAt and nextSyncAt are updated
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
+ },
+ );
- 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: "daily",
- lastSyncAt: oneHourAgo,
- },
+ if (updatedIntegration?.lastSyncAt && updatedIntegration?.nextSyncAt) {
+ expect(updatedIntegration.lastSyncAt.getTime()).toBeGreaterThan(
+ twoHoursAgo.getTime(),
+ );
+ expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
+ now.getTime(),
+ );
+ } else {
+ expect.fail("Integration should have lastSyncAt and nextSyncAt set");
+ }
});
- // Create test data
- const traceId = randomUUID();
- await createTracesCh([
- createTrace({
- id: traceId,
- project_id: projectId,
- timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
- }),
- ]);
-
- // When
- await handleBlobStorageIntegrationProjectJob({
- data: { payload: { projectId } },
- } as Job);
-
- // Then
- const files = await storageService.listFiles(s3Prefix);
- const projectFiles = files.filter((f) => f.file.includes(projectId));
-
- // All files should have the prefix
- expect(projectFiles.every((f) => f.file.startsWith(s3Prefix))).toBe(true);
- });
+ it("should respect export frequency when setting nextSyncAt", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
- it("should handle CSV, JSON, and JSONL file types correctly", async () => {
- // Setup
- const { projectId } = await createOrgProjectAndApiKey();
- s3Prefix = `${projectId}/`;
- const now = new Date();
- const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+ // Setup for weekly export
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
- // Create test data
- const traceId = randomUUID();
- const observationId = randomUUID();
- const scoreId = randomUUID();
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: "",
+ accessKeyId: minioAccessKeyId,
+ secretAccessKey: encrypt(minioAccessKeySecret),
+ region: region,
+ endpoint: minioEndpoint,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "weekly",
+ lastSyncAt: oneHourAgo,
+ },
+ });
- await Promise.all([
- createTracesCh([
+ // Create test data
+ const traceId = randomUUID();
+ await createTracesCh([
createTrace({
id: traceId,
project_id: projectId,
- timestamp: now.getTime() - 40 * 60 * 1000, // 40 min before now
- name: "Test Trace",
- }),
- ]),
- createObservationsCh([
- createObservation({
- id: observationId,
- trace_id: traceId,
- project_id: projectId,
- start_time: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
- name: "Test Observation",
+ timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
}),
- ]),
- createScoresCh([
- createTraceScore({
- id: scoreId,
- trace_id: traceId,
- project_id: projectId,
- timestamp: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
- name: "Test Score",
- value: 0.95,
- }),
- ]),
- ]);
-
- // Test each file type
- for (const fileType of [
- BlobStorageIntegrationFileType.CSV,
- BlobStorageIntegrationFileType.JSON,
- BlobStorageIntegrationFileType.JSONL,
- ]) {
- const fileTypePrefix = `${fileType.toLowerCase()}-test/`;
- const prefix = `${s3Prefix}${fileTypePrefix}`;
-
- // Create integration with specific file type
- await prisma.blobStorageIntegration.upsert({
- where: { projectId },
- update: {
- prefix,
- fileType,
- lastSyncAt: oneHourAgo,
+ ]);
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: { projectId },
},
- create: {
+ );
+
+ // Should be set to 7 days in the future from maxTimestamp (now - 30min)
+ const expectedNextSync = new Date(
+ now.getTime() - 30 * 60 * 1000 + 7 * 24 * 60 * 60 * 1000,
+ );
+
+ if (updatedIntegration?.nextSyncAt) {
+ // Use a tolerance value in milliseconds instead of numeric precision
+ const tolerance = 1000; // 1 second tolerance
+ expect(
+ Math.abs(
+ updatedIntegration.nextSyncAt.getTime() -
+ expectedNextSync.getTime(),
+ ),
+ ).toBeLessThan(tolerance);
+ } else {
+ expect.fail("Integration should have nextSyncAt set");
+ }
+ });
+
+ it("should use prefix in file path when specified", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ s3Prefix = "test-prefix";
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ await prisma.blobStorageIntegration.create({
+ data: {
projectId,
type: BlobStorageIntegrationType.S3,
bucketName,
- prefix,
+ prefix: s3Prefix,
accessKeyId: minioAccessKeyId,
secretAccessKey: encrypt(minioAccessKeySecret),
region: region ? region : "auto",
@@ -412,71 +346,185 @@ describe("BlobStorageIntegrationProcessingJob", () => {
forcePathStyle:
env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
enabled: true,
- exportFrequency: "hourly",
- fileType,
+ exportFrequency: "daily",
lastSyncAt: oneHourAgo,
},
});
- // Process the integration
+ // Create test data
+ const traceId = randomUUID();
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
+ }),
+ ]);
+
+ // When
await handleBlobStorageIntegrationProjectJob({
data: { payload: { projectId } },
} as Job);
- // Get files for this file type
- const files = await s3StorageService.listFiles(prefix);
- const projectFiles = files.filter(
- (f) => f.file.includes(projectId) && f.file.includes(fileTypePrefix),
- );
+ // Then
+ const files = await storageService.listFiles(s3Prefix);
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
- // Should have 3 files (traces, observations, scores)
- expect(projectFiles).toHaveLength(3);
+ // All files should have the prefix
+ expect(projectFiles.every((f) => f.file.startsWith(s3Prefix))).toBe(true);
+ });
- // Check file extensions
- const expectedExtension = fileType.toLowerCase();
- expect(
- projectFiles.every((f) => f.file.endsWith(`.${expectedExtension}`)),
- ).toBe(true);
-
- // Check file contents for each type
- for (const file of projectFiles) {
- const content = await s3StorageService.download(file.file);
-
- // Verify content based on file type
- if (file.file.includes("/traces/")) {
- expect(content).toContain(traceId);
- expect(content).toContain("Test Trace");
- } else if (file.file.includes("/observations/")) {
- expect(content).toContain(observationId);
- expect(content).toContain("Test Observation");
- } else if (file.file.includes("/scores/")) {
- expect(content).toContain(scoreId);
- expect(content).toContain("Test Score");
- expect(content).toContain("0.95");
- }
+ it("should handle CSV, JSON, and JSONL file types correctly", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ s3Prefix = `${projectId}/`;
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ // Create test data
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const scoreId = randomUUID();
+
+ // Create event data for events table export
+ const event = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "Test Event",
+ start_time: (now.getTime() - 35 * 60 * 1000) * 1000, // 35 minutes before now (microseconds)
+ });
+
+ await Promise.all([
+ createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 40 * 60 * 1000, // 40 min before now
+ name: "Test Trace",
+ }),
+ ]),
+ createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Observation",
+ }),
+ ]),
+ createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ trace_id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Score",
+ value: 0.95,
+ }),
+ ]),
+ createEventsCh([event]),
+ ]);
+
+ // Test each file type
+ for (const fileType of [
+ BlobStorageIntegrationFileType.CSV,
+ BlobStorageIntegrationFileType.JSON,
+ BlobStorageIntegrationFileType.JSONL,
+ ]) {
+ const fileTypePrefix = `${fileType.toLowerCase()}-test/`;
+ const prefix = `${s3Prefix}${fileTypePrefix}`;
+
+ // Create integration with specific file type
+ await prisma.blobStorageIntegration.upsert({
+ where: { projectId },
+ update: {
+ prefix,
+ fileType,
+ lastSyncAt: oneHourAgo,
+ },
+ create: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix,
+ 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",
+ fileType,
+ lastSyncAt: oneHourAgo,
+ },
+ });
- // Verify format based on file type
- switch (fileType) {
- case BlobStorageIntegrationFileType.CSV:
- // CSV should have commas and newlines
- expect(content).toContain(",");
- break;
- case BlobStorageIntegrationFileType.JSON:
- // JSON should be parseable and have array brackets
- expect(content.trim().startsWith("[")).toBe(true);
- expect(content.trim().endsWith("]")).toBe(true);
- expect(() => JSON.parse(content)).not.toThrow();
- break;
- case BlobStorageIntegrationFileType.JSONL:
- // JSONL should have newlines and each line should be parseable JSON
- const lines = content.trim().split("\n");
- expect(lines.length).toBeGreaterThan(0);
- // Check first line is valid JSON
- expect(() => JSON.parse(lines[0])).not.toThrow();
- break;
+ // Process the integration
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Get files for this file type
+ const files = await s3StorageService.listFiles(prefix);
+ const projectFiles = files.filter(
+ (f) => f.file.includes(projectId) && f.file.includes(fileTypePrefix),
+ );
+
+ // Should have 4 files (traces, observations, scores, events)
+ expect(projectFiles).toHaveLength(4);
+
+ // Check file extensions
+ const expectedExtension = fileType.toLowerCase();
+ expect(
+ projectFiles.every((f) => f.file.endsWith(`.${expectedExtension}`)),
+ ).toBe(true);
+
+ // Check file contents for each type
+ for (const file of projectFiles) {
+ const content = await s3StorageService.download(file.file);
+
+ // Verify content based on file type
+ if (file.file.includes("/traces/")) {
+ expect(content).toContain(traceId);
+ expect(content).toContain("Test Trace");
+ } else if (file.file.includes("/observations/")) {
+ expect(content).toContain(observationId);
+ expect(content).toContain("Test Observation");
+ } else if (file.file.includes("/scores/")) {
+ expect(content).toContain(scoreId);
+ expect(content).toContain("Test Score");
+ expect(content).toContain("0.95");
+ } else if (file.file.includes("/events/")) {
+ expect(content).toContain(event.span_id);
+ expect(content).toContain("Test Event");
+ }
+
+ // Verify format based on file type
+ switch (fileType) {
+ case BlobStorageIntegrationFileType.CSV:
+ // CSV should have commas and newlines
+ expect(content).toContain(",");
+ break;
+ case BlobStorageIntegrationFileType.JSON:
+ // JSON should be parseable and have array brackets
+ expect(content.trim().startsWith("[")).toBe(true);
+ expect(content.trim().endsWith("]")).toBe(true);
+ expect(() => JSON.parse(content)).not.toThrow();
+ break;
+ case BlobStorageIntegrationFileType.JSONL:
+ // JSONL should have newlines and each line should be parseable JSON
+ const lines = content.trim().split("\n");
+ expect(lines.length).toBeGreaterThan(0);
+ // Check first line is valid JSON
+ expect(() => JSON.parse(lines[0])).not.toThrow();
+ break;
+ }
}
}
- }
+ });
});
describe("BlobStorageExportMode minTimestamp behavior", () => {
diff --git a/worker/src/__tests__/mixpanelTransformers.test.ts b/worker/src/__tests__/mixpanelTransformers.test.ts
new file mode 100644
index 0000000000..5ef721159a
--- /dev/null
+++ b/worker/src/__tests__/mixpanelTransformers.test.ts
@@ -0,0 +1,256 @@
+import { describe, it, expect } from "vitest";
+import {
+ transformTraceForMixpanel,
+ transformGenerationForMixpanel,
+ transformScoreForMixpanel,
+ transformEventForMixpanel,
+} from "../features/mixpanel/transformers";
+import type {
+ AnalyticsTraceEvent,
+ AnalyticsGenerationEvent,
+ AnalyticsScoreEvent,
+ AnalyticsObservationEvent,
+} from "@langfuse/shared/src/server";
+
+describe("Mixpanel transformers", () => {
+ const projectId = "test-project-id";
+
+ describe("transformEventForMixpanel", () => {
+ it("should transform an event with user_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "test-event",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_url:
+ "https://langfuse.com/project/test/traces/trace-456?observation=event-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.001,
+ langfuse_input_units: 100,
+ langfuse_output_units: 50,
+ langfuse_total_units: 150,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 1.5,
+ langfuse_time_to_first_token: 0.3,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_model: "gpt-4",
+ langfuse_level: "DEFAULT",
+ langfuse_type: "GENERATION",
+ langfuse_tags: ["tag1", "tag2"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-123",
+ mixpanel_session_id: "mixpanel-session-456",
+ };
+
+ const result = transformEventForMixpanel(event, projectId);
+
+ expect(result.event).toBe("[Langfuse] Observation");
+ expect(result.properties.distinct_id).toBe("user-789");
+ expect(result.properties.$user_id).toBe("user-789");
+ expect(result.properties.time).toBe(
+ new Date("2024-01-15T10:00:00Z").getTime(),
+ );
+ expect(result.properties.$insert_id).toBeDefined();
+ expect(result.properties.session_id).toBe("mixpanel-session-456");
+ expect(result.properties.langfuse_observation_name).toBe("test-event");
+ expect(result.properties.langfuse_trace_name).toBe("test-trace");
+ expect(result.properties.langfuse_model).toBe("gpt-4");
+ expect(result.properties.langfuse_type).toBe("GENERATION");
+ // Should not include posthog_session_id or mixpanel_session_id in properties
+ expect(result.properties.posthog_session_id).toBeUndefined();
+ expect(result.properties.mixpanel_session_id).toBeUndefined();
+ });
+
+ it("should transform an anonymous event without user_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-anonymous",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "anonymous-event",
+ langfuse_project_id: projectId,
+ langfuse_user_id: null,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: null,
+ };
+
+ const result = transformEventForMixpanel(event, projectId);
+
+ expect(result.event).toBe("[Langfuse] Observation");
+ // distinct_id should be the generated $insert_id when no user_id
+ expect(result.properties.distinct_id).toBe(result.properties.$insert_id);
+ // Should not have $user_id for anonymous events
+ expect(result.properties.$user_id).toBeUndefined();
+ expect(result.properties.session_id).toBeUndefined();
+ });
+
+ it("should generate consistent insert IDs for the same event", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-consistent",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "consistent-event",
+ langfuse_project_id: projectId,
+ langfuse_user_id: null,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: null,
+ };
+
+ const result1 = transformEventForMixpanel(event, projectId);
+ const result2 = transformEventForMixpanel(event, projectId);
+
+ expect(result1.properties.$insert_id).toBe(result2.properties.$insert_id);
+ });
+
+ it("should use langfuse_session_id when mixpanel_session_id is not available", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-with-langfuse-session",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "session-event",
+ langfuse_session_id: "langfuse-session-123",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-456",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: null,
+ };
+
+ const result = transformEventForMixpanel(event, projectId);
+
+ expect(result.properties.session_id).toBe("langfuse-session-123");
+ });
+
+ it("should prefer mixpanel_session_id over langfuse_session_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-with-both-sessions",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "session-event",
+ langfuse_session_id: "langfuse-session-123",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-456",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-789",
+ mixpanel_session_id: "mixpanel-session-456",
+ };
+
+ const result = transformEventForMixpanel(event, projectId);
+
+ expect(result.properties.session_id).toBe("mixpanel-session-456");
+ });
+ });
+
+ describe("transformTraceForMixpanel", () => {
+ it("should transform a trace with user_id", () => {
+ const trace: AnalyticsTraceEvent = {
+ langfuse_id: "trace-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_trace_name: "test-trace",
+ langfuse_url: "https://langfuse.com/project/test/traces/trace-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.01,
+ langfuse_count_observations: 5,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 2.5,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_tags: ["tag1"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: "mixpanel-session-123",
+ };
+
+ const result = transformTraceForMixpanel(trace, projectId);
+
+ expect(result.event).toBe("[Langfuse] Trace");
+ expect(result.properties.distinct_id).toBe("user-789");
+ expect(result.properties.$user_id).toBe("user-789");
+ expect(result.properties.session_id).toBe("mixpanel-session-123");
+ });
+ });
+
+ describe("transformGenerationForMixpanel", () => {
+ it("should transform a generation with user_id", () => {
+ const generation: AnalyticsGenerationEvent = {
+ langfuse_id: "gen-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_generation_name: "test-generation",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_url:
+ "https://langfuse.com/project/test/traces/trace-456?observation=gen-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.005,
+ langfuse_input_units: 200,
+ langfuse_output_units: 100,
+ langfuse_total_units: 300,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 1.2,
+ langfuse_time_to_first_token: 0.2,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_model: "gpt-4-turbo",
+ langfuse_level: "DEFAULT",
+ langfuse_tags: ["api"],
+ langfuse_environment: "staging",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: "mixpanel-session-456",
+ };
+
+ const result = transformGenerationForMixpanel(generation, projectId);
+
+ expect(result.event).toBe("[Langfuse] Generation");
+ expect(result.properties.distinct_id).toBe("user-789");
+ expect(result.properties.$user_id).toBe("user-789");
+ expect(result.properties.session_id).toBe("mixpanel-session-456");
+ expect(result.properties.langfuse_model).toBe("gpt-4-turbo");
+ });
+ });
+
+ describe("transformScoreForMixpanel", () => {
+ it("should transform a score with user_id", () => {
+ const score: AnalyticsScoreEvent = {
+ langfuse_id: "score-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_score_name: "quality",
+ langfuse_score_value: 0.95,
+ langfuse_score_comment: "Good response",
+ langfuse_score_metadata: { source: "human" },
+ langfuse_score_string_value: null,
+ langfuse_score_data_type: "NUMERIC",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_release: "v1.0.0",
+ langfuse_tags: ["human-eval"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ langfuse_score_entity_type: "trace",
+ langfuse_dataset_run_id: null,
+ posthog_session_id: null,
+ mixpanel_session_id: "mixpanel-session-789",
+ };
+
+ const result = transformScoreForMixpanel(score, projectId);
+
+ expect(result.event).toBe("[Langfuse] Score");
+ expect(result.properties.distinct_id).toBe("user-789");
+ expect(result.properties.$user_id).toBe("user-789");
+ expect(result.properties.session_id).toBe("mixpanel-session-789");
+ expect(result.properties.langfuse_score_name).toBe("quality");
+ expect(result.properties.langfuse_score_value).toBe(0.95);
+ });
+ });
+});
diff --git a/worker/src/__tests__/posthogTransformers.test.ts b/worker/src/__tests__/posthogTransformers.test.ts
new file mode 100644
index 0000000000..b23f36f043
--- /dev/null
+++ b/worker/src/__tests__/posthogTransformers.test.ts
@@ -0,0 +1,238 @@
+import { describe, it, expect } from "vitest";
+import {
+ transformTraceForPostHog,
+ transformGenerationForPostHog,
+ transformScoreForPostHog,
+ transformEventForPostHog,
+} from "../features/posthog/transformers";
+import type {
+ AnalyticsTraceEvent,
+ AnalyticsGenerationEvent,
+ AnalyticsScoreEvent,
+ AnalyticsObservationEvent,
+} from "@langfuse/shared/src/server";
+
+describe("PostHog transformers", () => {
+ const projectId = "test-project-id";
+
+ describe("transformEventForPostHog", () => {
+ it("should transform an event with user_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "test-event",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_url:
+ "https://langfuse.com/project/test/traces/trace-456?observation=event-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.001,
+ langfuse_input_units: 100,
+ langfuse_output_units: 50,
+ langfuse_total_units: 150,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 1.5,
+ langfuse_time_to_first_token: 0.3,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_model: "gpt-4",
+ langfuse_level: "DEFAULT",
+ langfuse_type: "GENERATION",
+ langfuse_tags: ["tag1", "tag2"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-123",
+ mixpanel_session_id: "mixpanel-session-456",
+ };
+
+ const result = transformEventForPostHog(event, projectId);
+
+ expect(result.event).toBe("langfuse observation");
+ expect(result.distinctId).toBe("user-789");
+ expect(result.timestamp).toEqual(new Date("2024-01-15T10:00:00Z"));
+ expect(result.uuid).toBeDefined();
+ expect(result.properties.$session_id).toBe("posthog-session-123");
+ expect(result.properties.langfuse_observation_name).toBe("test-event");
+ expect(result.properties.langfuse_trace_name).toBe("test-trace");
+ expect(result.properties.langfuse_model).toBe("gpt-4");
+ expect(result.properties.langfuse_type).toBe("GENERATION");
+ expect(result.properties.$set).toEqual({
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ });
+ // Should not include posthog_session_id or mixpanel_session_id in properties
+ expect(result.properties.posthog_session_id).toBeUndefined();
+ expect(result.properties.mixpanel_session_id).toBeUndefined();
+ });
+
+ it("should transform an anonymous event without user_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-anonymous",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "anonymous-event",
+ langfuse_project_id: projectId,
+ langfuse_user_id: null,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: null,
+ };
+
+ const result = transformEventForPostHog(event, projectId);
+
+ expect(result.event).toBe("langfuse observation");
+ // distinctId should be the generated UUID when no user_id
+ expect(result.distinctId).toBe(result.uuid);
+ expect(result.properties.$session_id).toBeNull();
+ // Should have $process_person_profile: false for anonymous events
+ expect(result.properties.$process_person_profile).toBe(false);
+ expect(result.properties.$set).toBeUndefined();
+ });
+
+ it("should generate consistent UUIDs for the same event", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-consistent",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "consistent-event",
+ langfuse_project_id: projectId,
+ langfuse_user_id: null,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: null,
+ mixpanel_session_id: null,
+ };
+
+ const result1 = transformEventForPostHog(event, projectId);
+ const result2 = transformEventForPostHog(event, projectId);
+
+ expect(result1.uuid).toBe(result2.uuid);
+ });
+
+ it("should handle event with session_id but no user_id", () => {
+ const event: AnalyticsObservationEvent = {
+ langfuse_id: "event-with-session",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_observation_name: "session-event",
+ langfuse_session_id: "session-123",
+ langfuse_project_id: projectId,
+ langfuse_user_id: null,
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-abc",
+ mixpanel_session_id: null,
+ };
+
+ const result = transformEventForPostHog(event, projectId);
+
+ expect(result.properties.$session_id).toBe("posthog-session-abc");
+ expect(result.properties.langfuse_session_id).toBe("session-123");
+ expect(result.properties.$process_person_profile).toBe(false);
+ });
+ });
+
+ describe("transformTraceForPostHog", () => {
+ it("should transform a trace with user_id", () => {
+ const trace: AnalyticsTraceEvent = {
+ langfuse_id: "trace-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_trace_name: "test-trace",
+ langfuse_url: "https://langfuse.com/project/test/traces/trace-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.01,
+ langfuse_count_observations: 5,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 2.5,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_tags: ["tag1"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-123",
+ mixpanel_session_id: null,
+ };
+
+ const result = transformTraceForPostHog(trace, projectId);
+
+ expect(result.event).toBe("langfuse trace");
+ expect(result.distinctId).toBe("user-789");
+ expect(result.properties.$session_id).toBe("posthog-session-123");
+ });
+ });
+
+ describe("transformGenerationForPostHog", () => {
+ it("should transform a generation with user_id", () => {
+ const generation: AnalyticsGenerationEvent = {
+ langfuse_id: "gen-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_generation_name: "test-generation",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_url:
+ "https://langfuse.com/project/test/traces/trace-456?observation=gen-123",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_cost_usd: 0.005,
+ langfuse_input_units: 200,
+ langfuse_output_units: 100,
+ langfuse_total_units: 300,
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_latency: 1.2,
+ langfuse_time_to_first_token: 0.2,
+ langfuse_release: "v1.0.0",
+ langfuse_version: "1",
+ langfuse_model: "gpt-4-turbo",
+ langfuse_level: "DEFAULT",
+ langfuse_tags: ["api"],
+ langfuse_environment: "staging",
+ langfuse_event_version: "1.0.0",
+ posthog_session_id: "posthog-session-456",
+ mixpanel_session_id: null,
+ };
+
+ const result = transformGenerationForPostHog(generation, projectId);
+
+ expect(result.event).toBe("langfuse generation");
+ expect(result.distinctId).toBe("user-789");
+ expect(result.properties.$session_id).toBe("posthog-session-456");
+ expect(result.properties.langfuse_model).toBe("gpt-4-turbo");
+ });
+ });
+
+ describe("transformScoreForPostHog", () => {
+ it("should transform a score with user_id", () => {
+ const score: AnalyticsScoreEvent = {
+ langfuse_id: "score-123",
+ timestamp: new Date("2024-01-15T10:00:00Z"),
+ langfuse_score_name: "quality",
+ langfuse_score_value: 0.95,
+ langfuse_score_comment: "Good response",
+ langfuse_score_metadata: { source: "human" },
+ langfuse_score_string_value: null,
+ langfuse_score_data_type: "NUMERIC",
+ langfuse_trace_name: "test-trace",
+ langfuse_trace_id: "trace-456",
+ langfuse_user_url: "https://langfuse.com/project/test/users/user-789",
+ langfuse_session_id: "session-abc",
+ langfuse_project_id: projectId,
+ langfuse_user_id: "user-789",
+ langfuse_release: "v1.0.0",
+ langfuse_tags: ["human-eval"],
+ langfuse_environment: "production",
+ langfuse_event_version: "1.0.0",
+ langfuse_score_entity_type: "trace",
+ langfuse_dataset_run_id: null,
+ posthog_session_id: "posthog-session-789",
+ mixpanel_session_id: null,
+ };
+
+ const result = transformScoreForPostHog(score, projectId);
+
+ expect(result.event).toBe("langfuse score");
+ expect(result.distinctId).toBe("user-789");
+ expect(result.properties.$session_id).toBe("posthog-session-789");
+ expect(result.properties.langfuse_score_name).toBe("quality");
+ expect(result.properties.langfuse_score_value).toBe(0.95);
+ });
+ });
+});
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index ad224a98f0..258d4fe9b5 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -22,6 +22,7 @@ import { env } from "../../env";
import { getDatabaseReadStreamPaginated } from "../database-read-stream/getDatabaseReadStream";
import { getObservationStream } from "../database-read-stream/observation-stream";
import { getTraceStream } from "../database-read-stream/trace-stream";
+import { getEventsStream } from "../database-read-stream/event-stream";
// Map table names to comment object types for preprocessing
const tableToCommentType: Record<string, CommentObjectType | undefined> = {
@@ -183,12 +184,19 @@ export const handleBatchExportJob = async (
...parsedQuery.data,
filter: processedFilter,
})
- : await getDatabaseReadStreamPaginated({
- projectId,
- cutoffCreatedAt: jobDetails.createdAt,
- ...parsedQuery.data,
- filter: processedFilter,
- });
+ : parsedQuery.data.tableName === BatchExportTableName.Events
+ ? await getEventsStream({
+ projectId,
+ cutoffCreatedAt: jobDetails.createdAt,
+ ...parsedQuery.data,
+ filter: processedFilter,
+ })
+ : await getDatabaseReadStreamPaginated({
+ projectId,
+ cutoffCreatedAt: jobDetails.createdAt,
+ ...parsedQuery.data,
+ filter: processedFilter,
+ });
// Transform data to desired format
let rowCount = 0;
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 7a5f3c6b8d..330646e024 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -11,6 +11,7 @@ import {
getObservationsForBlobStorageExport,
getTracesForBlobStorageExport,
getScoresForBlobStorageExport,
+ getEventsForBlobStorageExport,
getCurrentSpan,
BlobStorageIntegrationProcessingQueue,
queryClickhouse,
@@ -155,7 +156,7 @@ const processBlobStorageExport = async (config: {
prefix?: string;
forcePathStyle?: boolean;
type: BlobStorageIntegrationType;
- table: "traces" | "observations" | "scores";
+ table: "traces" | "observations" | "scores" | "observations_v2"; // observations_v2 is the events table
fileType: BlobStorageIntegrationFileType;
}) => {
logger.info(
@@ -211,6 +212,13 @@ const processBlobStorageExport = async (config: {
config.maxTimestamp,
);
break;
+ case "observations_v2": // observations_v2 is the events table
+ dataStream = getEventsForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+ break;
default:
throw new Error(`Unsupported table type: ${config.table}`);
}
@@ -347,25 +355,56 @@ export const handleBlobStorageIntegrationProjectJob = async (
fileType: blobStorageIntegration.fileType,
};
- // Check if this project should only export traces
+ // Check if this project should only export traces (legacy behavior via env var)
const isTraceOnlyProject =
env.LANGFUSE_BLOB_STORAGE_EXPORT_TRACE_ONLY_PROJECT_IDS.includes(
projectId,
);
if (isTraceOnlyProject) {
- // Only process traces table for projects in the trace-only list
+ // Only process traces table for projects in the trace-only list (legacy behavior)
logger.info(
- `[BLOB INTEGRATION] Project ${projectId} is configured for trace-only export, skipping observations and scores`,
+ `[BLOB INTEGRATION] Project ${projectId} is configured for trace-only export via env var, skipping observations, scores, and events`,
);
await processBlobStorageExport({ ...executionConfig, table: "traces" });
} else {
- // Process all tables for projects not in the trace-only list
- await Promise.all([
- processBlobStorageExport({ ...executionConfig, table: "traces" }),
- processBlobStorageExport({ ...executionConfig, table: "observations" }),
+ // Process tables based on exportSource setting
+ const processPromises: Promise<void>[] = [];
+
+ // Always include scores
+ processPromises.push(
processBlobStorageExport({ ...executionConfig, table: "scores" }),
- ]);
+ );
+
+ // Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS
+ if (
+ blobStorageIntegration.exportSource === "TRACES_OBSERVATIONS" ||
+ blobStorageIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(
+ processBlobStorageExport({ ...executionConfig, table: "traces" }),
+ processBlobStorageExport({
+ ...executionConfig,
+ table: "observations",
+ }),
+ );
+ }
+
+ // Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS
+ // events are stored in the observations_v2 directory in blob storage
+ if (
+ blobStorageIntegration.exportSource === "EVENTS" ||
+ blobStorageIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(
+ processBlobStorageExport({
+ ...executionConfig,
+ table: "observations_v2",
+ }),
+ );
+ }
+
+ await Promise.all(processPromises);
}
// Determine if we've caught up with present-day data
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
new file mode 100644
index 0000000000..4b5d368d68
--- /dev/null
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -0,0 +1,339 @@
+/**
+ * Event stream for batch exports.
+ * Queries the ClickHouse events table with filters and streams results
+ * for efficient batch export processing.
+ *
+ * The events table is denormalized with trace data already included,
+ * so no JOINs are needed for trace-level fields.
+ */
+
+import {
+ FilterCondition,
+ ScoreDataTypeEnum,
+ type ScoreDataTypeType,
+ TimeFilter,
+ TracingSearchType,
+} from "@langfuse/shared";
+import {
+ getDistinctScoreNames,
+ queryClickhouseStream,
+ logger,
+ FilterList,
+ createFilterFromFilterState,
+ eventsTableUiColumnDefinitions,
+ clickhouseSearchCondition,
+ EventsQueryBuilder,
+ eventsScoresAggregation,
+} from "@langfuse/shared/src/server";
+import { Readable } from "stream";
+import { env } from "../../env";
+import {
+ getChunkWithFlattenedScores,
+ prepareScoresForOutput,
+} from "./getDatabaseReadStream";
+import { fetchCommentsForExport } from "./fetchCommentsForExport";
+import { BatchExportEventsRow } from "./types";
+
+const BATCH_SIZE = 1000; // Fetch comments in batches for efficiency
+
+/**
+ * Creates a stream of events from ClickHouse for batch export.
+ * Includes comments fetched in batches and flattened scores.
+ *
+ * @param props - Query parameters including projectId, filters, and limits
+ * @returns A Node.js Readable stream of event records
+ */
+export const getEventsStream = async (props: {
+ projectId: string;
+ cutoffCreatedAt: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit?: number;
+}): Promise<Readable> => {
+ const {
+ projectId,
+ cutoffCreatedAt,
+ filter = [],
+ searchQuery,
+ searchType,
+ rowLimit = env.BATCH_EXPORT_ROW_LIMIT,
+ } = props;
+
+ const clickhouseConfigs = {
+ request_timeout: 180_000, // 3 minutes
+ clickhouse_settings: {
+ join_algorithm: "partial_merge" as const,
+ // Increase HTTP timeouts to prevent Code 209 errors during slow blob storage uploads
+ // See: https://github.com/ClickHouse/ClickHouse/issues/64731
+ http_send_timeout: 300,
+ http_receive_timeout: 300,
+ },
+ };
+
+ // Filter out score and comment filters since they require special handling
+ const eventOnlyFilters = (filter ?? []).filter((f) => {
+ const columnDef = eventsTableUiColumnDefinitions.find(
+ (col) => col.uiTableName === f.column || col.uiTableId === f.column,
+ );
+ // Keep the filter if it's not a scores or comments filter
+ return (
+ columnDef?.clickhouseTableName !== "scores" &&
+ columnDef?.clickhouseTableName !== "comments"
+ );
+ });
+
+ // Get distinct score names for empty columns
+ const distinctScoreNames = await getDistinctScoreNames({
+ projectId,
+ cutoffCreatedAt,
+ filter: eventOnlyFilters,
+ isTimestampFilter: (
+ filterItem: FilterCondition,
+ ): filterItem is TimeFilter =>
+ filterItem.column === "Start Time" && filterItem.type === "datetime",
+ clickhouseConfigs,
+ });
+
+ const emptyScoreColumns = distinctScoreNames.reduce(
+ (acc, name) => ({ ...acc, [name]: null }),
+ {} as Record<string, null>,
+ );
+
+ // Build filters for events (project_id is handled by the query builder)
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ [
+ ...eventOnlyFilters,
+ {
+ column: "startTime",
+ operator: "<" as const,
+ value: cutoffCreatedAt,
+ type: "datetime" as const,
+ },
+ ],
+ eventsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedEventsFilter = eventsFilter.apply();
+
+ const search = clickhouseSearchCondition(searchQuery, searchType, "e", [
+ "span_id",
+ "name",
+ "user_id",
+ "session_id",
+ "trace_id",
+ ]);
+
+ // Build the query using EventsQueryBuilder
+ const eventsQuery = new EventsQueryBuilder({ projectId })
+ .selectFieldSet("export")
+ .selectIO(false) // Full I/O, no truncation
+ .selectMetadataDirect() // Use direct JSON metadata column
+ .selectRaw(
+ "s.scores_avg as scores_avg",
+ "s.score_categories as score_categories",
+ )
+ .withCTE("scores_agg", eventsScoresAggregation({ projectId }))
+ .leftJoin(
+ "scores_agg s",
+ "ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",
+ )
+ .where(appliedEventsFilter)
+ .where(search)
+ .whereRaw("e.is_deleted = 0")
+ .orderByDefault()
+ .limitBy("e.span_id", "e.project_id")
+ .limit(rowLimit);
+
+ const { query, params: queryParams } = eventsQuery.buildWithParams();
+
+ type EventRow = {
+ id: string;
+ trace_id: string;
+ project_id: string;
+ start_time: Date;
+ end_time: Date | null;
+ name: string | null;
+ type: string;
+ environment: string | null;
+ version: string | null;
+ user_id: string | null;
+ session_id: string | null;
+ level: string;
+ status_message: string | null;
+ prompt_name: string | null;
+ prompt_id: string | null;
+ prompt_version: number | null;
+ model_id: string | null;
+ provided_model_name: string | null;
+ model_parameters: unknown;
+ usage_details: Record<string, number>;
+ cost_details: Record<string, number>;
+ total_cost: number | null;
+ input: unknown;
+ output: unknown;
+ metadata: Record<string, unknown>;
+ completion_start_time: Date | null;
+ latency: number | null;
+ time_to_first_token: number | null;
+ tags: string[];
+ release: string | null;
+ trace_name: string | null;
+ parent_observation_id: string | null;
+ scores_avg:
+ | {
+ name: string;
+ value: number;
+ dataType: ScoreDataTypeType;
+ stringValue: string;
+ }[]
+ | undefined;
+ score_categories: string[] | undefined;
+ };
+
+ const asyncGenerator = queryClickhouseStream<EventRow>({
+ query,
+ params: queryParams,
+ clickhouseConfigs,
+ tags: {
+ feature: "batch-export",
+ type: "event",
+ kind: "export",
+ projectId,
+ },
+ });
+
+ // Helper function to process a single event row
+ const processEventRow = (
+ bufferedRow: EventRow,
+ commentsByEvent: Map<string, any[]>,
+ ) => {
+ // Process numeric/boolean scores (tuples from ClickHouse)
+ const numericScores = (bufferedRow.scores_avg ?? []).map((score: any) => ({
+ name: score[0],
+ value: score[1],
+ dataType: score[2],
+ stringValue: score[3],
+ }));
+
+ // Process categorical scores (format: "name:value")
+ const categoricalScores = (bufferedRow.score_categories ?? []).map(
+ (cat: string) => {
+ const [name, ...valueParts] = cat.split(":");
+ return {
+ name,
+ value: null,
+ dataType: ScoreDataTypeEnum.CATEGORICAL,
+ stringValue: valueParts.join(":"),
+ };
+ },
+ );
+
+ const outputScores: Record<string, string[] | number[]> =
+ prepareScoresForOutput([...numericScores, ...categoricalScores]);
+
+ // Get comments for this event (events use OBSERVATION type since they are observations)
+ const eventComments = commentsByEvent.get(bufferedRow.id) ?? [];
+
+ const eventRow: BatchExportEventsRow = {
+ id: bufferedRow.id,
+ traceId: bufferedRow.trace_id,
+ traceName: bufferedRow.trace_name,
+ type: bufferedRow.type,
+ name: bufferedRow.name ?? "",
+ startTime: bufferedRow.start_time,
+ endTime: bufferedRow.end_time,
+ completionStartTime: bufferedRow.completion_start_time,
+ environment: bufferedRow.environment,
+ version: bufferedRow.version,
+ userId: bufferedRow.user_id,
+ sessionId: bufferedRow.session_id,
+ level: bufferedRow.level,
+ statusMessage: bufferedRow.status_message,
+ promptName: bufferedRow.prompt_name,
+ promptId: bufferedRow.prompt_id,
+ promptVersion: bufferedRow.prompt_version,
+ modelId: bufferedRow.model_id,
+ providedModelName: bufferedRow.provided_model_name,
+ modelParameters: bufferedRow.model_parameters,
+ usageDetails: bufferedRow.usage_details,
+ costDetails: bufferedRow.cost_details,
+ totalCost: bufferedRow.total_cost,
+ input: bufferedRow.input,
+ output: bufferedRow.output,
+ metadata: bufferedRow.metadata,
+ latencyMs: bufferedRow.latency,
+ timeToFirstTokenMs: bufferedRow.time_to_first_token,
+ tags: bufferedRow.tags,
+ release: bufferedRow.release,
+ parentObservationId: bufferedRow.parent_observation_id,
+ scores: outputScores,
+ comments: eventComments,
+ };
+
+ return getChunkWithFlattenedScores([eventRow], emptyScoreColumns)[0];
+ };
+
+ // Convert async generator to Node.js Readable stream
+ let recordsProcessed = 0;
+
+ return Readable.from(
+ (async function* () {
+ let rowBuffer: EventRow[] = [];
+ let eventIds: string[] = [];
+
+ for await (const row of asyncGenerator) {
+ rowBuffer.push(row);
+ eventIds.push(row.id);
+
+ // Process in batches
+ if (rowBuffer.length >= BATCH_SIZE) {
+ // Fetch comments for this batch (events are observations)
+ const commentsByEvent = await fetchCommentsForExport(
+ projectId,
+ "OBSERVATION",
+ eventIds,
+ );
+
+ // Process each row in the buffer
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+ if (recordsProcessed % 10000 === 0) {
+ logger.info(
+ `Streaming events for project ${projectId}: processed ${recordsProcessed} rows`,
+ );
+ }
+
+ yield processEventRow(bufferedRow, commentsByEvent);
+ }
+
+ // Reset buffers
+ rowBuffer = [];
+ eventIds = [];
+ }
+ }
+
+ // Process remaining rows in buffer
+ if (rowBuffer.length > 0) {
+ const commentsByEvent = await fetchCommentsForExport(
+ projectId,
+ "OBSERVATION",
+ eventIds,
+ );
+
+ for (const bufferedRow of rowBuffer) {
+ recordsProcessed++;
+ if (recordsProcessed % 10000 === 0) {
+ logger.info(
+ `Streaming events for project ${projectId}: processed ${recordsProcessed} rows`,
+ );
+ }
+
+ yield processEventRow(bufferedRow, commentsByEvent);
+ }
+ }
+ })(),
+ );
+};
diff --git a/worker/src/features/database-read-stream/getDatabaseReadStream.ts b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
index ef06dcd662..d252658370 100644
--- a/worker/src/features/database-read-stream/getDatabaseReadStream.ts
+++ b/worker/src/features/database-read-stream/getDatabaseReadStream.ts
@@ -28,7 +28,11 @@ import {
} from "@langfuse/shared/src/server";
import Decimal from "decimal.js";
import { env } from "../../env";
-import { BatchExportTracesRow, BatchExportSessionsRow } from "./types";
+import {
+ BatchExportTracesRow,
+ BatchExportSessionsRow,
+ BatchExportEventsRow,
+} from "./types";
import { fetchCommentsForExport } from "./fetchCommentsForExport";
const tableNameToTimeFilterColumn: Record<BatchTableNames, string> = {
@@ -36,6 +40,7 @@ const tableNameToTimeFilterColumn: Record<BatchTableNames, string> = {
sessions: "createdAt",
traces: "timestamp",
observations: "startTime",
+ events: "startTime",
dataset_run_items: "createdAt",
dataset_items: "createdAt", // TODO: flip to validFrom once we write in new format
audit_logs: "createdAt",
@@ -45,6 +50,7 @@ const tableNameToTimeFilterColumnCh: Record<BatchTableNames, string> = {
sessions: "createdAt",
traces: "timestamp",
observations: "startTime",
+ events: "startTime",
dataset_run_items: "createdAt",
dataset_items: "createdAt",
audit_logs: "createdAt",
@@ -60,7 +66,10 @@ export const isTraceTimestampFilter = (
return filter.column === "Timestamp" && filter.type === "datetime";
};
export const getChunkWithFlattenedScores = <
- T extends BatchExportTracesRow[] | FullObservationsWithScores,
+ T extends
+ | BatchExportTracesRow[]
+ | FullObservationsWithScores
+ | BatchExportEventsRow[],
>(
chunk: T,
emptyScoreColumns: Record<string, null>,
diff --git a/worker/src/features/database-read-stream/types.ts b/worker/src/features/database-read-stream/types.ts
index ec2199c663..2fefbfec1c 100644
--- a/worker/src/features/database-read-stream/types.ts
+++ b/worker/src/features/database-read-stream/types.ts
@@ -33,3 +33,39 @@ export type BatchExportTracesRow = {
metadata?: unknown | null;
tags: string[];
};
+
+export type BatchExportEventsRow = {
+ id: string;
+ traceId: string;
+ traceName: string | null;
+ type: string;
+ name: string;
+ startTime: Date;
+ endTime: Date | null;
+ completionStartTime: Date | null;
+ environment: string | null;
+ version: string | null;
+ userId: string | null;
+ sessionId: string | null;
+ level: string;
+ statusMessage: string | null;
+ promptName: string | null;
+ promptId: string | null;
+ promptVersion: number | null;
+ modelId: string | null;
+ providedModelName: string | null;
+ modelParameters: unknown;
+ usageDetails: Record<string, number>;
+ costDetails: Record<string, number>;
+ totalCost: number | null;
+ input: unknown;
+ output: unknown;
+ metadata: Record<string, unknown>;
+ latencyMs: number | null;
+ timeToFirstTokenMs: number | null;
+ tags: string[];
+ release: string | null;
+ parentObservationId: string | null;
+ scores?: Record<string, string[] | number[]> | null;
+ comments: unknown[];
+};
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index d15d8dc86f..af3f0f7a07 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -7,6 +7,7 @@ import {
getTracesForAnalyticsIntegrations,
getGenerationsForAnalyticsIntegrations,
getScoresForAnalyticsIntegrations,
+ getEventsForAnalyticsIntegrations,
getCurrentSpan,
} from "@langfuse/shared/src/server";
import { decrypt } from "@langfuse/shared/encryption";
@@ -15,6 +16,7 @@ import {
transformTraceForMixpanel,
transformGenerationForMixpanel,
transformScoreForMixpanel,
+ transformEventForMixpanel,
} from "./transformers";
type MixpanelExecutionConfig = {
@@ -130,6 +132,41 @@ const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
);
};
+const processMixpanelEvents = async (config: MixpanelExecutionConfig) => {
+ const events = getEventsForAnalyticsIntegrations(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+
+ logger.info(
+ `[MIXPANEL] Sending events for project ${config.projectId} to Mixpanel`,
+ );
+
+ const mixpanel = new MixpanelClient({
+ projectToken: config.decryptedMixpanelProjectToken,
+ region: config.mixpanelRegion,
+ });
+
+ let count = 0;
+ for await (const analyticsEvent of events) {
+ count++;
+ const event = transformEventForMixpanel(analyticsEvent, config.projectId);
+ mixpanel.addEvent(event);
+
+ if (count % 1000 === 0) {
+ await mixpanel.flush();
+ logger.info(
+ `[MIXPANEL] Sent ${count} events to Mixpanel for project ${config.projectId}`,
+ );
+ }
+ }
+ await mixpanel.flush();
+ logger.info(
+ `[MIXPANEL] Sent ${count} events to Mixpanel for project ${config.projectId}`,
+ );
+};
+
export const handleMixpanelIntegrationProjectJob = async (
job: Job<TQueueJobTypes[QueueName.MixpanelIntegrationProcessingQueue]>,
) => {
@@ -173,11 +210,31 @@ export const handleMixpanelIntegrationProjectJob = async (
};
try {
- await Promise.all([
- processMixpanelTraces(executionConfig),
- processMixpanelGenerations(executionConfig),
- processMixpanelScores(executionConfig),
- ]);
+ const processPromises: Promise<void>[] = [];
+
+ // Always include scores
+ processPromises.push(processMixpanelScores(executionConfig));
+
+ // Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS
+ if (
+ mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS" ||
+ mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(
+ processMixpanelTraces(executionConfig),
+ processMixpanelGenerations(executionConfig),
+ );
+ }
+
+ // Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS
+ if (
+ mixpanelIntegration.exportSource === "EVENTS" ||
+ mixpanelIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(processMixpanelEvents(executionConfig));
+ }
+
+ await Promise.all(processPromises);
// Update the last run information for the mixpanelIntegration record.
await prisma.mixpanelIntegration.update({
diff --git a/worker/src/features/mixpanel/transformers.ts b/worker/src/features/mixpanel/transformers.ts
index 2c7e06cb81..10512f2a6d 100644
--- a/worker/src/features/mixpanel/transformers.ts
+++ b/worker/src/features/mixpanel/transformers.ts
@@ -3,6 +3,7 @@ import type {
AnalyticsTraceEvent,
AnalyticsGenerationEvent,
AnalyticsScoreEvent,
+ AnalyticsObservationEvent,
} from "@langfuse/shared/src/server";
// UUID v5 namespace for Mixpanel (different from PostHog)
@@ -121,3 +122,37 @@ export const transformScoreForMixpanel = (
},
};
};
+
+export const transformEventForMixpanel = (
+ event: AnalyticsObservationEvent,
+ projectId: string,
+): MixpanelEvent => {
+ const insertId = v5(
+ `${projectId}-${event.langfuse_id}`,
+ MIXPANEL_UUID_NAMESPACE,
+ );
+
+ // Extract session IDs and exclude from properties
+
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = event;
+
+ return {
+ event: "[Langfuse] Observation",
+ properties: {
+ time: new Date(event.timestamp as Date).getTime(),
+ distinct_id: event.langfuse_user_id
+ ? (event.langfuse_user_id as string)
+ : insertId,
+ $insert_id: insertId,
+ ...(event.langfuse_user_id
+ ? { $user_id: event.langfuse_user_id as string }
+ : {}),
+ session_id:
+ mixpanel_session_id || event.langfuse_session_id
+ ? (mixpanel_session_id as string) ||
+ (event.langfuse_session_id as string)
+ : undefined,
+ ...otherProps,
+ },
+ };
+};
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index d12d6062a1..9a6c8e98d3 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -7,12 +7,14 @@ import {
getTracesForAnalyticsIntegrations,
getGenerationsForAnalyticsIntegrations,
getScoresForAnalyticsIntegrations,
+ getEventsForAnalyticsIntegrations,
getCurrentSpan,
validateWebhookURL,
} from "@langfuse/shared/src/server";
import {
transformTraceForPostHog,
transformGenerationForPostHog,
+ transformEventForPostHog,
transformScoreForPostHog,
} from "./transformers";
import { decrypt } from "@langfuse/shared/encryption";
@@ -168,6 +170,51 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {
);
};
+const processPostHogEvents = async (config: PostHogExecutionConfig) => {
+ const events = getEventsForAnalyticsIntegrations(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+
+ logger.info(
+ `[POSTHOG] Sending events for project ${config.projectId} to PostHog`,
+ );
+
+ // Send each via PostHog SDK
+ const posthog = new PostHog(config.decryptedPostHogApiKey, {
+ host: config.postHogHost,
+ ...postHogSettings,
+ });
+
+ let sendError: Error | undefined;
+ posthog.on("error", (error) => {
+ logger.error(
+ `[POSTHOG] Error sending events to PostHog for project ${config.projectId}: ${error}`,
+ );
+ sendError = error instanceof Error ? error : new Error(String(error));
+ });
+
+ let count = 0;
+ for await (const analyticsEvent of events) {
+ if (sendError) throw sendError;
+ count++;
+ const event = transformEventForPostHog(analyticsEvent, config.projectId);
+ posthog.capture(event);
+ if (count % 10000 === 0) {
+ await posthog.flush();
+ logger.info(
+ `[POSTHOG] Sent ${count} events to PostHog for project ${config.projectId}`,
+ );
+ }
+ }
+ await posthog.flush();
+ if (sendError) throw sendError;
+ logger.info(
+ `[POSTHOG] Sent ${count} events to PostHog for project ${config.projectId}`,
+ );
+};
+
export const handlePostHogIntegrationProjectJob = async (
job: Job<TQueueJobTypes[QueueName.PostHogIntegrationProcessingQueue]>,
) => {
@@ -221,11 +268,31 @@ export const handlePostHogIntegrationProjectJob = async (
};
try {
- await Promise.all([
- processPostHogTraces(executionConfig),
- processPostHogGenerations(executionConfig),
- processPostHogScores(executionConfig),
- ]);
+ const processPromises: Promise<void>[] = [];
+
+ // Always include scores
+ processPromises.push(processPostHogScores(executionConfig));
+
+ // Traces and observations - for TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS
+ if (
+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS" ||
+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(
+ processPostHogTraces(executionConfig),
+ processPostHogGenerations(executionConfig),
+ );
+ }
+
+ // Events - for EVENTS and TRACES_OBSERVATIONS_EVENTS
+ if (
+ postHogIntegration.exportSource === "EVENTS" ||
+ postHogIntegration.exportSource === "TRACES_OBSERVATIONS_EVENTS"
+ ) {
+ processPromises.push(processPostHogEvents(executionConfig));
+ }
+
+ await Promise.all(processPromises);
// Update the last run information for the postHogIntegration record.
await prisma.posthogIntegration.update({
diff --git a/worker/src/features/posthog/transformers.ts b/worker/src/features/posthog/transformers.ts
index 92af367ff1..d21a79b956 100644
--- a/worker/src/features/posthog/transformers.ts
+++ b/worker/src/features/posthog/transformers.ts
@@ -3,6 +3,7 @@ import type {
AnalyticsTraceEvent,
AnalyticsGenerationEvent,
AnalyticsScoreEvent,
+ AnalyticsObservationEvent,
} from "@langfuse/shared/src/server";
// UUID v5 namespace for PostHog
@@ -120,3 +121,37 @@ export const transformScoreForPostHog = (
uuid,
};
};
+
+export const transformEventForPostHog = (
+ event: AnalyticsObservationEvent,
+ projectId: string,
+): PostHogEvent => {
+ const uuid = v5(`${projectId}-${event.langfuse_id}`, POSTHOG_UUID_NAMESPACE);
+
+ // Extract posthog_session_id and map to $session_id
+
+ const { posthog_session_id, mixpanel_session_id, ...otherProps } = event;
+
+ return {
+ distinctId: event.langfuse_user_id
+ ? (event.langfuse_user_id as string)
+ : uuid,
+ event: "langfuse observation",
+ properties: {
+ ...otherProps,
+ $session_id: posthog_session_id ?? null,
+ // PostHog-specific: add user profile enrichment or mark as anonymous
+ ...(event.langfuse_user_id && event.langfuse_user_url
+ ? {
+ $set: {
+ langfuse_user_url: event.langfuse_user_url,
+ },
+ }
+ : // Capture as anonymous PostHog event (cheaper/faster)
+ // https://posthog.com/docs/data/anonymous-vs-identified-events?tab=Backend
+ { $process_person_profile: false }),
+ },
+ timestamp: event.timestamp as Date,
+ uuid,
+ };
+};