πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(blob-storage): force EVENTS export source on events_only self-hosted deployments (LFE-10148) (#14928)
Niklas Semmler9360e7a7d0f9
diff --git a/packages/shared/src/features/analytics-integrations/export-source-policy.test.ts b/packages/shared/src/features/analytics-integrations/export-source-policy.test.tsindex 84624e0821..60fd9f949d 100644--- a/packages/shared/src/features/analytics-integrations/export-source-policy.test.ts+++ b/packages/shared/src/features/analytics-integrations/export-source-policy.test.ts@@ -20,6 +20,7 @@ const ROW_AT = LEGACY_BLOB_EXPORTER_CUTOFF;const ctx = (over: Partial<ExportSourceContext>): ExportSourceContext => ({isCloud: false,enrichedAvailable: true,+ legacyWritesActive: true,...over,});@@ -105,6 +106,44 @@ describe("validateExportSource matrix", () => {).toBeUndefined();});+ it("legacy under events_only: blocked by capability, deployment-agnostic; EVENTS unaffected", () => {+ const eventsOnly = ctx({ legacyWritesActive: false });+ expect(reasonOf("TRACES_OBSERVATIONS", eventsOnly)).toBe(+ "legacy-writes-disabled",+ );+ expect(reasonOf("TRACES_OBSERVATIONS_EVENTS", eventsOnly)).toBe(+ "legacy-writes-disabled",+ );+ expect(reasonOf("EVENTS", eventsOnly)).toBeUndefined();+ // Deployment-agnostic: applies on Cloud too, but the Cloud cutoff wins+ // the reason so Cloud users never see env-var messaging.+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS",+ ctx({ isCloud: true, legacyWritesActive: false }),+ ),+ ).toBe("legacy-writes-disabled");+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS",+ ctx({+ isCloud: true,+ legacyWritesActive: false,+ projectCreatedAt: PROJECT_POST,+ }),+ ),+ ).toBe("cloud-cutoff");+ // Operator-facing message names the env var.+ const res = validateExportSource("TRACES_OBSERVATIONS", eventsOnly);+ if (!res.ok) expect(res.message).toContain("events_only");+ });++ it("legacy on dual/legacy write modes: unaffected", () => {+ expect(+ reasonOf("TRACES_OBSERVATIONS", ctx({ legacyWritesActive: true })),+ ).toBeUndefined();+ });+it("TRACES_OBSERVATIONS_EVENTS is both enriched and legacy; enriched-unavailable wins", () => {expect(reasonOf(diff --git a/packages/shared/src/features/analytics-integrations/export-source-policy.ts b/packages/shared/src/features/analytics-integrations/export-source-policy.tsindex 481eec9f52..ccd96bc275 100644--- a/packages/shared/src/features/analytics-integrations/export-source-policy.ts+++ b/packages/shared/src/features/analytics-integrations/export-source-policy.ts@@ -22,6 +22,14 @@// preview opt-in. A persisted enriched value left behind by a preview// rollback is rejected too, instead of silently driving exports against// unpopulated tables (LFE-10296).+// - LEGACY WRITE CAPABILITY ("legacy-writes-disabled"): legacy sources read+// the v3 traces/observations tables. Under+// LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only those tables are no longer+// written, so a legacy source would silently export stale/empty data β+// blocked by data capability, deployment-agnostic, on Cloud and self-hosted+// alike (LFE-10148). Unlike the date cutoffs this also applies to persisted+// values: keeping one would not grandfather anything, it would export+// nothing.// - PERSISTED VALUES ARE NEVER SILENTLY REWRITTEN (LFE-10296): the UI keeps a// persisted-but-blocked source visible as an unavailable option and blocks// the save; forms and servers must not substitute a different source behind@@ -30,7 +38,9 @@// Check order inside validateExportSource doubles as the user-facing reason// precedence: enriched-unavailable first (such a source cannot export at all),// then the Cloud cutoffs β so Cloud users are never shown messaging about-// deployment configuration they do not control.+// deployment configuration they do not control β then legacy-writes-disabled,+// which in practice only surfaces on self-hosted (Cloud does not run+// events_only), where naming the env var is operator-appropriate.import { AnalyticsIntegrationExportSource } from "@prisma/client";@@ -124,9 +134,21 @@ export function isEnrichedBlobExportAvailable(return isCloud || isV4PreviewEnabled === true;}+/**+ * Mirrors the LANGFUSE_MIGRATION_V4_WRITE_MODE env enum; kept as a literal+ * union so this client-safe file has no dependency on server env parsing.+ */+export type BlobExportWriteMode = "legacy" | "dual" | "events_only";++/** Whether the deployment still writes the v3 traces/observations tables. */+export function areLegacyWritesActive(writeMode: BlobExportWriteMode): boolean {+ return writeMode !== "events_only";+}+/*** Everything the policy needs to know about a deployment/project/integration.- * Adapters assemble it; optional fields skip their check when absent:+ * Adapters assemble it (env reads stay server/worker-side); optional fields+ * skip their check when absent:* - projectCreatedAt: omit to skip the project-level Cloud cutoff (e.g. when* the caller has no project in scope).* - integrationCreatedAt: omit to skip the integration-level Cloud cutoff@@ -136,11 +158,15 @@ export function isEnrichedBlobExportAvailable(export type ExportSourceContext = {isCloud: boolean;enrichedAvailable: boolean;+ legacyWritesActive: boolean;projectCreatedAt?: Date;integrationCreatedAt?: Date | null;};-export type ExportSourceBlockedReason = "cloud-cutoff" | "enriched-unavailable";+export type ExportSourceBlockedReason =+ | "cloud-cutoff"+ | "legacy-writes-disabled"+ | "enriched-unavailable";export type ExportSourceValidation =| { ok: true }@@ -156,6 +182,13 @@ const PROJECT_CUTOFF_MESSAGE =const exporterCutoffMessage = () =>`Legacy export sources are not available for blob storage integrations created on or after ${LEGACY_BLOB_EXPORTER_CUTOFF.toISOString()} on Cloud. Use 'OBSERVATIONS_V2' instead.`;+// Self-hosted-operator-facing: naming the env var is intentional. Worded+// integration-neutrally since blob storage, PostHog, and Mixpanel all surface+// it. (The Cloud-cutoff messages above keep their pre-existing+// 'OBSERVATIONS_V2' blob-REST wording; tracked under LFE-9688.)+const LEGACY_WRITES_DISABLED_MESSAGE =+ "Legacy export sources are not available while LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only, because the legacy traces/observations tables are no longer written. Switch to the enriched observations export source instead.";+/** Whether a source may be selected/kept in the given context. */export function validateExportSource(source: AnalyticsIntegrationExportSource,@@ -190,6 +223,13 @@ export function validateExportSource(};}}+ if (isLegacyBlobExportSource(source) && !ctx.legacyWritesActive) {+ return {+ ok: false,+ reason: "legacy-writes-disabled",+ message: LEGACY_WRITES_DISABLED_MESSAGE,+ };+ }return { ok: true };}diff --git a/web/src/__tests__/server/mixpanel-integration.servertest.ts b/web/src/__tests__/server/mixpanel-integration.servertest.tsindex 6879f9e508..82132be390 100644--- a/web/src/__tests__/server/mixpanel-integration.servertest.ts+++ b/web/src/__tests__/server/mixpanel-integration.servertest.ts@@ -189,4 +189,199 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;}});++ // LFE-10148: events_only no longer writes the v3 tables, so legacy sources+ // are refused by data capability, independent of Cloud date cutoffs.+ describe("events_only write-mode gate", () => {+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ beforeEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("self-hosted + events_only + legacy source β BAD_REQUEST", async () => {+ const { caller, project } = await prepare();+ await expect(+ caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "TRACES_OBSERVATIONS" as const,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });++ it("self-hosted + events_only + EVENTS β allow", async () => {+ const { caller, project } = await prepare();+ await expect(+ caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ }),+ ).resolves.not.toThrow();+ });++ it("get returns legacyWritesActive=false on events_only", async () => {+ const { caller, project } = await prepare();+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.legacyWritesActive).toBe(false);+ expect(result.config).toBeNull();+ });++ it("get returns legacyWritesActive=true on dual, with config", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ const { caller, project } = await prepare();+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.legacyWritesActive).toBe(true);+ expect(result.config?.exportSource).toBe("EVENTS");+ });+ });++ // LFE-10148 review: the form schema's zod default must not be injected into+ // partial updates β an omitted exportSource preserves the persisted value+ // (capability-checked only), and CREATE picks an explicit, validated default.+ describe("Mixpanel partial updates and create defaults", () => {+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ beforeEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("update omitting exportSource preserves a persisted EVENTS value (dual)", async () => {+ const { caller, project } = await prepare();+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ enabled: false,+ });+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ expect(result.config?.enabled).toBe(false);+ });++ it("update omitting exportSource succeeds on events_only with persisted EVENTS", async () => {+ const { caller, project } = await prepare();+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ await expect(+ caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ enabled: false,+ }),+ ).resolves.not.toThrow();+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ });++ it("create without exportSource defaults to TRACES_OBSERVATIONS on dual", async () => {+ const { caller, project } = await prepare();+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ });+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("TRACES_OBSERVATIONS");+ });++ it("Cloud + post-cutoff project + create without exportSource β BAD_REQUEST (validated default)", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";+ const { caller, project } = await prepare();+ await prisma.project.update({+ where: { id: project.id },+ data: { createdAt: POST_CUTOFF },+ });+ await expect(+ caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });++ it("raced delete between read and write: mis-created legacy row is rolled back (post-cutoff Cloud)", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";+ const { caller, project } = await prepare();+ await prisma.project.update({+ where: { id: project.id },+ data: { createdAt: POST_CUTOFF },+ });+ // Simulate the TOCTOU: the pre-flight read sees a row that a concurrent+ // delete removes before the upsert, flipping it into a CREATE carrying+ // the legacy default. The in-transaction backstop must roll it back.+ const spy = vi+ .spyOn(prisma.mixpanelIntegration, "findUnique")+ .mockResolvedValueOnce({+ exportSource: "TRACES_OBSERVATIONS",+ createdAt: new Date("2026-01-01T00:00:00Z"),+ } as never);+ try {+ await expect(+ caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ } finally {+ spy.mockRestore();+ }+ // Transaction rolled back: nothing was persisted.+ expect(+ await prisma.mixpanelIntegration.findUnique({+ where: { projectId: project.id },+ }),+ ).toBeNull();+ });++ it("create without exportSource defaults to EVENTS on events_only", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ const { caller, project } = await prepare();+ await caller.mixpanelIntegration.update({+ projectId: project.id,+ ...baseConfig,+ });+ const result = await caller.mixpanelIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ });+ });});diff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.tsindex 8742533a4d..1e4b220aa2 100644--- a/web/src/__tests__/server/posthog-integration.servertest.ts+++ b/web/src/__tests__/server/posthog-integration.servertest.ts@@ -233,4 +233,199 @@ describe("PostHog Integration legacy export source cutoff gate", () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;}});++ // LFE-10148: events_only no longer writes the v3 tables, so legacy sources+ // are refused by data capability, independent of Cloud date cutoffs.+ describe("events_only write-mode gate", () => {+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ beforeEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("self-hosted + events_only + legacy source β BAD_REQUEST", async () => {+ const { caller, project } = await prepare();+ await expect(+ caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "TRACES_OBSERVATIONS" as const,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });++ it("self-hosted + events_only + EVENTS β allow", async () => {+ const { caller, project } = await prepare();+ await expect(+ caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ }),+ ).resolves.not.toThrow();+ });++ it("get returns legacyWritesActive=false on events_only", async () => {+ const { caller, project } = await prepare();+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.legacyWritesActive).toBe(false);+ expect(result.config).toBeNull();+ });++ it("get returns legacyWritesActive=true on dual, with config", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ const { caller, project } = await prepare();+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.legacyWritesActive).toBe(true);+ expect(result.config?.exportSource).toBe("EVENTS");+ });+ });++ // LFE-10148 review: the form schema's zod default must not be injected into+ // partial updates β an omitted exportSource preserves the persisted value+ // (capability-checked only), and CREATE picks an explicit, validated default.+ describe("PostHog partial updates and create defaults", () => {+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ beforeEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ });++ afterEach(() => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("update omitting exportSource preserves a persisted EVENTS value (dual)", async () => {+ const { caller, project } = await prepare();+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ enabled: false,+ });+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ expect(result.config?.enabled).toBe(false);+ });++ it("update omitting exportSource succeeds on events_only with persisted EVENTS", async () => {+ const { caller, project } = await prepare();+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ exportSource: "EVENTS" as const,+ });+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ await expect(+ caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ enabled: false,+ }),+ ).resolves.not.toThrow();+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ });++ it("create without exportSource defaults to TRACES_OBSERVATIONS on dual", async () => {+ const { caller, project } = await prepare();+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ });+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("TRACES_OBSERVATIONS");+ });++ it("Cloud + post-cutoff project + create without exportSource β BAD_REQUEST (validated default)", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";+ const { caller, project } = await prepare();+ await prisma.project.update({+ where: { id: project.id },+ data: { createdAt: POST_CUTOFF },+ });+ await expect(+ caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ });++ it("raced delete between read and write: mis-created legacy row is rolled back (post-cutoff Cloud)", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";+ const { caller, project } = await prepare();+ await prisma.project.update({+ where: { id: project.id },+ data: { createdAt: POST_CUTOFF },+ });+ // Simulate the TOCTOU: the pre-flight read sees a row that a concurrent+ // delete removes before the upsert, flipping it into a CREATE carrying+ // the legacy default. The in-transaction backstop must roll it back.+ const spy = vi+ .spyOn(prisma.posthogIntegration, "findUnique")+ .mockResolvedValueOnce({+ exportSource: "TRACES_OBSERVATIONS",+ createdAt: new Date("2026-01-01T00:00:00Z"),+ } as never);+ try {+ await expect(+ caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ } finally {+ spy.mockRestore();+ }+ // Transaction rolled back: nothing was persisted.+ expect(+ await prisma.posthogIntegration.findUnique({+ where: { projectId: project.id },+ }),+ ).toBeNull();+ });++ it("create without exportSource defaults to EVENTS on events_only", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ const { caller, project } = await prepare();+ await caller.posthogIntegration.update({+ projectId: project.id,+ ...baseConfig,+ });+ const result = await caller.posthogIntegration.get({+ projectId: project.id,+ });+ expect(result.config?.exportSource).toBe("EVENTS");+ });+ });});diff --git a/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.tsindex 97d7ae9ada..da3db9a179 100644--- a/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts+++ b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts@@ -15,6 +15,7 @@ const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);const cloudPostCutoff: ExportSourceContext = {isCloud: true,enrichedAvailable: true,+ legacyWritesActive: true,projectCreatedAt: POST_CUTOFF,};@@ -53,14 +54,29 @@ describe("assertExportSourceAllowed", () => {).not.toThrow();});- it("omitted source: rejects a persisted value the deployment cannot export (capability reason)", () => {+ it("omitted source: rejects a persisted value the deployment cannot export (capability reasons)", () => {expect(() =>assertExportSourceAllowed({nextExportSource: undefined,persistedExportSource: "EVENTS",- ctx: { isCloud: false, enrichedAvailable: false },+ ctx: {+ isCloud: false,+ enrichedAvailable: false,+ legacyWritesActive: true,+ },}),).toThrow(/Enriched blob export is not available/);+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: undefined,+ persistedExportSource: "TRACES_OBSERVATIONS",+ ctx: {+ isCloud: false,+ enrichedAvailable: true,+ legacyWritesActive: false,+ },+ }),+ ).toThrow(/events_only/);});it("omitted source without a persisted row is a no-op", () => {diff --git a/web/src/features/analytics-integrations/exportSource.clienttest.ts b/web/src/features/analytics-integrations/exportSource.clienttest.tsindex ec9ee9be38..2c0292235e 100644--- a/web/src/features/analytics-integrations/exportSource.clienttest.ts+++ b/web/src/features/analytics-integrations/exportSource.clienttest.ts@@ -25,22 +25,33 @@ const ROW_PRE = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY);const cloudPreCutoff: ExportSourceContext = {isCloud: true,enrichedAvailable: true,+ legacyWritesActive: true,projectCreatedAt: PROJECT_PRE,integrationCreatedAt: ROW_PRE,};const cloudPostCutoff: ExportSourceContext = {isCloud: true,enrichedAvailable: true,+ legacyWritesActive: true,projectCreatedAt: PROJECT_POST,integrationCreatedAt: ROW_PRE,};const selfHostedWithPreview: ExportSourceContext = {isCloud: false,enrichedAvailable: true,+ legacyWritesActive: true,};const selfHostedRolledBack: ExportSourceContext = {isCloud: false,enrichedAvailable: false,+ legacyWritesActive: true,+};+// Self-hosted events_only: v3 tables no longer written (LFE-10148). Enriched+// stays available (events_only requires the V4 preview opt-in).+const selfHostedEventsOnly: ExportSourceContext = {+ isCloud: false,+ enrichedAvailable: true,+ legacyWritesActive: false,};describe("getExportSourceFormValue", () => {@@ -74,6 +85,18 @@ describe("getExportSourceFormValue", () => {AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,);});++ it("defaults new configurations to EVENTS on events_only, keeps a persisted legacy value (LFE-10148)", () => {+ expect(getExportSourceFormValue(undefined, selfHostedEventsOnly)).toBe(+ AnalyticsIntegrationExportSource.EVENTS,+ );+ expect(+ getExportSourceFormValue(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ selfHostedEventsOnly,+ ),+ ).toBe(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS);+ });});describe("isExportSourceSelectable", () => {@@ -121,6 +144,21 @@ describe("isExportSourceSelectable", () => {);}});++ it("rejects legacy sources on events_only, EVENTS stays (LFE-10148)", () => {+ expect(+ isExportSourceSelectable(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ selfHostedEventsOnly,+ ),+ ).toBe(false);+ expect(+ isExportSourceSelectable(+ AnalyticsIntegrationExportSource.EVENTS,+ selfHostedEventsOnly,+ ),+ ).toBe(true);+ });});describe("getExportSourceOptions", () => {@@ -141,6 +179,23 @@ describe("getExportSourceOptions", () => {]);});+ it("marks a persisted legacy source unavailable on events_only, EVENTS selectable (LFE-10148)", () => {+ const options = getExportSourceOptions(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ selfHostedEventsOnly,+ );+ expect(+ options.find(+ (o) => o.value === AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ )?.unavailable,+ ).toBe(true);+ expect(+ options.find((o) => o.value === AnalyticsIntegrationExportSource.EVENTS)+ ?.unavailable,+ ).toBe(false);+ expect(shouldHideExportSourceSelector(options)).toBe(false);+ });+it("includes a stale persisted enriched source, marked unavailable (LFE-10296)", () => {const options = getExportSourceOptions(AnalyticsIntegrationExportSource.EVENTS,@@ -209,4 +264,10 @@ describe("getExportSourceUnavailableMessage", () => {"no longer available for this project",);});++ it("names the env var for legacy-writes-disabled (self-hosted operator-facing)", () => {+ const message = getExportSourceUnavailableMessage("legacy-writes-disabled");+ expect(message).toContain("LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only");+ expect(message).not.toContain("no longer available for this project");+ });});diff --git a/web/src/features/analytics-integrations/exportSource.ts b/web/src/features/analytics-integrations/exportSource.tsindex 543e49f78b..1a4dee3ee3 100644--- a/web/src/features/analytics-integrations/exportSource.ts+++ b/web/src/features/analytics-integrations/exportSource.ts@@ -73,6 +73,9 @@ const EXPORT_SOURCE_UNAVAILABLE_MESSAGES: Record<"This integration is configured to export enriched observations, but enriched export is not available on this deployment. Saving is blocked until you select an available export source above. To keep the current configuration instead, re-enable enriched export (V4 preview opt-in) on your deployment.","cloud-cutoff":"This integration is configured to export legacy traces and observations, which is no longer available for this project. Saving is blocked until you select an available export source above.",+ // Self-hosted-operator-facing: naming the env var is intentional.+ "legacy-writes-disabled":+ "This integration is configured to export legacy traces and observations, but this deployment runs LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only and no longer writes the legacy traces/observations tables. Saving is blocked until you select an available export source above.",};export function getExportSourceUnavailableMessage(diff --git a/web/src/features/analytics-integrations/server/assertExportSourceAllowed.ts b/web/src/features/analytics-integrations/server/assertExportSourceAllowed.tsindex 6fc3100251..67fb0f3d53 100644--- a/web/src/features/analytics-integrations/server/assertExportSourceAllowed.ts+++ b/web/src/features/analytics-integrations/server/assertExportSourceAllowed.ts@@ -12,8 +12,8 @@ import { type AnalyticsIntegrationExportSource } from "@langfuse/shared/src/db";** An explicitly requested source must pass every check. When the request omits* the source, the persisted one stays in effect: deployment-capability reasons- * still reject it (it could not export), while the Cloud date cutoffs- * grandfather it β they gate newly chosen values only.+ * (enriched-unavailable, legacy-writes-disabled) still reject it β it could+ * not export β while the Cloud date cutoffs grandfather it.*/export function assertExportSourceAllowed({nextExportSource,@@ -30,8 +30,12 @@ export function assertExportSourceAllowed({return;}if (!persistedExportSource) return;- const validation = validateExportSource(persistedExportSource, ctx);- if (!validation.ok && validation.reason !== "cloud-cutoff") {- throw new InvalidRequestError(validation.message);- }+ // Capability-only check: dropping the creation dates disables the Cloud+ // date cutoffs, which gate newly chosen values only.+ const validation = validateExportSource(persistedExportSource, {+ isCloud: ctx.isCloud,+ enrichedAvailable: ctx.enrichedAvailable,+ legacyWritesActive: ctx.legacyWritesActive,+ });+ if (!validation.ok) throw new InvalidRequestError(validation.message);}diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex 61fb2ae260..513639cdd8 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -27,6 +27,7 @@ import { randomUUID } from "crypto";import { decrypt } from "@langfuse/shared/encryption";import {AnalyticsIntegrationExportSource,+ areLegacyWritesActive,BlobStorageIntegrationType,BlobStorageIntegrationFileType,InvalidRequestError,@@ -78,6 +79,10 @@ export const blobStorageIntegrationRouter = createTRPCRouter({isCloud,env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true",);+ // Data capability for legacy sources (see export-source-policy.ts).+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );const config = await ctx.prisma.blobStorageIntegration.findFirst({where: {@@ -88,7 +93,11 @@ export const blobStorageIntegrationRouter = createTRPCRouter({},});- return { config: config ?? null, isEnrichedExportAvailable };+ return {+ config: config ?? null,+ isEnrichedExportAvailable,+ legacyWritesActive,+ };} catch (e) {logger.error(`Failed to get blob storage integration`, e);throw new TRPCError({@@ -151,6 +160,9 @@ export const blobStorageIntegrationRouter = createTRPCRouter({isCloud,isV4PreviewEnabled,),+ legacyWritesActive: areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ ),projectCreatedAt,integrationCreatedAt: existingIntegration?.createdAt ?? null,},diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsxindex 271efae062..1ee6b843a9 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx@@ -27,11 +27,13 @@ export const BlobStorageIntegrationContainer = ({projectId,isLoading,isEnrichedExportAvailable,+ legacyWritesActive,}: {config: Partial<BlobStorageIntegration> | null;projectId: string;isLoading: boolean;isEnrichedExportAvailable: boolean;+ legacyWritesActive: boolean;}) => {const capture = usePostHogClientCapture();const { isLangfuseCloud } = useLangfuseCloudRegion();@@ -45,6 +47,7 @@ export const BlobStorageIntegrationContainer = ({() => ({isCloud: isLangfuseCloud,enrichedAvailable: isEnrichedExportAvailable,+ legacyWritesActive,projectCreatedAt: projectCreatedAt? new Date(projectCreatedAt): undefined,@@ -55,6 +58,7 @@ export const BlobStorageIntegrationContainer = ({[isLangfuseCloud,isEnrichedExportAvailable,+ legacyWritesActive,projectCreatedAt,integrationCreatedAt,],diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsxindex 77f71e3757..527d28d80a 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx@@ -19,6 +19,7 @@ import {const exportSourceCtx: ExportSourceContext = {isCloud: true,enrichedAvailable: true,+ legacyWritesActive: true,projectCreatedAt: new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + 1),integrationCreatedAt: null,};diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex 9d0a91801f..f8917fb57f 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -4,6 +4,7 @@ import {BlobStorageIntegrationType,InvalidRequestError,AnalyticsIntegrationExportSource,+ areLegacyWritesActive,validateExportSource,BlobStorageIntegrationFileType,type ObservationFieldGroupFull,@@ -145,9 +146,15 @@ export async function upsertBlobStorageIntegration(params: {// at INSERT time regardless of what findUnique saw. UPDATE uses// writeData.exportSource (undefined β Prisma omits the column β preserves// the existing value), so the caller intent is always honored on both paths.+ // Under events_only a new row must never fall back to the legacy Prisma+ // column default; force EVENTS in-transaction, deployment-agnostic+ // (see export-source-policy.ts).+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );const createExportSource =data.exportSource ??- (params.forceEventsOnCreate+ (params.forceEventsOnCreate || !legacyWritesActive? AnalyticsIntegrationExportSource.EVENTS: undefined);@@ -194,6 +201,7 @@ export async function upsertBlobStorageIntegration(params: {const backstop = validateExportSource(result.exportSource, {isCloud: !isSelfHosted,enrichedAvailable: true,+ legacyWritesActive,integrationCreatedAt: params.refuseLegacyOnCreate? result.createdAt: undefined,diff --git a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts b/web/src/features/mixpanel-integration/mixpanel-integration-router.tsindex 41ee40fdbc..a5718f8c09 100644--- a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts@@ -11,6 +11,12 @@ import { decrypt, encrypt } from "@langfuse/shared/encryption";import { mixpanelIntegrationFormSchema } from "@/src/features/mixpanel-integration/types";import { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";+import {+ AnalyticsIntegrationExportSource,+ areLegacyWritesActive,+ InvalidRequestError,+ validateExportSource,+} from "@langfuse/shared";export const mixpanelIntegrationRouter = createTRPCRouter({get: protectedProjectProcedure@@ -21,6 +27,10 @@ export const mixpanelIntegrationRouter = createTRPCRouter({projectId: input.projectId,scope: "integrations:CRUD",});+ // Data capability for legacy sources (see export-source-policy.ts).+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );try {const dbConfig = await ctx.prisma.mixpanelIntegration.findFirst({where: {@@ -29,16 +39,19 @@ export const mixpanelIntegrationRouter = createTRPCRouter({});if (!dbConfig) {- return null;+ return { config: null, legacyWritesActive };}const { encryptedMixpanelProjectToken, exportSource, ...config } =dbConfig;return {- ...config,- exportSource,- mixpanelProjectToken: decrypt(encryptedMixpanelProjectToken),+ config: {+ ...config,+ exportSource,+ mixpanelProjectToken: decrypt(encryptedMixpanelProjectToken),+ },+ legacyWritesActive,};} catch (e) {console.error("mixpanel integration get", e);@@ -49,7 +62,14 @@ export const mixpanelIntegrationRouter = createTRPCRouter({}),update: protectedProjectProcedure- .input(mixpanelIntegrationFormSchema.extend({ projectId: z.string() }))+ .input(+ mixpanelIntegrationFormSchema.extend({+ projectId: z.string(),+ // Drop the base schema default so an omitted value preserves the+ // persisted source instead of rewriting it to the legacy default.+ exportSource: z.enum(AnalyticsIntegrationExportSource).optional(),+ }),+ ).mutation(async ({ input, ctx }) => {throwIfNoProjectAccess({session: ctx.session,@@ -71,23 +91,44 @@ export const mixpanelIntegrationRouter = createTRPCRouter({}}- // Post-cutoff Cloud projects may not select a legacy export source- // (LFE-9688). EVENTS is always accepted by this router, hence- // enrichedAvailable: true. See export-source-policy.ts.- if (input.exportSource) {- const project = await ctx.prisma.project.findUniqueOrThrow({- where: { id: input.projectId },- select: { createdAt: true },- });- assertExportSourceAllowed({- nextExportSource: input.exportSource,- ctx: {- isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),- enrichedAvailable: true,- projectCreatedAt: project.createdAt,- },+ // EVENTS is always accepted by this router, hence enrichedAvailable:+ // true. An omitted source preserves the persisted row; on CREATE it+ // falls back to a default that is validated like an explicit choice+ // (LFE-9688 / LFE-10148). See export-source-policy.ts.+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );+ const existingIntegration =+ await ctx.prisma.mixpanelIntegration.findUnique({+ where: { projectId: input.projectId },+ select: { exportSource: true, createdAt: true },});- }+ const createDefaultExportSource = legacyWritesActive+ ? AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS+ : AnalyticsIntegrationExportSource.EVENTS;+ const nextExportSource =+ input.exportSource ??+ (existingIntegration ? undefined : createDefaultExportSource);+ // The Cloud cutoffs need the project only for explicitly chosen (or+ // create-defaulted) sources.+ const projectCreatedAt = nextExportSource+ ? (+ await ctx.prisma.project.findUniqueOrThrow({+ where: { id: input.projectId },+ select: { createdAt: true },+ })+ ).createdAt+ : undefined;+ assertExportSourceAllowed({+ nextExportSource,+ persistedExportSource: existingIntegration?.exportSource,+ ctx: {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt,+ },+ });await auditLog({session: ctx.session,@@ -99,23 +140,50 @@ export const mixpanelIntegrationRouter = createTRPCRouter({const encryptedMixpanelProjectToken = encrypt(mixpanelProjectToken);- await ctx.prisma.mixpanelIntegration.upsert({- where: {- projectId: input.projectId,- },- create: {- projectId: input.projectId,- mixpanelRegion: config.mixpanelRegion,- encryptedMixpanelProjectToken,- enabled: config.enabled,- exportSource: config.exportSource,- },- update: {- encryptedMixpanelProjectToken,- mixpanelRegion: config.mixpanelRegion,- enabled: config.enabled,- exportSource: config.exportSource,- },+ await ctx.prisma.$transaction(async (tx) => {+ const result = await tx.mixpanelIntegration.upsert({+ where: {+ projectId: input.projectId,+ },+ create: {+ projectId: input.projectId,+ mixpanelRegion: config.mixpanelRegion,+ encryptedMixpanelProjectToken,+ enabled: config.enabled,+ exportSource: config.exportSource ?? createDefaultExportSource,+ },+ update: {+ encryptedMixpanelProjectToken,+ mixpanelRegion: config.mixpanelRegion,+ enabled: config.enabled,+ // undefined β Prisma omits the column β preserves the persisted+ // value on partial updates (LFE-10296).+ exportSource: config.exportSource,+ },+ });++ // Race backstop (mirrors blob storage's service.ts): a concurrent+ // delete between the pre-flight read and this upsert can flip the+ // expected UPDATE into a CREATE carrying the unvalidated legacy+ // default. Detectable as a createdAt change; re-validate the persisted+ // row as an explicit choice and roll back on failure.+ if (+ input.exportSource === undefined &&+ existingIntegration &&+ result.createdAt.getTime() !== existingIntegration.createdAt.getTime()+ ) {+ const project = await tx.project.findUniqueOrThrow({+ where: { id: input.projectId },+ select: { createdAt: true },+ });+ const validation = validateExportSource(result.exportSource, {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt: project.createdAt,+ });+ if (!validation.ok) throw new InvalidRequestError(validation.message);+ }});}),delete: protectedProjectProcedurediff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.tsindex 6a5ef9645c..d71625197f 100644--- a/web/src/features/posthog-integration/posthog-integration-router.ts+++ b/web/src/features/posthog-integration/posthog-integration-router.ts@@ -12,6 +12,12 @@ import { posthogIntegrationFormSchema } from "@/src/features/posthog-integrationimport { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";import { validateWebhookURL } from "@langfuse/shared/src/server";+import {+ AnalyticsIntegrationExportSource,+ areLegacyWritesActive,+ InvalidRequestError,+ validateExportSource,+} from "@langfuse/shared";export const posthogIntegrationRouter = createTRPCRouter({get: protectedProjectProcedure@@ -22,6 +28,10 @@ export const posthogIntegrationRouter = createTRPCRouter({projectId: input.projectId,scope: "integrations:CRUD",});+ // Data capability for legacy sources (see export-source-policy.ts).+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );try {const dbConfig = await ctx.prisma.posthogIntegration.findFirst({where: {@@ -30,15 +40,18 @@ export const posthogIntegrationRouter = createTRPCRouter({});if (!dbConfig) {- return null;+ return { config: null, legacyWritesActive };}const { encryptedPosthogApiKey, exportSource, ...config } = dbConfig;return {- ...config,- exportSource,- posthogApiKey: decrypt(encryptedPosthogApiKey),+ config: {+ ...config,+ exportSource,+ posthogApiKey: decrypt(encryptedPosthogApiKey),+ },+ legacyWritesActive,};} catch (e) {console.error("posthog integration get", e);@@ -49,7 +62,14 @@ export const posthogIntegrationRouter = createTRPCRouter({}),update: protectedProjectProcedure- .input(posthogIntegrationFormSchema.extend({ projectId: z.string() }))+ .input(+ posthogIntegrationFormSchema.extend({+ projectId: z.string(),+ // Drop the base schema default so an omitted value preserves the+ // persisted source instead of rewriting it to the legacy default.+ exportSource: z.enum(AnalyticsIntegrationExportSource).optional(),+ }),+ ).mutation(async ({ input, ctx }) => {throwIfNoProjectAccess({session: ctx.session,@@ -84,23 +104,44 @@ export const posthogIntegrationRouter = createTRPCRouter({});}- // Post-cutoff Cloud projects may not select a legacy export source- // (LFE-9688). EVENTS is always accepted by this router, hence- // enrichedAvailable: true. See export-source-policy.ts.- if (input.exportSource) {- const project = await ctx.prisma.project.findUniqueOrThrow({- where: { id: input.projectId },- select: { createdAt: true },- });- assertExportSourceAllowed({- nextExportSource: input.exportSource,- ctx: {- isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),- enrichedAvailable: true,- projectCreatedAt: project.createdAt,- },+ // EVENTS is always accepted by this router, hence enrichedAvailable:+ // true. An omitted source preserves the persisted row; on CREATE it+ // falls back to a default that is validated like an explicit choice+ // (LFE-9688 / LFE-10148). See export-source-policy.ts.+ const legacyWritesActive = areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ );+ const existingIntegration =+ await ctx.prisma.posthogIntegration.findUnique({+ where: { projectId: input.projectId },+ select: { exportSource: true, createdAt: true },});- }+ const createDefaultExportSource = legacyWritesActive+ ? AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS+ : AnalyticsIntegrationExportSource.EVENTS;+ const nextExportSource =+ input.exportSource ??+ (existingIntegration ? undefined : createDefaultExportSource);+ // The Cloud cutoffs need the project only for explicitly chosen (or+ // create-defaulted) sources.+ const projectCreatedAt = nextExportSource+ ? (+ await ctx.prisma.project.findUniqueOrThrow({+ where: { id: input.projectId },+ select: { createdAt: true },+ })+ ).createdAt+ : undefined;+ assertExportSourceAllowed({+ nextExportSource,+ persistedExportSource: existingIntegration?.exportSource,+ ctx: {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt,+ },+ });await auditLog({session: ctx.session,@@ -112,23 +153,50 @@ export const posthogIntegrationRouter = createTRPCRouter({const encryptedPosthogApiKey = encrypt(posthogProjectApiKey);- await ctx.prisma.posthogIntegration.upsert({- where: {- projectId: input.projectId,- },- create: {- projectId: input.projectId,- posthogHostName: config.posthogHostname,- encryptedPosthogApiKey,- enabled: config.enabled,- exportSource: config.exportSource,- },- update: {- encryptedPosthogApiKey,- posthogHostName: config.posthogHostname,- enabled: config.enabled,- exportSource: config.exportSource,- },+ await ctx.prisma.$transaction(async (tx) => {+ const result = await tx.posthogIntegration.upsert({+ where: {+ projectId: input.projectId,+ },+ create: {+ projectId: input.projectId,+ posthogHostName: config.posthogHostname,+ encryptedPosthogApiKey,+ enabled: config.enabled,+ exportSource: config.exportSource ?? createDefaultExportSource,+ },+ update: {+ encryptedPosthogApiKey,+ posthogHostName: config.posthogHostname,+ enabled: config.enabled,+ // undefined β Prisma omits the column β preserves the persisted+ // value on partial updates (LFE-10296).+ exportSource: config.exportSource,+ },+ });++ // Race backstop (mirrors blob storage's service.ts): a concurrent+ // delete between the pre-flight read and this upsert can flip the+ // expected UPDATE into a CREATE carrying the unvalidated legacy+ // default. Detectable as a createdAt change; re-validate the persisted+ // row as an explicit choice and roll back on failure.+ if (+ input.exportSource === undefined &&+ existingIntegration &&+ result.createdAt.getTime() !== existingIntegration.createdAt.getTime()+ ) {+ const project = await tx.project.findUniqueOrThrow({+ where: { id: input.projectId },+ select: { createdAt: true },+ });+ const validation = validateExportSource(result.exportSource, {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt: project.createdAt,+ });+ if (!validation.ok) throw new InvalidRequestError(validation.message);+ }});}),delete: protectedProjectProcedurediff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex a3b3d8420d..d369af2b85 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -18,7 +18,10 @@ import {} from "@langfuse/shared";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";-import { isEnrichedBlobExportAvailable } from "@langfuse/shared";+import {+ areLegacyWritesActive,+ isEnrichedBlobExportAvailable,+} from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { env } from "@/src/env.mjs";@@ -186,6 +189,9 @@ async function handleUpsertBlobStorageIntegration(isCloud,isV4PreviewEnabled,),+ legacyWritesActive: areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ ),projectCreatedAt: project.createdAt,integrationCreatedAt: existingIntegration?.createdAt ?? null,},diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsxindex 4633772678..32a6560c1c 100644--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx@@ -113,6 +113,7 @@ export default function BlobStorageIntegrationSettings() {isEnrichedExportAvailable={state.data?.isEnrichedExportAvailable ?? false}+ legacyWritesActive={state.data?.legacyWritesActive ?? true}/></Card></>diff --git a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsxindex c929529692..1d6f575c23 100644--- a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx@@ -34,9 +34,17 @@ import {} from "@/src/features/mixpanel-integration/types";import {AnalyticsIntegrationExportSource,- EXPORT_SOURCE_OPTIONS,validateExportSource,+ type ExportSourceContext,} from "@langfuse/shared";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+// Shared export-source UI adapters; policy in export-source-policy.ts.+import {+ getExportSourceOptions,+ getExportSourceUnavailableMessage,+ isExportSourceSelectable,+ shouldHideExportSourceSelector,+} from "@/src/features/analytics-integrations/exportSource";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";import { useQueryProject } from "@/src/features/projects/hooks";@@ -47,7 +55,7 @@ import { zodResolver } from "@hookform/resolvers/zod";import { Card } from "@/src/components/ui/card";import Link from "next/link";import { useRouter } from "next/router";-import { useEffect } from "react";+import { useEffect, useMemo } from "react";import { useForm } from "react-hook-form";import { type z } from "zod";import { Info, ExternalLink } from "lucide-react";@@ -70,7 +78,7 @@ export default function MixpanelIntegrationSettings() {const status =state.isLoading || !hasAccess? undefined- : state.data?.enabled+ : state.data?.config?.enabled? "active": "inactive";@@ -114,20 +122,21 @@ export default function MixpanelIntegrationSettings() {<Card className="p-3"><MixpanelLogo className="text-foreground mb-4 w-20" /><MixpanelIntegrationSettingsForm- state={state.data}+ state={state.data?.config ?? undefined}projectId={projectId}isLoading={state.isLoading}+ legacyWritesActive={state.data?.legacyWritesActive ?? true}/></Card></>)}- {state.data?.enabled && (+ {state.data?.config?.enabled && (<><Header title="Status" className="mt-8" /><p className="text-primary text-sm">Data synced until:{" "}- {state.data?.lastSyncAt- ? new Date(state.data.lastSyncAt).toLocaleString()+ {state.data?.config?.lastSyncAt+ ? new Date(state.data.config.lastSyncAt).toLocaleString(): "Never (pending)"}</p></>@@ -140,45 +149,86 @@ const MixpanelIntegrationSettingsForm = ({state,projectId,isLoading,+ legacyWritesActive,}: {- state?: RouterOutput["mixpanelIntegration"]["get"];+ state?: NonNullable<RouterOutput["mixpanelIntegration"]["get"]["config"]>;projectId: string;isLoading: boolean;+ legacyWritesActive: boolean;}) => {const capture = usePostHogClientCapture();const { isBetaEnabled } = useV4Beta();const { isLangfuseCloud } = useLangfuseCloudRegion();const { project } = useQueryProject();- // Post-cutoff Cloud projects may only use OBSERVATIONS_V2 (EVENTS). The- // Export Source field is hidden in that case; the form value is pinned to- // EVENTS via the default below (see export-source-policy.ts).+ // Policy context; EVENTS is always accepted by this router, hence+ // enrichedAvailable: true (see export-source-policy.ts).+ const projectCreatedAt = project?.createdAt;+ const exportSourceCtx: ExportSourceContext = useMemo(+ () => ({+ isCloud: isLangfuseCloud,+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt: projectCreatedAt+ ? new Date(projectCreatedAt)+ : undefined,+ }),+ [isLangfuseCloud, legacyWritesActive, projectCreatedAt],+ );+ const legacyValidation = validateExportSource(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ exportSourceCtx,+ );+ // Post-cutoff Cloud projects: field hidden, form value pinned to EVENTS via+ // the default below (LFE-9688 / 9830 behavior, unchanged).const isPostCutoffCloud =- project?.createdAt != null &&- !validateExportSource(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- {- isCloud: isLangfuseCloud,- enrichedAvailable: true,- projectCreatedAt: new Date(project.createdAt),- },- ).ok;- const showExportSourceField = isBetaEnabled && !isPostCutoffCloud;+ !legacyValidation.ok && legacyValidation.reason === "cloud-cutoff";+ const exportSourceOptions = getExportSourceOptions(+ state?.exportSource ?? null,+ exportSourceCtx,+ );+ // Selector is beta-gated, except a persisted source blocked by capability+ // forces it visible so the blocked-save alert has something to point at.+ const persistedBlockedByCapability =+ state?.exportSource != null &&+ !isPostCutoffCloud &&+ !isExportSourceSelectable(state.exportSource, exportSourceCtx);+ const showExportSourceField =+ ((isBetaEnabled && !isPostCutoffCloud) || persistedBlockedByCapability) &&+ !shouldHideExportSourceSelector(exportSourceOptions);++ // Blocked-save validation instead of silent rewrite (LFE-10296).+ const formSchema = useMemo(+ () =>+ mixpanelIntegrationFormSchema.superRefine((data, ctx) => {+ if (!isExportSourceSelectable(data.exportSource, exportSourceCtx)) {+ ctx.addIssue({+ code: "custom",+ path: ["exportSource"],+ message:+ "This export source is not available on this deployment. Select an available export source to save.",+ });+ }+ }),+ [exportSourceCtx],+ );++ const defaultExportSource = isPostCutoffCloud+ ? AnalyticsIntegrationExportSource.EVENTS+ : (state?.exportSource ??+ (isBetaEnabled || !legacyWritesActive+ ? AnalyticsIntegrationExportSource.EVENTS+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS));const mixpanelForm = useForm({- resolver: zodResolver(mixpanelIntegrationFormSchema),+ resolver: zodResolver(formSchema),defaultValues: {mixpanelRegion:(state?.mixpanelRegion as MixpanelRegion) ??MIXPANEL_REGIONS[0].subdomain,mixpanelProjectToken: state?.mixpanelProjectToken ?? "",enabled: state?.enabled ?? false,- exportSource: isPostCutoffCloud- ? AnalyticsIntegrationExportSource.EVENTS- : (state?.exportSource ??- (isBetaEnabled- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS)),+ exportSource: defaultExportSource,},disabled: isLoading,});@@ -190,16 +240,17 @@ const MixpanelIntegrationSettingsForm = ({MIXPANEL_REGIONS[0].subdomain,mixpanelProjectToken: state?.mixpanelProjectToken ?? "",enabled: state?.enabled ?? false,- exportSource: isPostCutoffCloud- ? AnalyticsIntegrationExportSource.EVENTS- : (state?.exportSource ??- (isBetaEnabled- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS)),+ exportSource: defaultExportSource,});// eslint-disable-next-line react-hooks/exhaustive-deps}, [state]);+ const watchedExportSource = mixpanelForm.watch("exportSource");+ const watchedValidation =+ watchedExportSource != null+ ? validateExportSource(watchedExportSource, exportSourceCtx)+ : ({ ok: true } as const);+const utils = api.useUtils();const mut = api.mixpanelIntegration.update.useMutation({onSuccess: () => {@@ -288,7 +339,7 @@ const MixpanelIntegrationSettingsForm = ({side="bottom"className="max-w-[350px] space-y-2 p-3">- {EXPORT_SOURCE_OPTIONS.map((option) => (+ {exportSourceOptions.map((option) => (<div key={option.value} className="space-y-0.5"><div className="font-medium">{option.label}</div><div className="text-muted-foreground text-xs">@@ -317,9 +368,15 @@ const MixpanelIntegrationSettingsForm = ({</SelectTrigger></FormControl><SelectContent>- {EXPORT_SOURCE_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}+ {exportSourceOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ disabled={option.unavailable}+ >+ {option.unavailable+ ? `${option.label} (not available on this deployment)`+ : option.label}</SelectItem>))}</SelectContent>@@ -333,6 +390,14 @@ const MixpanelIntegrationSettingsForm = ({)}/>)}+ {!watchedValidation.ok && (+ <Alert variant="destructive">+ <AlertTitle>Saved export source is no longer available</AlertTitle>+ <AlertDescription>+ {getExportSourceUnavailableMessage(watchedValidation.reason)}+ </AlertDescription>+ </Alert>+ )}<FormFieldcontrol={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.tsxindex 1b407311d4..948ed167ac 100644--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx@@ -31,9 +31,17 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport { posthogIntegrationFormSchema } from "@/src/features/posthog-integration/types";import {AnalyticsIntegrationExportSource,- EXPORT_SOURCE_OPTIONS,validateExportSource,+ type ExportSourceContext,} from "@langfuse/shared";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+// Shared export-source UI adapters; policy in export-source-policy.ts.+import {+ getExportSourceOptions,+ getExportSourceUnavailableMessage,+ isExportSourceSelectable,+ shouldHideExportSourceSelector,+} from "@/src/features/analytics-integrations/exportSource";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";import { useQueryProject } from "@/src/features/projects/hooks";@@ -44,7 +52,7 @@ import { zodResolver } from "@hookform/resolvers/zod";import { Card } from "@/src/components/ui/card";import Link from "next/link";import { useRouter } from "next/router";-import { useEffect } from "react";+import { useEffect, useMemo } from "react";import { useForm } from "react-hook-form";import { type z } from "zod";import { Info, ExternalLink } from "lucide-react";@@ -67,7 +75,7 @@ export default function PosthogIntegrationSettings() {const status =state.isLoading || !hasAccess? undefined- : state.data?.enabled+ : state.data?.config?.enabled? "active": "inactive";@@ -111,20 +119,21 @@ export default function PosthogIntegrationSettings() {<Card className="p-3"><PostHogLogo className="text-foreground mb-4 w-36" /><PostHogIntegrationSettings- state={state.data}+ state={state.data?.config ?? undefined}projectId={projectId}isLoading={state.isLoading}+ legacyWritesActive={state.data?.legacyWritesActive ?? true}/></Card></>)}- {state.data?.enabled && (+ {state.data?.config?.enabled && (<><Header title="Status" className="mt-8" /><p className="text-primary text-sm">Data synced until:{" "}- {state.data?.lastSyncAt- ? new Date(state.data.lastSyncAt).toLocaleString()+ {state.data?.config?.lastSyncAt+ ? new Date(state.data.config.lastSyncAt).toLocaleString(): "Never (pending)"}</p></>@@ -137,43 +146,84 @@ const PostHogIntegrationSettings = ({state,projectId,isLoading,+ legacyWritesActive,}: {- state?: RouterOutput["posthogIntegration"]["get"];+ state?: NonNullable<RouterOutput["posthogIntegration"]["get"]["config"]>;projectId: string;isLoading: boolean;+ legacyWritesActive: boolean;}) => {const capture = usePostHogClientCapture();const { isBetaEnabled } = useV4Beta();const { isLangfuseCloud } = useLangfuseCloudRegion();const { project } = useQueryProject();- // Post-cutoff Cloud projects may only use OBSERVATIONS_V2 (EVENTS). The- // Export Source field is hidden in that case; the form value is pinned to- // EVENTS via the default below (see export-source-policy.ts).+ // Policy context; EVENTS is always accepted by this router, hence+ // enrichedAvailable: true (see export-source-policy.ts).+ const projectCreatedAt = project?.createdAt;+ const exportSourceCtx: ExportSourceContext = useMemo(+ () => ({+ isCloud: isLangfuseCloud,+ enrichedAvailable: true,+ legacyWritesActive,+ projectCreatedAt: projectCreatedAt+ ? new Date(projectCreatedAt)+ : undefined,+ }),+ [isLangfuseCloud, legacyWritesActive, projectCreatedAt],+ );+ const legacyValidation = validateExportSource(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ exportSourceCtx,+ );+ // Post-cutoff Cloud projects: field hidden, form value pinned to EVENTS via+ // the default below (LFE-9688 / 9830 behavior, unchanged).const isPostCutoffCloud =- project?.createdAt != null &&- !validateExportSource(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- {- isCloud: isLangfuseCloud,- enrichedAvailable: true,- projectCreatedAt: new Date(project.createdAt),- },- ).ok;- const showExportSourceField = isBetaEnabled && !isPostCutoffCloud;+ !legacyValidation.ok && legacyValidation.reason === "cloud-cutoff";+ const exportSourceOptions = getExportSourceOptions(+ state?.exportSource ?? null,+ exportSourceCtx,+ );+ // Selector is beta-gated, except a persisted source blocked by capability+ // forces it visible so the blocked-save alert has something to point at.+ const persistedBlockedByCapability =+ state?.exportSource != null &&+ !isPostCutoffCloud &&+ !isExportSourceSelectable(state.exportSource, exportSourceCtx);+ const showExportSourceField =+ ((isBetaEnabled && !isPostCutoffCloud) || persistedBlockedByCapability) &&+ !shouldHideExportSourceSelector(exportSourceOptions);++ // Blocked-save validation instead of silent rewrite (LFE-10296).+ const formSchema = useMemo(+ () =>+ posthogIntegrationFormSchema.superRefine((data, ctx) => {+ if (!isExportSourceSelectable(data.exportSource, exportSourceCtx)) {+ ctx.addIssue({+ code: "custom",+ path: ["exportSource"],+ message:+ "This export source is not available on this deployment. Select an available export source to save.",+ });+ }+ }),+ [exportSourceCtx],+ );++ const defaultExportSource = isPostCutoffCloud+ ? AnalyticsIntegrationExportSource.EVENTS+ : (state?.exportSource ??+ (isBetaEnabled || !legacyWritesActive+ ? AnalyticsIntegrationExportSource.EVENTS+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS));const posthogForm = useForm({- resolver: zodResolver(posthogIntegrationFormSchema),+ resolver: zodResolver(formSchema),defaultValues: {posthogHostname: state?.posthogHostName ?? "",posthogProjectApiKey: state?.posthogApiKey ?? "",enabled: state?.enabled ?? false,- exportSource: isPostCutoffCloud- ? AnalyticsIntegrationExportSource.EVENTS- : (state?.exportSource ??- (isBetaEnabled- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS)),+ exportSource: defaultExportSource,},disabled: isLoading,});@@ -183,16 +233,17 @@ const PostHogIntegrationSettings = ({posthogHostname: state?.posthogHostName ?? "",posthogProjectApiKey: state?.posthogApiKey ?? "",enabled: state?.enabled ?? false,- exportSource: isPostCutoffCloud- ? AnalyticsIntegrationExportSource.EVENTS- : (state?.exportSource ??- (isBetaEnabled- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS)),+ exportSource: defaultExportSource,});// eslint-disable-next-line react-hooks/exhaustive-deps}, [state]);+ const watchedExportSource = posthogForm.watch("exportSource");+ const watchedValidation =+ watchedExportSource != null+ ? validateExportSource(watchedExportSource, exportSourceCtx)+ : ({ ok: true } as const);+const utils = api.useUtils();const mut = api.posthogIntegration.update.useMutation({onSuccess: () => {@@ -264,7 +315,7 @@ const PostHogIntegrationSettings = ({side="bottom"className="max-w-[350px] space-y-2 p-3">- {EXPORT_SOURCE_OPTIONS.map((option) => (+ {exportSourceOptions.map((option) => (<div key={option.value} className="space-y-0.5"><div className="font-medium">{option.label}</div><div className="text-muted-foreground text-xs">@@ -293,9 +344,15 @@ const PostHogIntegrationSettings = ({</SelectTrigger></FormControl><SelectContent>- {EXPORT_SOURCE_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}+ {exportSourceOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ disabled={option.unavailable}+ >+ {option.unavailable+ ? `${option.label} (not available on this deployment)`+ : option.label}</SelectItem>))}</SelectContent>@@ -309,6 +366,14 @@ const PostHogIntegrationSettings = ({)}/>)}+ {!watchedValidation.ok && (+ <Alert variant="destructive">+ <AlertTitle>Saved export source is no longer available</AlertTitle>+ <AlertDescription>+ {getExportSourceUnavailableMessage(watchedValidation.reason)}+ </AlertDescription>+ </Alert>+ )}<FormFieldcontrol={posthogForm.control}name="enabled"diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 61d86cbeb1..a42aaa1881 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -186,6 +186,58 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ // LFE-10148: a persisted legacy export source on an events_only deployment+ // reads the v3 traces/observations tables, which are no longer written β the+ // job must fail loudly instead of exporting stale/empty data.+ describe("legacy export source guard on events_only", () => {+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;++ afterEach(() => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = originalWriteMode;+ });++ it("fails the job and persists lastError when a legacy source runs on events_only", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ const { projectId } = await createOrgProjectAndApiKey();+ s3Prefix = projectId;++ await prisma.blobStorageIntegration.create({+ data: {+ projectId,+ type: BlobStorageIntegrationType.S3,+ bucketName,+ prefix: s3Prefix,+ accessKeyId,+ secretAccessKey: encrypt(secretAccessKey),+ region: region ? region : "auto",+ endpoint: endpoint ? endpoint : null,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ enabled: true,+ exportFrequency: "daily",+ exportSource: "TRACES_OBSERVATIONS",+ lastSyncAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),+ },+ });++ await expect(+ handleBlobStorageIntegrationProjectJob({+ data: { payload: { projectId } },+ } as Job),+ ).rejects.toThrow(/events_only/i);++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId },+ });+ expect(row.lastError).toMatch(/events_only/i);+ expect(row.lastErrorAt).not.toBeNull();++ // Nothing was exported.+ const files = await storageService.listFiles(s3Prefix);+ expect(files.filter((f) => f.file.includes(projectId))).toHaveLength(0);+ });+ });+// After BullMQ exhausts its retries, a customer-fault error disables the// integration; everything else keeps retrying as before.describe("customer-fault disable", () => {diff --git a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.tsindex e98c512e0c..6b7b2e31b2 100644--- a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts+++ b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts@@ -43,12 +43,28 @@ const h = vi.hoisted(() => {const mixpanelIntegrationUpdate = vi.fn();+ const defaultIntegration = () => ({+ projectId: "project-1",+ enabled: true,+ exportSource: "TRACES_OBSERVATIONS_EVENTS",+ mixpanelRegion: "api",+ encryptedMixpanelProjectToken: "enc",+ lastSyncAt: new Date("2024-01-01"),+ project: { name: "Test Project" },+ });++ // Mutable row returned by the prisma findFirst mock so individual tests can+ // vary exportSource.+ const db = { integration: defaultIntegration() as Record<string, unknown> };+return {timeline,constructed,state,fakeStream,mixpanelIntegrationUpdate,+ defaultIntegration,+ db,};});@@ -78,23 +94,19 @@ vi.mock("@langfuse/shared/encryption", () => ({}));// Keep the throttle delay out of the unit test (real value defaults to 500ms).-// Path is relative to this test file -> resolves to worker/src/env.+// Path is relative to this test file -> resolves to worker/src/env (also the+// module the exportWriteModeGuard reads its write mode from).vi.mock("../env", () => ({- env: { LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: 0 },+ env: {+ LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: 0,+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy",+ },}));vi.mock("@langfuse/shared/src/db", () => ({prisma: {mixpanelIntegration: {- findFirst: vi.fn(async () => ({- projectId: "project-1",- enabled: true,- exportSource: "TRACES_OBSERVATIONS_EVENTS",- mixpanelRegion: "api",- encryptedMixpanelProjectToken: "enc",- lastSyncAt: new Date("2024-01-01"),- project: { name: "Test Project" },- })),+ findFirst: vi.fn(async () => h.db.integration),update: h.mixpanelIntegrationUpdate,},},@@ -115,6 +127,7 @@ vi.mock("@langfuse/shared/src/server", () => ({// Import after mocks are registered.import { handleMixpanelIntegrationProjectJob } from "../features/mixpanel/handleMixpanelIntegrationProjectJob";+import { env } from "../env";function makeJob() {return {@@ -130,6 +143,8 @@ describe("handleMixpanelIntegrationProjectJob throttling (issue #12786)", () =>h.state.activeStreams = 0;h.state.maxConcurrentStreams = 0;h.mixpanelIntegrationUpdate.mockClear();+ h.db.integration = h.defaultIntegration();+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";});it("reuses a single MixpanelClient for the whole job", async () => {@@ -150,3 +165,44 @@ describe("handleMixpanelIntegrationProjectJob throttling (issue #12786)", () =>}});});++// LFE-10148: a persisted legacy export source on an events_only deployment+// reads the v3 traces/observations tables, which are no longer written β the+// job must fail loudly before exporting empty data and advancing lastSyncAt.+describe("handleMixpanelIntegrationProjectJob events_only legacy guard (LFE-10148)", () => {+ beforeEach(() => {+ h.timeline.length = 0;+ h.mixpanelIntegrationUpdate.mockClear();+ h.db.integration = h.defaultIntegration();+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ });++ it("throws before export and does not advance lastSyncAt on events_only + legacy source", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "TRACES_OBSERVATIONS",+ };++ await expect(+ handleMixpanelIntegrationProjectJob(makeJob()),+ ).rejects.toThrow(/events_only/);++ // No stream was started (guard fires before the scores export too) and+ // sync state did not advance.+ expect(h.timeline).toHaveLength(0);+ expect(h.mixpanelIntegrationUpdate).not.toHaveBeenCalled();+ });++ it("exports an EVENTS source normally on events_only", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "EVENTS",+ };++ await handleMixpanelIntegrationProjectJob(makeJob());++ expect(h.mixpanelIntegrationUpdate).toHaveBeenCalledTimes(1);+ });+});diff --git a/worker/src/__tests__/posthogIntegrationProjectJob.test.ts b/worker/src/__tests__/posthogIntegrationProjectJob.test.tsnew file mode 100644index 0000000000..081c749dc2--- /dev/null+++ b/worker/src/__tests__/posthogIntegrationProjectJob.test.ts@@ -0,0 +1,160 @@+import { describe, it, expect, beforeEach, vi } from "vitest";++/**+ * Unit tests for the PostHog integration project job's events_only legacy+ * guard (LFE-10148): a persisted legacy export source on an events_only+ * deployment reads the v3 traces/observations tables, which are no longer+ * written β the job must fail loudly before exporting empty data and+ * advancing lastSyncAt. Mocked in the same style as+ * mixpanelIntegrationProjectJob.test.ts.+ */++// vi.mock factories are hoisted above module scope, so all shared mutable+// state the factories touch must live inside vi.hoisted().+const h = vi.hoisted(() => {+ async function* fakeStream(label: string) {+ yield { langfuse_id: `${label}-1` };+ }++ const posthogIntegrationUpdate = vi.fn();+ const getTraces = vi.fn(() => fakeStream("traces"));+ const getGenerations = vi.fn(() => fakeStream("generations"));+ const getScores = vi.fn(() => fakeStream("scores"));+ const getEvents = vi.fn(() => fakeStream("events"));++ const defaultIntegration = () => ({+ projectId: "project-1",+ enabled: true,+ exportSource: "TRACES_OBSERVATIONS",+ posthogHostName: "https://us.posthog.com",+ encryptedPosthogApiKey: "enc",+ lastSyncAt: new Date("2024-01-01"),+ project: { name: "Test Project", createdAt: new Date("2023-01-01") },+ });++ // Mutable row returned by the prisma findFirst mock so individual tests can+ // vary exportSource.+ const db = { integration: defaultIntegration() as Record<string, unknown> };++ return {+ posthogIntegrationUpdate,+ getTraces,+ getGenerations,+ getScores,+ getEvents,+ defaultIntegration,+ db,+ };+});++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ posthogIntegration: {+ findFirst: vi.fn(async () => h.db.integration),+ update: h.posthogIntegrationUpdate,+ },+ },+}));++vi.mock("@langfuse/shared/src/server", () => ({+ QueueName: { PostHogIntegrationProcessingQueue: "posthog" },+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ recordIncrement: vi.fn(),+ getCurrentSpan: vi.fn(() => undefined),+ validateWebhookURL: vi.fn(async () => {}),+ getTracesForAnalyticsIntegrations: h.getTraces,+ getGenerationsForAnalyticsIntegrations: h.getGenerations,+ getScoresForAnalyticsIntegrations: h.getScores,+ getEventsForAnalyticsIntegrations: h.getEvents,+}));++vi.mock("../features/posthog/transformers", () => ({+ transformTraceForPostHog: vi.fn((e) => e),+ transformGenerationForPostHog: vi.fn((e) => e),+ transformScoreForPostHog: vi.fn((e) => e),+ transformEventForPostHog: vi.fn((e) => e),+}));++vi.mock("@langfuse/shared/encryption", () => ({+ decrypt: vi.fn(() => "phc_decrypted"),+}));++vi.mock("posthog-node", () => ({+ PostHog: class {+ capture = vi.fn();+ flush = vi.fn(async () => {});+ on = vi.fn();+ },+}));++// Path is relative to this test file -> resolves to worker/src/env (the+// module the exportWriteModeGuard reads its write mode from).+vi.mock("../env", () => ({+ env: { LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy" },+}));++// Import after mocks are registered.+import { handlePostHogIntegrationProjectJob } from "../features/posthog/handlePostHogIntegrationProjectJob";+import { env } from "../env";++function makeJob() {+ return {+ data: { id: "job-1", payload: { projectId: "project-1" } },+ attemptsMade: 0,+ } as unknown as Parameters<typeof handlePostHogIntegrationProjectJob>[0];+}++describe("handlePostHogIntegrationProjectJob events_only legacy guard (LFE-10148)", () => {+ beforeEach(() => {+ h.posthogIntegrationUpdate.mockClear();+ h.getTraces.mockClear();+ h.getGenerations.mockClear();+ h.getScores.mockClear();+ h.getEvents.mockClear();+ h.db.integration = h.defaultIntegration();+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+ });++ it("throws before export and does not advance lastSyncAt on events_only + legacy source", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "TRACES_OBSERVATIONS",+ };++ await expect(handlePostHogIntegrationProjectJob(makeJob())).rejects.toThrow(+ /events_only/,+ );++ // No stream was started (guard fires before the scores export too) and+ // sync state did not advance.+ expect(h.getScores).not.toHaveBeenCalled();+ expect(h.getTraces).not.toHaveBeenCalled();+ expect(h.getGenerations).not.toHaveBeenCalled();+ expect(h.getEvents).not.toHaveBeenCalled();+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();+ });++ it("exports an EVENTS source normally on events_only", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ h.db.integration = {+ ...h.defaultIntegration(),+ exportSource: "EVENTS",+ };++ await handlePostHogIntegrationProjectJob(makeJob());++ expect(h.getEvents).toHaveBeenCalledTimes(1);+ expect(h.getTraces).not.toHaveBeenCalled();+ expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);+ });++ it("exports a legacy source normally on dual write mode", async () => {+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";++ await handlePostHogIntegrationProjectJob(makeJob());++ expect(h.getTraces).toHaveBeenCalledTimes(1);+ expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);+ });+});diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 30b8c37f31..50a73ddcb9 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -72,6 +72,7 @@ import { env as sharedEnv } from "@langfuse/shared/src/env";import { randomUUID } from "crypto";import { SpanKind } from "@opentelemetry/api";import { env, v4AllowPreviewOptIn } from "../../env";+import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";import { recordExportVolume } from "../../services/exportVolumeMetric";import {buildBlobExportManifest,@@ -1278,6 +1279,13 @@ export const handleBlobStorageIntegrationProjectJob = async ();}+ // Symmetric legacy-side guard (LFE-10148); the catch persists lastError+ // and notifies admins.+ assertLegacyExportSourceWritable(+ blobStorageIntegration.exportSource,+ "Select the enriched export source (OBSERVATIONS_V2) in the blob storage integration settings.",+ );+// Preflight the persisted integration endpoint once per job inside the// export error path. StorageService connection-time validation remains the// DNS-rebinding defense for each SDK connection.diff --git a/worker/src/features/exportWriteModeGuard.ts b/worker/src/features/exportWriteModeGuard.tsnew file mode 100644index 0000000000..4108c896f9--- /dev/null+++ b/worker/src/features/exportWriteModeGuard.ts@@ -0,0 +1,37 @@+import {+ areLegacyWritesActive,+ validateExportSource,+ type AnalyticsIntegrationExportSource,+} from "@langfuse/shared";+import { env } from "../env";++/**+ * Legacy-source write-mode guard for the export workers (blob storage,+ * PostHog, Mixpanel) β thin adapter over validateExportSource; policy and+ * rationale in export-source-policy.ts. Throws BEFORE any export work so each+ * handler's normal failure path (log + rethrow, BullMQ retry, and for blob+ * storage lastError persistence + admin notification) takes over instead of+ * silently exporting stale/empty data while sync state advances (LFE-10148).+ *+ * The env read lives here in worker code. `remediation` is the+ * operator-actionable closing sentence, per integration.+ */+export function assertLegacyExportSourceWritable(+ exportSource: AnalyticsIntegrationExportSource,+ remediation: string,+): void {+ const validation = validateExportSource(exportSource, {+ // Capability-only context: no dates β the Cloud cutoffs never fire here+ // (they gate writes, not running exports), and enriched availability has+ // its own dedicated worker guard.+ isCloud: false,+ enrichedAvailable: true,+ legacyWritesActive: areLegacyWritesActive(+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ ),+ });+ if (validation.ok) return;+ throw new Error(+ `The configured export source reads the legacy traces/observations tables, but this deployment runs LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only and no longer writes them. ${remediation}`,+ );+}diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.tsindex 40b2ff60ed..1acbd1be10 100644--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts@@ -20,6 +20,7 @@ import {transformEventForMixpanel,} from "./transformers";import { env } from "../../env";+import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";const sleep = (ms: number) =>ms > 0@@ -248,6 +249,13 @@ export const handleMixpanelIntegrationProjectJob = async (};try {+ // Fail loudly before exporting empty data and advancing lastSyncAt+ // (LFE-10148); the catch below logs and BullMQ retries.+ assertLegacyExportSourceWritable(+ mixpanelIntegration.exportSource,+ "Select the enriched observations export source in the Mixpanel integration settings.",+ );+// Reuse a single client and run streams sequentially so the per-job export// rate stays bounded. Running the streams in parallel with one client each// produced an unbounded burst that overwhelmed the target (issue #12786).diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.tsindex de76928ccf..7e93789e2f 100644--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts@@ -20,6 +20,7 @@ import {import { decrypt } from "@langfuse/shared/encryption";import { PostHog } from "posthog-node";import { recordExportVolume } from "../../services/exportVolumeMetric";+import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";type PostHogExecutionConfig = {projectId: string;@@ -364,6 +365,13 @@ export const handlePostHogIntegrationProjectJob = async (};try {+ // Fail loudly before exporting empty data and advancing lastSyncAt+ // (LFE-10148); the catch below logs and BullMQ retries.+ assertLegacyExportSourceWritable(+ postHogIntegration.exportSource,+ "Select the enriched observations export source in the PostHog integration settings.",+ );+const processPromises: Promise<void>[] = [];// Always include scores