πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
refactor(analytics-integrations): consolidate export-source availability policy into one module (LFE-10148) (#15151)
Niklas Semmler9f9cb98fab30
diff --git a/packages/shared/src/features/analytics-integrations/blob-export-gate.test.ts b/packages/shared/src/features/analytics-integrations/blob-export-gate.test.tsdeleted file mode 100644index 20cc72dc36..0000000000--- a/packages/shared/src/features/analytics-integrations/blob-export-gate.test.ts+++ /dev/null@@ -1,44 +0,0 @@-import { describe, it, expect } from "vitest";-import { AnalyticsIntegrationExportSource } from "@prisma/client";--import {- isEnrichedBlobExportSource,- isLegacyBlobExportSource,-} from "./blob-export-gate";--describe("isLegacyBlobExportSource", () => {- it("is true for the legacy sources", () => {- expect(- isLegacyBlobExportSource(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- ),- ).toBe(true);- expect(- isLegacyBlobExportSource(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,- ),- ).toBe(true);- });-- it("is false for the enriched-only source and nullish values", () => {- expect(- isLegacyBlobExportSource(AnalyticsIntegrationExportSource.EVENTS),- ).toBe(false);- expect(isLegacyBlobExportSource(null)).toBe(false);- expect(isLegacyBlobExportSource(undefined)).toBe(false);- });-- it("TRACES_OBSERVATIONS_EVENTS counts as both legacy and enriched", () => {- // It exports the legacy tables *and* the enriched events, so both- // predicates must return true β this project still needs the warning.- const source = AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS;- expect(isLegacyBlobExportSource(source)).toBe(true);- expect(isEnrichedBlobExportSource(source)).toBe(true);- });-- it("EVENTS is enriched-only, never legacy", () => {- const source = AnalyticsIntegrationExportSource.EVENTS;- expect(isLegacyBlobExportSource(source)).toBe(false);- expect(isEnrichedBlobExportSource(source)).toBe(true);- });-});diff --git a/packages/shared/src/features/analytics-integrations/blob-export-gate.ts b/packages/shared/src/features/analytics-integrations/blob-export-gate.tsdeleted file mode 100644index 9725ba34e3..0000000000--- a/packages/shared/src/features/analytics-integrations/blob-export-gate.ts+++ /dev/null@@ -1,124 +0,0 @@-// Business rules for the legacy blob export source deprecation gate.-// This is a client-safe file that can be imported from @langfuse/shared.--import { AnalyticsIntegrationExportSource } from "@prisma/client";--// Cloud projects created on or after this instant cannot use legacy export sources.-// Both cutoffs in this file are Cloud-only by design (the `!isCloud` short-circuits-// below): self-hosted instances can enable the enriched export via the V4 preview-// opt-in, but that must not activate these cutoffs β deprecating legacy sources-// on self-hosted is a separate, still-open decision.-// NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF overrides the default for local dev testing.-const _override = process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF- ? new Date(process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF)- : null;-export const LEGACY_BLOB_EXPORT_CUTOFF =- _override && !isNaN(_override.getTime())- ? _override- : new Date("2026-05-20T00:00:00.000Z");--// Cloud blob storage integrations created on or after this instant cannot use legacy-// export sources. Symmetric with `LEGACY_BLOB_EXPORT_CUTOFF` (project-level) but applied-// to `BlobStorageIntegration.createdAt` instead of `Project.createdAt`. Cloud-only β-// see the note above.-// NEXT_PUBLIC_LANGFUSE_BLOB_EXPORTER_CUTOFF overrides the default for local dev testing.-const _exporterOverride = process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORTER_CUTOFF- ? new Date(process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORTER_CUTOFF)- : null;-export const LEGACY_BLOB_EXPORTER_CUTOFF =- _exporterOverride && !isNaN(_exporterOverride.getTime())- ? _exporterOverride- : new Date("2026-06-22T00:00:00.000Z");--// Internal enum values that are considered "legacy". satisfies ensures each-// element remains a valid AnalyticsIntegrationExportSource β catches renames or-// removals at compile time. Adding a new enum variant does NOT automatically-// produce an error here; the list must be reviewed manually.-export const LEGACY_BLOB_EXPORT_SOURCES = [- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,-] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;--/**- * Returns true when a project may use legacy blob export sources.- * False means the project is post-cutoff Cloud and must use OBSERVATIONS_V2 (internal: EVENTS) only.- *- * Shared by the server guard (throws when false + legacy source) and the UI- * (hides legacy dropdown options when false) so the predicate lives once.- */-export function isLegacyBlobExportAllowed(- projectCreatedAt: Date,- isCloud: boolean,-): boolean {- if (!isCloud) return true;- return projectCreatedAt < LEGACY_BLOB_EXPORT_CUTOFF;-}--// Internal enum values whose export includes the enriched observations-// (events) path. satisfies ensures each element remains a valid-// AnalyticsIntegrationExportSource. Adding a new enum variant does NOT-// automatically produce an error here; the list must be reviewed manually.-export const ENRICHED_BLOB_EXPORT_SOURCES = [- AnalyticsIntegrationExportSource.EVENTS,- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,-] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;--export function isEnrichedBlobExportSource(- source: AnalyticsIntegrationExportSource | null | undefined,-): boolean {- return (- source != null &&- (- ENRICHED_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]- ).includes(source)- );-}--/**- * Whether an export source is one of the deprecated legacy sources β i.e. it- * still exports the legacy traces/observations tables. True for both- * TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS (the latter exports the- * legacy tables *and* the enriched events); false for the EVENTS-only source.- * Symmetric with isEnrichedBlobExportSource.- */-export function isLegacyBlobExportSource(- source: AnalyticsIntegrationExportSource | null | undefined,-): boolean {- return (- source != null &&- (- LEGACY_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]- ).includes(source)- );-}--/**- * Whether a blob storage integration row counts as legacy β i.e. may still use- * legacy export sources. Applied to `BlobStorageIntegration.createdAt`.- *- * - `!isCloud` β `true`: self-hosted is exempt (cutoff does not apply).- * - `null` createdAt β `false`: no existing row means a brand-new integration,- * which follows new-customer rules.- * - otherwise legacy iff the row was created strictly before the cutoff.- */-export function isLegacyBlobExporter(- integrationCreatedAt: Date | null,- isCloud: boolean,-): boolean {- if (!isCloud) return true;- if (integrationCreatedAt == null) return false;- return integrationCreatedAt < LEGACY_BLOB_EXPORTER_CUTOFF;-}--/**- * Whether this deployment has the enriched events export path.- * True for Cloud, or for self-hosted instances that have opted into the V4 preview- * via LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN (server-side only β pass the flag- * from a server-computed context rather than reading it client-side).- */-export function isEnrichedBlobExportAvailable(- isCloud: boolean,- isV4PreviewEnabled?: boolean,-): boolean {- return isCloud || isV4PreviewEnabled === true;-}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.tsnew file mode 100644index 0000000000..84624e0821--- /dev/null+++ b/packages/shared/src/features/analytics-integrations/export-source-policy.test.ts@@ -0,0 +1,175 @@+import { describe, expect, it } from "vitest";++import {+ getAvailableExportSources,+ isEnrichedBlobExportSource,+ isLegacyBlobExportSource,+ LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_BLOB_EXPORTER_CUTOFF,+ validateExportSource,+ type ExportSourceContext,+} from "./export-source-policy";++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const PROJECT_PRE = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);+const PROJECT_AT = LEGACY_BLOB_EXPORT_CUTOFF;+const PROJECT_POST = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const ROW_PRE = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY);+const ROW_AT = LEGACY_BLOB_EXPORTER_CUTOFF;++const ctx = (over: Partial<ExportSourceContext>): ExportSourceContext => ({+ isCloud: false,+ enrichedAvailable: true,+ ...over,+});++const reasonOf = (+ source: Parameters<typeof validateExportSource>[0],+ c: ExportSourceContext,+) => {+ const res = validateExportSource(source, c);+ return res.ok ? undefined : res.reason;+};++describe("validateExportSource matrix", () => {+ it("EVENTS: ok whenever enriched is available, blocked otherwise", () => {+ expect(reasonOf("EVENTS", ctx({}))).toBeUndefined();+ expect(reasonOf("EVENTS", ctx({ isCloud: true }))).toBeUndefined();+ expect(reasonOf("EVENTS", ctx({ enrichedAvailable: false }))).toBe(+ "enriched-unavailable",+ );+ });++ it("legacy on self-hosted: ok regardless of dates (cutoffs are Cloud-only)", () => {+ for (const source of [+ "TRACES_OBSERVATIONS",+ "TRACES_OBSERVATIONS_EVENTS",+ ] as const) {+ expect(+ reasonOf(+ source,+ ctx({ projectCreatedAt: PROJECT_POST, integrationCreatedAt: null }),+ ),+ ).toBeUndefined();+ }+ });++ it("legacy on Cloud: project cutoff with >= semantics", () => {+ const cloud = (projectCreatedAt: Date) =>+ ctx({ isCloud: true, projectCreatedAt, integrationCreatedAt: ROW_PRE });+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(PROJECT_PRE))).toBeUndefined();+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(PROJECT_AT))).toBe(+ "cloud-cutoff",+ );+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(PROJECT_POST))).toBe(+ "cloud-cutoff",+ );+ // Distinct messages for the two cutoff paths (log-countable).+ const res = validateExportSource(+ "TRACES_OBSERVATIONS",+ cloud(PROJECT_POST),+ );+ expect(res).toMatchObject({ ok: false });+ if (!res.ok) expect(res.message).toContain("Cloud projects");+ });++ it("legacy on Cloud: integration cutoff β new row (null) and >= cutoff blocked, pre-cutoff row grandfathered", () => {+ const cloud = (integrationCreatedAt: Date | null) =>+ ctx({+ isCloud: true,+ projectCreatedAt: PROJECT_PRE,+ integrationCreatedAt,+ });+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(ROW_PRE))).toBeUndefined();+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(ROW_AT))).toBe("cloud-cutoff");+ expect(reasonOf("TRACES_OBSERVATIONS", cloud(null))).toBe("cloud-cutoff");+ const res = validateExportSource("TRACES_OBSERVATIONS", cloud(null));+ if (!res.ok)+ expect(res.message).toContain("integrations created on or after");+ });++ it("omitted context fields skip their check", () => {+ // No project in scope (e.g. service backstop) β project gate skipped.+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS",+ ctx({ isCloud: true, integrationCreatedAt: ROW_PRE }),+ ),+ ).toBeUndefined();+ // No integration-level cutoff (PostHog/Mixpanel) β exporter gate skipped.+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS",+ ctx({ isCloud: true, projectCreatedAt: PROJECT_PRE }),+ ),+ ).toBeUndefined();+ });++ it("TRACES_OBSERVATIONS_EVENTS is both enriched and legacy; enriched-unavailable wins", () => {+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS_EVENTS",+ ctx({+ isCloud: true,+ enrichedAvailable: false,+ projectCreatedAt: PROJECT_POST,+ }),+ ),+ ).toBe("enriched-unavailable");+ // Legacy gates still apply when enriched is available.+ expect(+ reasonOf(+ "TRACES_OBSERVATIONS_EVENTS",+ ctx({ isCloud: true, projectCreatedAt: PROJECT_POST }),+ ),+ ).toBe("cloud-cutoff");+ });+});++describe("getAvailableExportSources", () => {+ it("returns all sources in UI order with per-source reasons", () => {+ const sources = getAvailableExportSources(+ ctx({ isCloud: true, projectCreatedAt: PROJECT_POST }),+ );+ expect(sources).toEqual([+ { source: "TRACES_OBSERVATIONS", blockedReason: "cloud-cutoff" },+ { source: "TRACES_OBSERVATIONS_EVENTS", blockedReason: "cloud-cutoff" },+ { source: "EVENTS" },+ ]);+ });++ it("marks nothing blocked on a permissive context", () => {+ expect(getAvailableExportSources(ctx({}))).toEqual([+ { source: "TRACES_OBSERVATIONS" },+ { source: "TRACES_OBSERVATIONS_EVENTS" },+ { source: "EVENTS" },+ ]);+ });+});++describe("isLegacyBlobExportSource", () => {+ it("is true for the legacy sources", () => {+ expect(isLegacyBlobExportSource("TRACES_OBSERVATIONS")).toBe(true);+ expect(isLegacyBlobExportSource("TRACES_OBSERVATIONS_EVENTS")).toBe(true);+ });++ it("is false for the enriched-only source and nullish values", () => {+ expect(isLegacyBlobExportSource("EVENTS")).toBe(false);+ expect(isLegacyBlobExportSource(null)).toBe(false);+ expect(isLegacyBlobExportSource(undefined)).toBe(false);+ });++ it("TRACES_OBSERVATIONS_EVENTS counts as both legacy and enriched", () => {+ // It exports the legacy tables *and* the enriched events, so both+ // predicates must return true β this project still needs the warning.+ const source = "TRACES_OBSERVATIONS_EVENTS";+ expect(isLegacyBlobExportSource(source)).toBe(true);+ expect(isEnrichedBlobExportSource(source)).toBe(true);+ });++ it("EVENTS is enriched-only, never legacy", () => {+ const source = "EVENTS";+ expect(isLegacyBlobExportSource(source)).toBe(false);+ expect(isEnrichedBlobExportSource(source)).toBe(true);+ });+});diff --git a/packages/shared/src/features/analytics-integrations/export-source-policy.ts b/packages/shared/src/features/analytics-integrations/export-source-policy.tsnew file mode 100644index 0000000000..481eec9f52--- /dev/null+++ b/packages/shared/src/features/analytics-integrations/export-source-policy.ts@@ -0,0 +1,218 @@+// Export-source availability policy for analytics integrations (blob storage,+// PostHog, Mixpanel). Client-safe: no server env reads β adapters assemble an+// ExportSourceContext from whatever they can read (env, DB rows, tRPC+// responses) and every decision funnels through the two policy functions+// below. UI option lists, the server upsert asserts, the in-transaction+// service backstop, and the worker guards are all thin adapters over this+// module.+//+// The reasoning, in one place:+//+// - CLOUD DATE CUTOFFS ("cloud-cutoff"): Cloud projects created on or after+// LEGACY_BLOB_EXPORT_CUTOFF, and Cloud blob storage integration rows created+// on or after LEGACY_BLOB_EXPORTER_CUTOFF (including brand-new rows), cannot+// use legacy export sources. These cutoffs are Cloud-only by design,+// permanently: their dates are arbitrary from a self-hosted operator's+// perspective (LFE-10065, LFE-10148). They apply to newly chosen values+// only β a persisted legacy value on an old row is grandfathered, which is+// why the cutoffs key on creation dates rather than the write path.+// - ENRICHED AVAILABILITY ("enriched-unavailable"): sources that include the+// enriched observations path (EVENTS, TRACES_OBSERVATIONS_EVENTS) need the+// enriched read path β available on Cloud, or on self-hosted via the V4+// 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).+// - 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+// the user's back.+//+// 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.++import { AnalyticsIntegrationExportSource } from "@prisma/client";++// NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF / _EXPORTER_CUTOFF override the+// defaults for local dev testing.+const _override = process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF+ ? new Date(process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF)+ : null;+export const LEGACY_BLOB_EXPORT_CUTOFF =+ _override && !isNaN(_override.getTime())+ ? _override+ : new Date("2026-05-20T00:00:00.000Z");++const _exporterOverride = process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORTER_CUTOFF+ ? new Date(process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORTER_CUTOFF)+ : null;+export const LEGACY_BLOB_EXPORTER_CUTOFF =+ _exporterOverride && !isNaN(_exporterOverride.getTime())+ ? _exporterOverride+ : new Date("2026-06-22T00:00:00.000Z");++// satisfies ensures each element remains a valid enum member β catches renames+// at compile time. A new enum variant does NOT automatically error here; the+// lists must be reviewed manually.+export const LEGACY_BLOB_EXPORT_SOURCES = [+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,+] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;++export const ENRICHED_BLOB_EXPORT_SOURCES = [+ AnalyticsIntegrationExportSource.EVENTS,+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,+] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;++export function isEnrichedBlobExportSource(+ source: AnalyticsIntegrationExportSource | null | undefined,+): boolean {+ return (+ source != null &&+ (+ ENRICHED_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]+ ).includes(source)+ );+}++/**+ * Whether an export source is one of the deprecated legacy sources β i.e. it+ * still exports the legacy traces/observations tables. True for both+ * TRACES_OBSERVATIONS and TRACES_OBSERVATIONS_EVENTS (the latter exports the+ * legacy tables *and* the enriched events); false for the EVENTS-only source.+ * Symmetric with isEnrichedBlobExportSource.+ */+export function isLegacyBlobExportSource(+ source: AnalyticsIntegrationExportSource | null | undefined,+): boolean {+ return (+ source != null &&+ (+ LEGACY_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]+ ).includes(source)+ );+}++/**+ * Whether a blob storage integration row counts as legacy β i.e. may still use+ * legacy export sources. Applied to `BlobStorageIntegration.createdAt`.+ *+ * - `!isCloud` β `true`: self-hosted is exempt (cutoff does not apply).+ * - `null` createdAt β `false`: no existing row means a brand-new integration,+ * which follows new-customer rules.+ * - otherwise legacy iff the row was created strictly before the cutoff.+ *+ * validateExportSource expresses the integration-level cutoff through this+ * predicate; it is also exported for row-age heuristics outside the policy+ * (e.g. the worker's deprecation-notice cleanup).+ */+export function isLegacyBlobExporter(+ integrationCreatedAt: Date | null,+ isCloud: boolean,+): boolean {+ if (!isCloud) return true;+ if (integrationCreatedAt == null) return false;+ return integrationCreatedAt < LEGACY_BLOB_EXPORTER_CUTOFF;+}++/** Enriched export path availability: Cloud, or self-hosted V4 preview opt-in. */+export function isEnrichedBlobExportAvailable(+ isCloud: boolean,+ isV4PreviewEnabled?: boolean,+): boolean {+ return isCloud || isV4PreviewEnabled === true;+}++/**+ * Everything the policy needs to know about a deployment/project/integration.+ * Adapters assemble it; 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+ * (PostHog/Mixpanel have no such cutoff); pass null for "no existing row",+ * which follows new-customer rules on Cloud.+ */+export type ExportSourceContext = {+ isCloud: boolean;+ enrichedAvailable: boolean;+ projectCreatedAt?: Date;+ integrationCreatedAt?: Date | null;+};++export type ExportSourceBlockedReason = "cloud-cutoff" | "enriched-unavailable";++export type ExportSourceValidation =+ | { ok: true }+ | { ok: false; reason: ExportSourceBlockedReason; message: string };++const ENRICHED_UNAVAILABLE_MESSAGE =+ "Enriched blob export is not available on this deployment";++// Distinct messages for the two Cloud-cutoff paths so rejections can be+// counted separately in logs. Customer-facing via the public REST PUT.+const PROJECT_CUTOFF_MESSAGE =+ "Legacy export sources are not available for Cloud projects created on or after 2026-05-20. Use 'OBSERVATIONS_V2' instead.";+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.`;++/** Whether a source may be selected/kept in the given context. */+export function validateExportSource(+ source: AnalyticsIntegrationExportSource,+ ctx: ExportSourceContext,+): ExportSourceValidation {+ if (isEnrichedBlobExportSource(source) && !ctx.enrichedAvailable) {+ return {+ ok: false,+ reason: "enriched-unavailable",+ message: ENRICHED_UNAVAILABLE_MESSAGE,+ };+ }+ if (isLegacyBlobExportSource(source) && ctx.isCloud) {+ if (+ ctx.projectCreatedAt !== undefined &&+ ctx.projectCreatedAt >= LEGACY_BLOB_EXPORT_CUTOFF+ ) {+ return {+ ok: false,+ reason: "cloud-cutoff",+ message: PROJECT_CUTOFF_MESSAGE,+ };+ }+ if (+ ctx.integrationCreatedAt !== undefined &&+ !isLegacyBlobExporter(ctx.integrationCreatedAt, ctx.isCloud)+ ) {+ return {+ ok: false,+ reason: "cloud-cutoff",+ message: exporterCutoffMessage(),+ };+ }+ }+ return { ok: true };+}++export type AvailableExportSource = {+ source: AnalyticsIntegrationExportSource;+ blockedReason?: ExportSourceBlockedReason;+};++// UI display order; matches EXPORT_SOURCE_OPTIONS in ./index.ts.+const EXPORT_SOURCE_ORDER = [+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,+ AnalyticsIntegrationExportSource.EVENTS,+] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;++/** All sources with their blocked reason (if any) in the given context. */+export function getAvailableExportSources(+ ctx: ExportSourceContext,+): AvailableExportSource[] {+ return EXPORT_SOURCE_ORDER.map((source) => {+ const validation = validateExportSource(source, ctx);+ return validation.ok+ ? { source }+ : { source, blockedReason: validation.reason };+ });+}diff --git a/packages/shared/src/features/analytics-integrations/index.ts b/packages/shared/src/features/analytics-integrations/index.tsindex 0c4564bd55..dd174d6d8a 100644--- a/packages/shared/src/features/analytics-integrations/index.ts+++ b/packages/shared/src/features/analytics-integrations/index.ts@@ -8,7 +8,7 @@ import {type ObservationFieldGroupFull,} from "../../domain/observation-field-groups";-export * from "./blob-export-gate";+export * from "./export-source-policy";export * from "./blob-export-tuning";export const EXPORT_SOURCE_OPTIONS: Array<{diff --git a/web/src/__tests__/server/unit/assertEnrichedBlobExportSourceAllowed.servertest.ts b/web/src/__tests__/server/unit/assertEnrichedBlobExportSourceAllowed.servertest.tsdeleted file mode 100644index 249ee657e5..0000000000--- a/web/src/__tests__/server/unit/assertEnrichedBlobExportSourceAllowed.servertest.ts+++ /dev/null@@ -1,122 +0,0 @@-import { describe, it, expect } from "vitest";-import { assertEnrichedBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed";--describe("assertEnrichedBlobExportSourceAllowed", () => {- it("Cloud + explicit EVENTS β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "EVENTS",- isCloud: true,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-- it("self-hosted + V4 preview + explicit EVENTS β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "EVENTS",- isCloud: false,- isV4PreviewEnabled: true,- }),- ).not.toThrow();- });-- it("self-hosted without V4 preview + explicit EVENTS β reject", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "EVENTS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).toThrow("Enriched blob export is not available on this deployment");- });-- it("self-hosted without V4 preview + explicit TRACES_OBSERVATIONS_EVENTS β reject", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "TRACES_OBSERVATIONS_EVENTS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).toThrow("Enriched blob export is not available on this deployment");- });-- it("self-hosted without V4 preview + explicit TRACES_OBSERVATIONS β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-- // Partial updates: the request omits exportSource, so the persisted value- // stays in effect and must satisfy the gate too (V4-preview rollback case).- it("self-hosted without V4 preview + omitted source + existing EVENTS β reject", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: undefined,- existingExportSource: "EVENTS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).toThrow("Enriched blob export is not available on this deployment");- });-- it("self-hosted without V4 preview + omitted source + existing TRACES_OBSERVATIONS_EVENTS β reject", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: undefined,- existingExportSource: "TRACES_OBSERVATIONS_EVENTS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).toThrow("Enriched blob export is not available on this deployment");- });-- it("self-hosted without V4 preview + omitted source + existing TRACES_OBSERVATIONS β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: undefined,- existingExportSource: "TRACES_OBSERVATIONS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-- it("self-hosted without V4 preview + omitted source + no existing row β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: undefined,- existingExportSource: null,- isCloud: false,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-- it("Cloud + omitted source + existing EVENTS β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: undefined,- existingExportSource: "EVENTS",- isCloud: true,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-- it("explicit legacy source overrides an existing enriched value β allow", () => {- expect(() =>- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: "TRACES_OBSERVATIONS",- existingExportSource: "EVENTS",- isCloud: false,- isV4PreviewEnabled: false,- }),- ).not.toThrow();- });-});diff --git a/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.tsnew file mode 100644index 0000000000..97d7ae9ada--- /dev/null+++ b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts@@ -0,0 +1,75 @@+import { describe, it, expect } from "vitest";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";+import {+ InvalidRequestError,+ LEGACY_BLOB_EXPORT_CUTOFF,+ type ExportSourceContext,+} from "@langfuse/shared";++// Thin composition tests only β the policy matrix lives with the policy+// (packages/shared/.../export-source-policy.test.ts).++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);++const cloudPostCutoff: ExportSourceContext = {+ isCloud: true,+ enrichedAvailable: true,+ projectCreatedAt: POST_CUTOFF,+};++describe("assertExportSourceAllowed", () => {+ it("throws InvalidRequestError with the policy message for a blocked explicit source", () => {+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: "TRACES_OBSERVATIONS",+ ctx: cloudPostCutoff,+ }),+ ).toThrow(InvalidRequestError);+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: "TRACES_OBSERVATIONS",+ ctx: cloudPostCutoff,+ }),+ ).toThrow(/Cloud projects/);+ });++ it("allows an allowed explicit source", () => {+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: "EVENTS",+ ctx: cloudPostCutoff,+ }),+ ).not.toThrow();+ });++ it("omitted source: grandfathers a persisted legacy value past the Cloud cutoffs", () => {+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: undefined,+ persistedExportSource: "TRACES_OBSERVATIONS",+ ctx: { ...cloudPostCutoff, integrationCreatedAt: POST_CUTOFF },+ }),+ ).not.toThrow();+ });++ it("omitted source: rejects a persisted value the deployment cannot export (capability reason)", () => {+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: undefined,+ persistedExportSource: "EVENTS",+ ctx: { isCloud: false, enrichedAvailable: false },+ }),+ ).toThrow(/Enriched blob export is not available/);+ });++ it("omitted source without a persisted row is a no-op", () => {+ expect(() =>+ assertExportSourceAllowed({+ nextExportSource: undefined,+ persistedExportSource: null,+ ctx: cloudPostCutoff,+ }),+ ).not.toThrow();+ });+});diff --git a/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowed.servertest.ts b/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowed.servertest.tsdeleted file mode 100644index 8e50a39ccf..0000000000--- a/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowed.servertest.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, it, expect } from "vitest";-import { assertLegacyBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed";-import {- isLegacyBlobExportAllowed,- LEGACY_BLOB_EXPORT_CUTOFF,-} from "@langfuse/shared";--const MS_PER_DAY = 24 * 60 * 60 * 1000;-const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);-const AT_CUTOFF = LEGACY_BLOB_EXPORT_CUTOFF;-const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);--describe("assertLegacyBlobExportSourceAllowed", () => {- it("Cloud + EVENTS + pre-cutoff β allow", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: PRE_CUTOFF },- nextInternalExportSource: "EVENTS",- isCloud: true,- }),- ).not.toThrow();- });-- it("Cloud + EVENTS + post-cutoff β allow", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: POST_CUTOFF },- nextInternalExportSource: "EVENTS",- isCloud: true,- }),- ).not.toThrow();- });-- it("Cloud + TRACES_OBSERVATIONS + pre-cutoff β allow (grandfathered)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: PRE_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).not.toThrow();- });-- it("Cloud + TRACES_OBSERVATIONS + post-cutoff β reject", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: POST_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-- it("Cloud + TRACES_OBSERVATIONS_EVENTS + post-cutoff β reject", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: POST_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS_EVENTS",- isCloud: true,- }),- ).toThrow();- });-- it("self-hosted + EVENTS + post-cutoff β allow (bypass)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: POST_CUTOFF },- nextInternalExportSource: "EVENTS",- isCloud: false,- }),- ).not.toThrow();- });-- it("self-hosted + TRACES_OBSERVATIONS + pre-cutoff β allow (bypass)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: PRE_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: false,- }),- ).not.toThrow();- });-- it("self-hosted + TRACES_OBSERVATIONS + post-cutoff β allow (bypass)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: POST_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: false,- }),- ).not.toThrow();- });-- it("boundary: project.createdAt === cutoff β reject (>= semantics)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowed({- project: { createdAt: AT_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-});--describe("isLegacyBlobExportAllowed predicate", () => {- it("self-hosted always returns true", () => {- expect(isLegacyBlobExportAllowed(POST_CUTOFF, false)).toBe(true);- expect(isLegacyBlobExportAllowed(AT_CUTOFF, false)).toBe(true);- expect(isLegacyBlobExportAllowed(PRE_CUTOFF, false)).toBe(true);- });-- it("Cloud + pre-cutoff β true (grandfathered)", () => {- expect(isLegacyBlobExportAllowed(PRE_CUTOFF, true)).toBe(true);- });-- it("Cloud + post-cutoff β false", () => {- expect(isLegacyBlobExportAllowed(POST_CUTOFF, true)).toBe(false);- });-- it("Cloud + exactly at cutoff β false (>= semantics)", () => {- expect(isLegacyBlobExportAllowed(AT_CUTOFF, true)).toBe(false);- });-});diff --git a/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowedForUpsert.servertest.ts b/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowedForUpsert.servertest.tsdeleted file mode 100644index 916af64b36..0000000000--- a/web/src/__tests__/server/unit/assertLegacyBlobExportSourceAllowedForUpsert.servertest.ts+++ /dev/null@@ -1,112 +0,0 @@-import { describe, it, expect } from "vitest";-import { assertLegacyBlobExportSourceAllowedForUpsert } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert";-import {- LEGACY_BLOB_EXPORT_CUTOFF,- LEGACY_BLOB_EXPORTER_CUTOFF,-} from "@langfuse/shared";--const MS_PER_DAY = 24 * 60 * 60 * 1000;--// Project-level cutoff (post-cutoff Cloud projects are forced to EVENTS).-const PROJECT_PRE_CUTOFF = new Date(- LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY,-);-const PROJECT_POST_CUTOFF = new Date(- LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY,-);--// Integration-level cutoff (rows created on/after this cannot keep legacy sources).-const INTEGRATION_PRE_CUTOFF = new Date(- LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY,-);-const INTEGRATION_AT_CUTOFF = LEGACY_BLOB_EXPORTER_CUTOFF;--describe("assertLegacyBlobExportSourceAllowedForUpsert", () => {- it("Cloud + pre-cutoff project + no row + legacy β throws", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_PRE_CUTOFF },- existingIntegration: null,- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-- it("Cloud + pre-cutoff project + row (createdAt < CUTOFF) + legacy β allows", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_PRE_CUTOFF },- existingIntegration: { createdAt: INTEGRATION_PRE_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).not.toThrow();- });-- it("Cloud + post-cutoff project + no row + legacy β throws (delegate)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_POST_CUTOFF },- existingIntegration: null,- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-- it("Cloud + post-cutoff project + row (createdAt < CUTOFF) + legacy β throws (delegate wins)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_POST_CUTOFF },- existingIntegration: { createdAt: INTEGRATION_PRE_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-- it("Cloud + any + EVENTS β allows", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_POST_CUTOFF },- existingIntegration: null,- nextInternalExportSource: "EVENTS",- isCloud: true,- }),- ).not.toThrow();- });-- it("self-hosted + post-cutoff project + no row + legacy β allows (short-circuit)", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_POST_CUTOFF },- existingIntegration: null,- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: false,- }),- ).not.toThrow();- });-- it("Cloud + pre-cutoff project + no row + TRACES_OBSERVATIONS_EVENTS β throws", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_PRE_CUTOFF },- existingIntegration: null,- nextInternalExportSource: "TRACES_OBSERVATIONS_EVENTS",- isCloud: true,- }),- ).toThrow();- });-- it("Cloud + pre-cutoff project + row (createdAt >= CUTOFF, reset-recreated) + legacy β throws", () => {- expect(() =>- assertLegacyBlobExportSourceAllowedForUpsert({- project: { createdAt: PROJECT_PRE_CUTOFF },- existingIntegration: { createdAt: INTEGRATION_AT_CUTOFF },- nextInternalExportSource: "TRACES_OBSERVATIONS",- isCloud: true,- }),- ).toThrow();- });-});diff --git a/web/src/features/blobstorage-integration/exportSource.clienttest.ts b/web/src/features/analytics-integrations/exportSource.clienttest.tssimilarity index 65%rename from web/src/features/blobstorage-integration/exportSource.clienttest.tsrename to web/src/features/analytics-integrations/exportSource.clienttest.tsindex b892b232b2..ec9ee9be38 100644--- a/web/src/features/blobstorage-integration/exportSource.clienttest.ts+++ b/web/src/features/analytics-integrations/exportSource.clienttest.ts@@ -1,58 +1,58 @@-import { AnalyticsIntegrationExportSource } from "@langfuse/shared";+import {+ AnalyticsIntegrationExportSource,+ LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_BLOB_EXPORTER_CUTOFF,+ type ExportSourceContext,+} from "@langfuse/shared";import {getExportSourceFormValue,getExportSourceOptions,+ getExportSourceUnavailableMessage,isExportSourceSelectable,shouldHideExportSourceSelector,} from "./exportSource";-const cloudPreCutoff = {- eventsExportAvailable: true,- forceEventsExport: false,+// UI-adapter tests. The policy matrix itself lives with the policy+// (packages/shared/.../export-source-policy.test.ts); these cover the+// option-list/form-value/alert derivations on representative contexts.++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const PROJECT_PRE = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);+const PROJECT_POST = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const ROW_PRE = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY);++const cloudPreCutoff: ExportSourceContext = {+ isCloud: true,+ enrichedAvailable: true,+ projectCreatedAt: PROJECT_PRE,+ integrationCreatedAt: ROW_PRE,};-const cloudPostCutoff = {- eventsExportAvailable: true,- forceEventsExport: true,+const cloudPostCutoff: ExportSourceContext = {+ isCloud: true,+ enrichedAvailable: true,+ projectCreatedAt: PROJECT_POST,+ integrationCreatedAt: ROW_PRE,};-const selfHostedWithPreview = {- eventsExportAvailable: true,- forceEventsExport: false,+const selfHostedWithPreview: ExportSourceContext = {+ isCloud: false,+ enrichedAvailable: true,};-const selfHostedRolledBack = {- eventsExportAvailable: false,- forceEventsExport: false,+const selfHostedRolledBack: ExportSourceContext = {+ isCloud: false,+ enrichedAvailable: false,};describe("getExportSourceFormValue", () => {- it("keeps a persisted enriched value when enriched export is unavailable (LFE-10296)", () => {- // Regression: the form used to substitute TRACES_OBSERVATIONS here, so any- // save silently overwrote the persisted enriched configuration.- expect(- getExportSourceFormValue(- AnalyticsIntegrationExportSource.EVENTS,- selfHostedRolledBack,- ),- ).toBe(AnalyticsIntegrationExportSource.EVENTS);- expect(- getExportSourceFormValue(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,- selfHostedRolledBack,- ),- ).toBe(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS);- });-- it("keeps any persisted value regardless of deployment state", () => {+ it("keeps any persisted value regardless of deployment state (LFE-10296)", () => {for (const persisted of Object.values(AnalyticsIntegrationExportSource)) {- for (const availability of [+ for (const ctx of [cloudPreCutoff,cloudPostCutoff,selfHostedWithPreview,selfHostedRolledBack,]) {- expect(getExportSourceFormValue(persisted, availability)).toBe(- persisted,- );+ expect(getExportSourceFormValue(persisted, ctx)).toBe(persisted);}}});@@ -77,7 +77,7 @@ describe("getExportSourceFormValue", () => {});describe("isExportSourceSelectable", () => {- it("rejects enriched sources when enriched export is unavailable", () => {+ it("rejects enriched sources when enriched export is unavailable, legacy stays", () => {expect(isExportSourceSelectable(AnalyticsIntegrationExportSource.EVENTS,@@ -98,19 +98,13 @@ describe("isExportSourceSelectable", () => {).toBe(true);});- it("rejects legacy sources on post-cutoff Cloud projects", () => {+ it("rejects legacy sources on post-cutoff Cloud projects, EVENTS stays", () => {expect(isExportSourceSelectable(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,cloudPostCutoff,),).toBe(false);- expect(- isExportSourceSelectable(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,- cloudPostCutoff,- ),- ).toBe(false);expect(isExportSourceSelectable(AnalyticsIntegrationExportSource.EVENTS,@@ -119,7 +113,7 @@ describe("isExportSourceSelectable", () => {).toBe(true);});- it("accepts all sources when enriched export is available and legacy is allowed", () => {+ it("accepts all sources when everything is available", () => {for (const source of Object.values(AnalyticsIntegrationExportSource)) {expect(isExportSourceSelectable(source, cloudPreCutoff)).toBe(true);expect(isExportSourceSelectable(source, selfHostedWithPreview)).toBe(@@ -140,17 +134,6 @@ describe("getExportSourceOptions", () => {expect(options.every((o) => !o.unavailable)).toBe(true);});- it("offers only the legacy source on a rolled-back self-hosted deployment", () => {- const options = getExportSourceOptions(- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- selfHostedRolledBack,- );- expect(options.map((o) => o.value)).toEqual([- AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- ]);- expect(options[0].unavailable).toBe(false);- });-it("offers only EVENTS for post-cutoff Cloud projects", () => {const options = getExportSourceOptions(undefined, cloudPostCutoff);expect(options.map((o) => o.value)).toEqual([@@ -171,17 +154,11 @@ describe("getExportSourceOptions", () => {options.find((o) => o.value === AnalyticsIntegrationExportSource.EVENTS)?.unavailable,).toBe(true);- expect(- options.find(- (o) => o.value === AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,- )?.unavailable,- ).toBe(false);});});describe("shouldHideExportSourceSelector", () => {it("hides the selector when there is exactly one selectable source", () => {- // Post-cutoff Cloud project: EVENTS only.expect(shouldHideExportSourceSelector(getExportSourceOptions(undefined, cloudPostCutoff),@@ -204,26 +181,32 @@ describe("shouldHideExportSourceSelector", () => {getExportSourceOptions(undefined, cloudPreCutoff),),).toBe(false);- // Stale persisted enriched source alongside the legacy fallback.- expect(- shouldHideExportSourceSelector(- getExportSourceOptions(- AnalyticsIntegrationExportSource.EVENTS,- selfHostedRolledBack,- ),- ),- ).toBe(false);});it("keeps the selector when the sole option is the stale persisted source", () => {// The unavailable-source alert points at the selector; hiding it here// would strand the user with a blocked save and nothing to change.const options = getExportSourceOptions(- AnalyticsIntegrationExportSource.EVENTS,- { eventsExportAvailable: false, forceEventsExport: true },+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ cloudPostCutoff,);- expect(options).toHaveLength(1);+ expect(options).toHaveLength(2);+ // Persisted legacy stays visible (unavailable) next to EVENTS.expect(options[0].unavailable).toBe(true);expect(shouldHideExportSourceSelector(options)).toBe(false);});});++describe("getExportSourceUnavailableMessage", () => {+ it("names the enriched path for enriched-unavailable", () => {+ const message = getExportSourceUnavailableMessage("enriched-unavailable");+ expect(message).toContain("enriched observations");+ expect(message).toContain("V4 preview opt-in");+ });++ it("describes the Cloud cutoff for cloud-cutoff", () => {+ expect(getExportSourceUnavailableMessage("cloud-cutoff")).toContain(+ "no longer available for this project",+ );+ });+});diff --git a/web/src/features/analytics-integrations/exportSource.ts b/web/src/features/analytics-integrations/exportSource.tsnew file mode 100644index 0000000000..543e49f78b--- /dev/null+++ b/web/src/features/analytics-integrations/exportSource.ts@@ -0,0 +1,82 @@+import {+ AnalyticsIntegrationExportSource,+ EXPORT_SOURCE_OPTIONS,+ getAvailableExportSources,+ validateExportSource,+ type ExportSourceBlockedReason,+ type ExportSourceContext,+ type ExportSourceOption,+} from "@langfuse/shared";++// UI adapters over the export-source policy, shared by the blob-storage,+// PostHog, and Mixpanel settings forms. Policy and rationale live in+// packages/shared/.../export-source-policy.ts.++export function isExportSourceSelectable(+ source: AnalyticsIntegrationExportSource,+ ctx: ExportSourceContext,+): boolean {+ return validateExportSource(source, ctx).ok;+}++// The persisted value always wins so initialize+save can never silently+// rewrite it (LFE-10296); validation blocks the save if it is not selectable.+export function getExportSourceFormValue(+ persisted: AnalyticsIntegrationExportSource | null | undefined,+ ctx: ExportSourceContext,+): AnalyticsIntegrationExportSource {+ if (persisted) return persisted;+ const legacySelectable = isExportSourceSelectable(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ ctx,+ );+ return ctx.enrichedAvailable || !legacySelectable+ ? AnalyticsIntegrationExportSource.EVENTS+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS;+}++export type SelectableExportSourceOption = ExportSourceOption & {+ unavailable: boolean;+};++// A single selectable option carries no decision, so the selector is hidden.+// When the sole option is the stale persisted source, keep the selector: the+// unavailable-source alert refers to it and hiding it would strand the user+// with a blocked save.+export function shouldHideExportSourceSelector(+ options: SelectableExportSourceOption[],+): boolean {+ return options.length === 1 && !options[0].unavailable;+}++// Selectable sources, plus the persisted one (marked unavailable) when it is+// no longer selectable, so the conflict is visible rather than silently+// rewritten (LFE-10296).+export function getExportSourceOptions(+ persisted: AnalyticsIntegrationExportSource | null | undefined,+ ctx: ExportSourceContext,+): SelectableExportSourceOption[] {+ return getAvailableExportSources(ctx).flatMap(({ source, blockedReason }) => {+ if (blockedReason && source !== persisted) return [];+ const option = EXPORT_SOURCE_OPTIONS.find((o) => o.value === source);+ if (!option) return [];+ return [{ ...option, unavailable: blockedReason !== undefined }];+ });+}++// Blocked-save alert body per policy reason.+const EXPORT_SOURCE_UNAVAILABLE_MESSAGES: Record<+ ExportSourceBlockedReason,+ string+> = {+ "enriched-unavailable":+ "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.",+};++export function getExportSourceUnavailableMessage(+ reason: ExportSourceBlockedReason,+): string {+ return EXPORT_SOURCE_UNAVAILABLE_MESSAGES[reason];+}diff --git a/web/src/features/analytics-integrations/server/assertExportSourceAllowed.ts b/web/src/features/analytics-integrations/server/assertExportSourceAllowed.tsnew file mode 100644index 0000000000..6fc3100251--- /dev/null+++ b/web/src/features/analytics-integrations/server/assertExportSourceAllowed.ts@@ -0,0 +1,37 @@+import {+ type ExportSourceContext,+ InvalidRequestError,+ validateExportSource,+} from "@langfuse/shared";+import { type AnalyticsIntegrationExportSource } from "@langfuse/shared/src/db";++/**+ * Write-time export-source gate shared by the blob-storage tRPC + REST upserts+ * and the PostHog/Mixpanel routers. Thin adapter over validateExportSource β+ * see export-source-policy.ts for the policy and its rationale.+ *+ * 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.+ */+export function assertExportSourceAllowed({+ nextExportSource,+ persistedExportSource,+ ctx,+}: {+ nextExportSource: AnalyticsIntegrationExportSource | undefined;+ persistedExportSource?: AnalyticsIntegrationExportSource | null;+ ctx: ExportSourceContext;+}): void {+ if (nextExportSource) {+ const validation = validateExportSource(nextExportSource, ctx);+ if (!validation.ok) throw new InvalidRequestError(validation.message);+ return;+ }+ if (!persistedExportSource) return;+ const validation = validateExportSource(persistedExportSource, ctx);+ if (!validation.ok && validation.reason !== "cloud-cutoff") {+ throw new InvalidRequestError(validation.message);+ }+}diff --git a/web/src/features/blobstorage-integration/README.md b/web/src/features/blobstorage-integration/README.mdindex 378a6fc2fe..119e2c6b17 100644--- a/web/src/features/blobstorage-integration/README.md+++ b/web/src/features/blobstorage-integration/README.md@@ -113,7 +113,7 @@ worker picks up the job and sets `runStartedAt`.| --------------------------------------------------------------------------- | ------------------------------------------------- || `deriveSyncStatus.ts` | Derives display status from DB fields || `types.ts` | Form zod schema, `BlobStorageSyncStatus` type |-| `exportSource.ts` | Export-source availability/options helpers (pure) |+| `../analytics-integrations/exportSource.ts` | Export-source option/alert UI adapters (pure); policy in `packages/shared/.../export-source-policy.ts` || `service.ts` | Upsert logic (web save path) || `blobstorage-integration-router.ts` | tRPC router (save, runNow) || `worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts` | Worker job handler |@@ -134,7 +134,7 @@ feature components below.| File | Role || ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |-| `BlobStorageIntegrationContainer.tsx` | State layer: availability derivation, the four mutations, entity-action buttons (Validate / Run Now / Reset), loading gate, identity key |+| `BlobStorageIntegrationContainer.tsx` | State layer: export-source policy context assembly, the four mutations, entity-action buttons (Validate / Run Now / Reset), loading gate, identity key || `BlobStorageIntegrationForm.tsx` | Disposable draft layer: `useForm` + schema, fields, Save; no tRPC || `formValues.ts` | Pure `buildBlobStorageFormValues()` + shared `BlobStorageFormControl` type || `StorageProviderFields.tsx` | Provider select + provider-dependent connection fields |diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex 8e417767e2..61fb2ae260 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -12,8 +12,7 @@ import {validateExportFieldGroups,} from "@/src/features/blobstorage-integration/validation";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";-import { assertLegacyBlobExportSourceAllowedForUpsert } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert";-import { assertEnrichedBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";import { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";import {@@ -132,26 +131,29 @@ export const blobStorageIntegrationRouter = createTRPCRouter({select: { createdAt: true, exportSource: true },});- // Legacy gate checks explicit values only; omitted preserves the row,- // CREATE is covered by forceEventsOnCreate below.- if (input.exportSource) {- const project = await ctx.prisma.project.findUniqueOrThrow({- where: { id: input.projectId },- select: { createdAt: true },- });- assertLegacyBlobExportSourceAllowedForUpsert({- project,- existingIntegration,- nextInternalExportSource: input.exportSource,+ // Cloud cutoffs gate explicit values only (the project is fetched just+ // for them); an omitted source preserves the row, and CREATE is covered+ // by forceEventsOnCreate below. See export-source-policy.ts.+ const projectCreatedAt = input.exportSource+ ? (+ await ctx.prisma.project.findUniqueOrThrow({+ where: { id: input.projectId },+ select: { createdAt: true },+ })+ ).createdAt+ : undefined;+ assertExportSourceAllowed({+ nextExportSource: input.exportSource,+ persistedExportSource: existingIntegration?.exportSource,+ ctx: {isCloud,- });- }-- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: input.exportSource,- existingExportSource: existingIntegration?.exportSource,- isCloud,- isV4PreviewEnabled,+ enrichedAvailable: isEnrichedBlobExportAvailable(+ isCloud,+ isV4PreviewEnabled,+ ),+ projectCreatedAt,+ integrationCreatedAt: existingIntegration?.createdAt ?? null,+ },});await auditLog({diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsxindex b98b55a2fa..271efae062 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx@@ -6,9 +6,8 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { api } from "@/src/utils/api";import {- isLegacyBlobExportAllowed,- isLegacyBlobExporter,type BlobStorageIntegration,+ type ExportSourceContext,} from "@langfuse/shared";import { type BlobStorageIntegrationFormSchema } from "@/src/features/blobstorage-integration/types";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";@@ -38,21 +37,27 @@ export const BlobStorageIntegrationContainer = ({const { isLangfuseCloud } = useLangfuseCloudRegion();const { project } = useQueryProject();- const isPostCutoffCloud =- project?.createdAt != null &&- !isLegacyBlobExportAllowed(new Date(project.createdAt), isLangfuseCloud);- const eventsExportAvailable = isEnrichedExportAvailable;- // Integration-level cutoff (Cloud only): a row predating the exporter cutoff- // keeps legacy options; a new or post-cutoff row is locked to EVENTS.- const isLegacyExporter = isLegacyBlobExporter(- config?.createdAt ? new Date(config.createdAt) : null,- isLangfuseCloud,- );- const forceEventsExport =- isPostCutoffCloud || (eventsExportAvailable && !isLegacyExporter);- const availability = useMemo(- () => ({ eventsExportAvailable, forceEventsExport }),- [eventsExportAvailable, forceEventsExport],+ // Policy context for the export-source selector; the policy itself lives in+ // export-source-policy.ts. null integrationCreatedAt = new row.+ const projectCreatedAt = project?.createdAt;+ const integrationCreatedAt = config?.createdAt;+ const exportSourceCtx: ExportSourceContext = useMemo(+ () => ({+ isCloud: isLangfuseCloud,+ enrichedAvailable: isEnrichedExportAvailable,+ projectCreatedAt: projectCreatedAt+ ? new Date(projectCreatedAt)+ : undefined,+ integrationCreatedAt: integrationCreatedAt+ ? new Date(integrationCreatedAt)+ : null,+ }),+ [+ isLangfuseCloud,+ isEnrichedExportAvailable,+ projectCreatedAt,+ integrationCreatedAt,+ ],);const utils = api.useUtils();@@ -116,9 +121,9 @@ export const BlobStorageIntegrationContainer = ({key={`${projectId}:${config ? "configured" : "new"}`}initialValues={buildBlobStorageFormValues(config ?? undefined,- availability,+ exportSourceCtx,)}- availability={availability}+ exportSourceCtx={exportSourceCtx}persistedExportSource={config?.exportSource}isSaving={mut.isPending}onSubmit={handleSubmit}diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsxindex a9eb4447d2..77f71e3757 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx@@ -2,7 +2,9 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";import {BlobStorageIntegrationFileType,BlobStorageIntegrationType,+ LEGACY_BLOB_EXPORT_CUTOFF,type BlobStorageIntegration,+ type ExportSourceContext,} from "@langfuse/shared";import { TooltipProvider } from "@/src/components/ui/tooltip";import { BlobStorageIntegrationForm } from "./BlobStorageIntegrationForm";@@ -10,13 +12,15 @@ import {buildBlobStorageFormValues,type BlobStorageFormValues,} from "./formValues";-import { type ExportSourceAvailability } from "@/src/features/blobstorage-integration/exportSource";-// EVENTS-only deployment: single selectable source, selector hidden β-// keeps the rendered tree small and the submit payload valid.-const availability: ExportSourceAvailability = {- eventsExportAvailable: true,- forceEventsExport: true,+// EVENTS-only context (post-cutoff Cloud project, new row): single selectable+// source, selector hidden β keeps the rendered tree small and the submit+// payload valid.+const exportSourceCtx: ExportSourceContext = {+ isCloud: true,+ enrichedAvailable: true,+ projectCreatedAt: new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + 1),+ integrationCreatedAt: null,};const savedConfig: Partial<BlobStorageIntegration> = {@@ -37,7 +41,7 @@ const ui = (<BlobStorageIntegrationFormkey={key}initialValues={initialValues}- availability={availability}+ exportSourceCtx={exportSourceCtx}persistedExportSource={null}isSaving={false}onSubmit={onSubmit}@@ -67,14 +71,16 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {const { rerender } = render(ui("p1:configured",- buildBlobStorageFormValues(savedConfig, availability),+ buildBlobStorageFormValues(savedConfig, exportSourceCtx),),);fireEvent.change(bucketInput(), { target: { value: "edited-bucket" } });expect(bucketInput()).toHaveValue("edited-bucket");// Container behavior after delete: config becomes null β key flips.- rerender(ui("p1:new", buildBlobStorageFormValues(undefined, availability)));+ rerender(+ ui("p1:new", buildBlobStorageFormValues(undefined, exportSourceCtx)),+ );expect(bucketInput()).toHaveValue("");expect(screen.getByLabelText("Region")).toHaveValue("auto");@@ -82,7 +88,7 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {it("project switch: key change discards unsaved input from the previous project", () => {const { rerender } = render(- ui("p1:new", buildBlobStorageFormValues(undefined, availability)),+ ui("p1:new", buildBlobStorageFormValues(undefined, exportSourceCtx)),);fireEvent.change(bucketInput(), {target: { value: "project-a-secret-bucket" },@@ -91,7 +97,9 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {target: { value: "AKIA-PROJECT-A" },});- rerender(ui("p2:new", buildBlobStorageFormValues(undefined, availability)));+ rerender(+ ui("p2:new", buildBlobStorageFormValues(undefined, exportSourceCtx)),+ );expect(bucketInput()).toHaveValue("");expect(screen.getByLabelText(/Access Key ID/)).toHaveValue("");@@ -99,14 +107,14 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {it("post-create: key flip to 'configured' initializes from the saved config", () => {const { rerender } = render(- ui("p1:new", buildBlobStorageFormValues(undefined, availability)),+ ui("p1:new", buildBlobStorageFormValues(undefined, exportSourceCtx)),);fireEvent.change(bucketInput(), { target: { value: "typed-before-save" } });rerender(ui("p1:configured",- buildBlobStorageFormValues(savedConfig, availability),+ buildBlobStorageFormValues(savedConfig, exportSourceCtx),),);@@ -120,7 +128,7 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {const { rerender } = render(ui("p1:configured",- buildBlobStorageFormValues(savedConfig, availability),+ buildBlobStorageFormValues(savedConfig, exportSourceCtx),),);fireEvent.change(bucketInput(), { target: { value: "mid-save-typing" } });@@ -130,7 +138,7 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {"p1:configured",buildBlobStorageFormValues({ ...savedConfig, bucketName: "refetched-bucket" },- availability,+ exportSourceCtx,),),);@@ -143,7 +151,7 @@ describe("BlobStorageIntegrationForm draft lifetime (keyed remount)", () => {render(ui("p1:new",- buildBlobStorageFormValues(undefined, availability),+ buildBlobStorageFormValues(undefined, exportSourceCtx),onSubmit,),);diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.tsxindex aa38cb0bcf..db2044afe3 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.tsx@@ -11,15 +11,15 @@ import {FormMessage,} from "@/src/components/ui/form";import { Switch } from "@/src/components/design-system/Switch/Switch";-import { type AnalyticsIntegrationExportSource } from "@langfuse/shared";+import {+ type AnalyticsIntegrationExportSource,+ type ExportSourceContext,+} from "@langfuse/shared";import {blobStorageIntegrationFormSchema,type BlobStorageIntegrationFormSchema,} from "@/src/features/blobstorage-integration/types";-import {- isExportSourceSelectable,- type ExportSourceAvailability,-} from "@/src/features/blobstorage-integration/exportSource";+import { isExportSourceSelectable } from "@/src/features/analytics-integrations/exportSource";import { type BlobStorageFormValues } from "@/src/features/blobstorage-integration/components/formValues";import { StorageProviderFields } from "@/src/features/blobstorage-integration/components/StorageProviderFields";import { ExportScheduleFields } from "@/src/features/blobstorage-integration/components/ExportScheduleFields";@@ -35,14 +35,14 @@ import { GzipCompressionField } from "@/src/features/blobstorage-integration/com// never patched in place.export const BlobStorageIntegrationForm = ({initialValues,- availability,+ exportSourceCtx,persistedExportSource,isSaving,onSubmit,children,}: {initialValues: BlobStorageFormValues;- availability: ExportSourceAvailability;+ exportSourceCtx: ExportSourceContext;persistedExportSource: AnalyticsIntegrationExportSource | null | undefined;isSaving: boolean;onSubmit: (values: BlobStorageIntegrationFormSchema) => void;@@ -52,13 +52,13 @@ export const BlobStorageIntegrationForm = ({children?: ReactNode;}) => {// Block the save when the persisted source is no longer selectable rather- // than silently rewriting it (LFE-10296). Availability is fixed for the- // lifetime of this mount: it derives from the project and config identity,- // and any identity change remounts the form via the container key.+ // than silently rewriting it (LFE-10296). The policy context is fixed for+ // the lifetime of this mount: it derives from the project and config+ // identity, and any identity change remounts the form via the container key.const formSchema = useMemo(() =>blobStorageIntegrationFormSchema.superRefine((data, ctx) => {- if (!isExportSourceSelectable(data.exportSource, availability)) {+ if (!isExportSourceSelectable(data.exportSource, exportSourceCtx)) {ctx.addIssue({code: "custom",path: ["exportSource"],@@ -67,7 +67,7 @@ export const BlobStorageIntegrationForm = ({});}}),- [availability],+ [exportSourceCtx],);const blobStorageForm = useForm({@@ -88,7 +88,7 @@ export const BlobStorageIntegrationForm = ({<ExportSourceFieldcontrol={control}persistedExportSource={persistedExportSource}- availability={availability}+ exportSourceCtx={exportSourceCtx}/><ExportFieldGroupsField control={control} /><GzipCompressionField control={control} />diff --git a/web/src/features/blobstorage-integration/components/ExportSourceField.tsx b/web/src/features/blobstorage-integration/components/ExportSourceField.tsxindex f44b12a228..55267ddbed 100644--- a/web/src/features/blobstorage-integration/components/ExportSourceField.tsx+++ b/web/src/features/blobstorage-integration/components/ExportSourceField.tsx@@ -21,13 +21,16 @@ import {TooltipContent,TooltipTrigger,} from "@/src/components/ui/tooltip";-import { type AnalyticsIntegrationExportSource } from "@langfuse/shared";+import {+ validateExportSource,+ type AnalyticsIntegrationExportSource,+ type ExportSourceContext,+} from "@langfuse/shared";import {getExportSourceOptions,- isExportSourceSelectable,+ getExportSourceUnavailableMessage,shouldHideExportSourceSelector,- type ExportSourceAvailability,-} from "@/src/features/blobstorage-integration/exportSource";+} from "@/src/features/analytics-integrations/exportSource";import { type BlobStorageFormControl } from "@/src/features/blobstorage-integration/components/formValues";// Export source selector plus the blocked-save alert for a persisted source@@ -35,25 +38,26 @@ import { type BlobStorageFormControl } from "@/src/features/blobstorage-integratexport const ExportSourceField = ({control,persistedExportSource,- availability,+ exportSourceCtx,}: {control: BlobStorageFormControl;persistedExportSource: AnalyticsIntegrationExportSource | null | undefined;- availability: ExportSourceAvailability;+ exportSourceCtx: ExportSourceContext;}) => {const watchedExportSource = useWatch({ control, name: "exportSource" });const exportSourceOptions = getExportSourceOptions(persistedExportSource,- availability,+ exportSourceCtx,);// No decision to make β no selector. Only the degenerate single-option// state (stale persisted source) stays visible, locked, so the// unavailable-source alert below has something to refer to.const hideExportSource = shouldHideExportSourceSelector(exportSourceOptions);const exportSourceLocked = exportSourceOptions.length === 1;- const exportSourceUnavailable =- watchedExportSource != null &&- !isExportSourceSelectable(watchedExportSource, availability);+ const watchedValidation =+ watchedExportSource != null+ ? validateExportSource(watchedExportSource, exportSourceCtx)+ : ({ ok: true } as const);return (<>@@ -129,17 +133,12 @@ export const ExportSourceField = ({/>)}- {exportSourceUnavailable && (+ {!watchedValidation.ok && (<Alert variant="destructive"><AlertTitle>Saved export source is no longer available</AlertTitle><AlertDescription>- {/* Two distinct rejection reasons; key on the deployment, not the- source, since TRACES_OBSERVATIONS_EVENTS is both enriched and- legacy. !eventsExportAvailable means enriched is genuinely- unavailable; otherwise the block is the Cloud legacy cutoff. */}- {!availability.eventsExportAvailable- ? "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."- : "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."}+ {/* Reason-specific body; texts live in the shared lookup. */}+ {getExportSourceUnavailableMessage(watchedValidation.reason)}</AlertDescription></Alert>)}diff --git a/web/src/features/blobstorage-integration/components/formValues.ts b/web/src/features/blobstorage-integration/components/formValues.tsindex 198762371e..e78c8a1072 100644--- a/web/src/features/blobstorage-integration/components/formValues.ts+++ b/web/src/features/blobstorage-integration/components/formValues.ts@@ -12,10 +12,8 @@ import type {blobStorageIntegrationFormSchema,BlobStorageIntegrationFormSchema,} from "@/src/features/blobstorage-integration/types";-import {- getExportSourceFormValue,- type ExportSourceAvailability,-} from "@/src/features/blobstorage-integration/exportSource";+import { getExportSourceFormValue } from "@/src/features/analytics-integrations/exportSource";+import { type ExportSourceContext } from "@langfuse/shared";// Pre-parse (input) shape of the form; zod defaults make some fields optional.export type BlobStorageFormValues = z.input<@@ -31,7 +29,7 @@ export type BlobStorageFormControl = Control<export function buildBlobStorageFormValues(state: Partial<BlobStorageIntegration> | undefined,- availability: ExportSourceAvailability,+ exportSourceCtx: ExportSourceContext,): BlobStorageFormValues {return {type: state?.type || BlobStorageIntegrationType.S3,@@ -48,7 +46,10 @@ export function buildBlobStorageFormValues(fileType: state?.fileType || BlobStorageIntegrationFileType.PARQUET,exportMode: state?.exportMode || BlobStorageExportMode.FULL_HISTORY,exportStartDate: state?.exportStartDate || null,- exportSource: getExportSourceFormValue(state?.exportSource, availability),+ exportSource: getExportSourceFormValue(+ state?.exportSource,+ exportSourceCtx,+ ),// Empty array in the DB means "export everything" (the worker falls back// to all groups), so surface it as the full selection in the form.exportFieldGroups: state?.exportFieldGroups?.lengthdiff --git a/web/src/features/blobstorage-integration/exportSource.ts b/web/src/features/blobstorage-integration/exportSource.tsdeleted file mode 100644index 8d29682bb4..0000000000--- a/web/src/features/blobstorage-integration/exportSource.ts+++ /dev/null@@ -1,65 +0,0 @@-import {- AnalyticsIntegrationExportSource,- EXPORT_SOURCE_OPTIONS,- isEnrichedBlobExportSource,- LEGACY_BLOB_EXPORT_SOURCES,- type ExportSourceOption,-} from "@langfuse/shared";--export type ExportSourceAvailability = {- eventsExportAvailable: boolean;- forceEventsExport: boolean;-};--// Mirrors the two server asserts: TRACES_OBSERVATIONS_EVENTS is both enriched-// and legacy, so it must clear both checks.-export function isExportSourceSelectable(- source: AnalyticsIntegrationExportSource,- availability: ExportSourceAvailability,-): boolean {- if (isEnrichedBlobExportSource(source) && !availability.eventsExportAvailable)- return false;- const isLegacy = (- LEGACY_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]- ).includes(source);- return !(isLegacy && availability.forceEventsExport);-}--// The persisted value always wins so initialize+save can never silently-// rewrite it (LFE-10296); validation blocks the save if it is not selectable.-export function getExportSourceFormValue(- persisted: AnalyticsIntegrationExportSource | null | undefined,- availability: ExportSourceAvailability,-): AnalyticsIntegrationExportSource {- if (persisted) return persisted;- return availability.eventsExportAvailable || availability.forceEventsExport- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS;-}--export type SelectableExportSourceOption = ExportSourceOption & {- unavailable: boolean;-};--// A single selectable option carries no decision, so the selector is hidden-// (post-cutoff Cloud projects never see it). When the sole option is the-// stale persisted source, keep the selector: the unavailable-source alert-// refers to it and hiding it would strand the user with a blocked save.-export function shouldHideExportSourceSelector(- options: SelectableExportSourceOption[],-): boolean {- return options.length === 1 && !options[0].unavailable;-}--// Selectable sources, plus the persisted one (marked unavailable) when it is-// no longer selectable, so the conflict is visible rather than silently rewritten.-export function getExportSourceOptions(- persisted: AnalyticsIntegrationExportSource | null | undefined,- availability: ExportSourceAvailability,-): SelectableExportSourceOption[] {- return EXPORT_SOURCE_OPTIONS.flatMap((option) => {- const selectable = isExportSourceSelectable(option.value, availability);- if (!selectable && option.value !== persisted) return [];- return [{ ...option, unavailable: !selectable }];- });-}diff --git a/web/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed.ts b/web/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed.tsdeleted file mode 100644index 8c7664b0fa..0000000000--- a/web/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed.ts+++ /dev/null@@ -1,37 +0,0 @@-import {- type AnalyticsIntegrationExportSource,- InvalidRequestError,- isEnrichedBlobExportAvailable,- isEnrichedBlobExportSource,-} from "@langfuse/shared";--/**- * Rejects enriched export sources (EVENTS, TRACES_OBSERVATIONS_EVENTS) on- * deployments where the enriched export path is unavailable (self-hosted- * without the V4 preview opt-in).- *- * For partial updates that omit exportSource, the persisted value stays in- * effect β pass it as existingExportSource so a stale enriched value left- * behind by a V4-preview flag rollback is rejected instead of silently- * driving the worker against unpopulated tables.- */-export function assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource,- existingExportSource,- isCloud,- isV4PreviewEnabled,-}: {- nextInternalExportSource: AnalyticsIntegrationExportSource | undefined;- existingExportSource?: AnalyticsIntegrationExportSource | null;- isCloud: boolean;- isV4PreviewEnabled: boolean;-}): void {- const effectiveSource = nextInternalExportSource ?? existingExportSource;- if (!isEnrichedBlobExportSource(effectiveSource)) return;-- if (isEnrichedBlobExportAvailable(isCloud, isV4PreviewEnabled)) return;-- throw new InvalidRequestError(- "Enriched blob export is not available on this deployment",- );-}diff --git a/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed.ts b/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed.tsdeleted file mode 100644index 756a26b16c..0000000000--- a/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed.ts+++ /dev/null@@ -1,29 +0,0 @@-import {- InvalidRequestError,- isLegacyBlobExportAllowed,- LEGACY_BLOB_EXPORT_SOURCES,-} from "@langfuse/shared";-import { type AnalyticsIntegrationExportSource } from "@langfuse/shared/src/db";--export function assertLegacyBlobExportSourceAllowed({- project,- nextInternalExportSource,- isCloud,-}: {- project: { createdAt: Date };- nextInternalExportSource: AnalyticsIntegrationExportSource;- isCloud: boolean;-}): void {- if (- !(LEGACY_BLOB_EXPORT_SOURCES as ReadonlyArray<string>).includes(- nextInternalExportSource,- )- )- return; // OBSERVATIONS_V2 (internal: EVENTS) is always allowed.-- if (isLegacyBlobExportAllowed(project.createdAt, isCloud)) return;-- throw new InvalidRequestError(- "Legacy export sources are not available for Cloud projects created on or after 2026-05-20. Use 'OBSERVATIONS_V2' instead.",- );-}diff --git a/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert.ts b/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert.tsdeleted file mode 100644index 9cb72de63c..0000000000--- a/web/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert.ts+++ /dev/null@@ -1,59 +0,0 @@-import {- InvalidRequestError,- isLegacyBlobExporter,- LEGACY_BLOB_EXPORT_SOURCES,- LEGACY_BLOB_EXPORTER_CUTOFF,-} from "@langfuse/shared";-import { type AnalyticsIntegrationExportSource } from "@langfuse/shared/src/db";-import { assertLegacyBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed";--/**- * Write-time gate for blob storage upserts, shared by the tRPC and REST paths.- * Composes the project-level post-cutoff gate- * (`assertLegacyBlobExportSourceAllowed`) with the integration-level cutoff: a- * row may only keep using a legacy export source if its own `createdAt`- * predates `LEGACY_BLOB_EXPORTER_CUTOFF`.- *- * `existingIntegration` is `null` for a brand-new integration, which is treated- * as non-legacy (new-customer rules) by `isLegacyBlobExporter`.- *- * Keyed on `isCloud` directly, not on enriched-export availability: self-hosted- * stays exempt even with the V4 preview enabled (see blob-export-gate.ts).- */-export function assertLegacyBlobExportSourceAllowedForUpsert({- project,- existingIntegration,- nextInternalExportSource,- isCloud,-}: {- project: { createdAt: Date };- existingIntegration: { createdAt: Date } | null;- nextInternalExportSource: AnalyticsIntegrationExportSource;- isCloud: boolean;-}): void {- // Project-level post-cutoff gate first (shared with REST). Throws on a- // post-cutoff Cloud project + legacy source regardless of the row's age.- assertLegacyBlobExportSourceAllowed({- project,- nextInternalExportSource,- isCloud,- });-- if (- !(LEGACY_BLOB_EXPORT_SOURCES as ReadonlyArray<string>).includes(- nextInternalExportSource,- )- )- return; // OBSERVATIONS_V2 (internal: EVENTS) is always allowed.-- if (isLegacyBlobExporter(existingIntegration?.createdAt ?? null, isCloud))- return;-- // Distinct message from the project-level gate so the two rejection paths can- // be counted separately in logs. Customer-facing via the public REST PUT- // (the UI prevents this state in the form flow). The date is read from the- // constant so a cutoff override stays accurate.- throw new InvalidRequestError(- `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.`,- );-}diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex 41d8965be2..9d0a91801f 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -4,9 +4,7 @@ import {BlobStorageIntegrationType,InvalidRequestError,AnalyticsIntegrationExportSource,- LEGACY_BLOB_EXPORT_SOURCES,- LEGACY_BLOB_EXPORTER_CUTOFF,- isLegacyBlobExporter,+ validateExportSource,BlobStorageIntegrationFileType,type ObservationFieldGroupFull,} from "@langfuse/shared";@@ -186,24 +184,22 @@ export async function upsertBlobStorageIntegration(params: {},});- // Race-free integration-cutoff backstop. The pre-flight `existing` snapshot- // (and the router's pre-flight gate) are racy under READ COMMITTED: a- // concurrent DELETE can flip this upsert to a CREATE after those reads.- // Validate the *persisted* row instead β its `createdAt` reflects the actual- // CREATE/UPDATE outcome (CREATE β now(); UPDATE β preserved). If the row- // that now exists is a brand-new post-cutoff Cloud exporter carrying a legacy- // source, throw to roll back. UPDATEs of pre-cutoff rows keep their- // original createdAt and are unaffected.- if (- params.refuseLegacyOnCreate &&- !isLegacyBlobExporter(result.createdAt, !isSelfHosted) &&- (LEGACY_BLOB_EXPORT_SOURCES as ReadonlyArray<string>).includes(- result.exportSource,- )- ) {- throw new InvalidRequestError(- `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.`,- );+ // Race-free backstop over the *persisted* row. The pre-flight `existing`+ // snapshot (and the router's pre-flight gate) are racy under READ+ // COMMITTED: a concurrent DELETE can flip this upsert to a CREATE after+ // those reads. `result.createdAt` reflects the actual CREATE/UPDATE+ // outcome (CREATE β now(); UPDATE β preserved), so validating it catches a+ // brand-new post-cutoff Cloud row born with a legacy source and rolls the+ // transaction back. See export-source-policy.ts.+ const backstop = validateExportSource(result.exportSource, {+ isCloud: !isSelfHosted,+ enrichedAvailable: true,+ integrationCreatedAt: params.refuseLegacyOnCreate+ ? result.createdAt+ : undefined,+ });+ if (!backstop.ok) {+ throw new InvalidRequestError(backstop.message);}return result;diff --git a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts b/web/src/features/mixpanel-integration/mixpanel-integration-router.tsindex 34174545a3..41ee40fdbc 100644--- a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts@@ -1,7 +1,7 @@import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { assertLegacyBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,@@ -71,17 +71,21 @@ export const mixpanelIntegrationRouter = createTRPCRouter({}}- // Post-cutoff Cloud projects may not select a legacy export source.- // Mirrors the blob-storage gate (LFE-9688); shares the same helper.+ // 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 },});- assertLegacyBlobExportSourceAllowed({- project,- nextInternalExportSource: input.exportSource,- isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ assertExportSourceAllowed({+ nextExportSource: input.exportSource,+ ctx: {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ projectCreatedAt: project.createdAt,+ },});}diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.tsindex 30e0fe2c45..6a5ef9645c 100644--- a/web/src/features/posthog-integration/posthog-integration-router.ts+++ b/web/src/features/posthog-integration/posthog-integration-router.ts@@ -1,7 +1,7 @@import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { assertLegacyBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowed";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {createTRPCRouter,@@ -84,17 +84,21 @@ export const posthogIntegrationRouter = createTRPCRouter({});}- // Post-cutoff Cloud projects may not select a legacy export source.- // Mirrors the blob-storage gate (LFE-9688); shares the same helper.+ // 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 },});- assertLegacyBlobExportSourceAllowed({- project,- nextInternalExportSource: input.exportSource,- isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ assertExportSourceAllowed({+ nextExportSource: input.exportSource,+ ctx: {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: true,+ projectCreatedAt: project.createdAt,+ },});}diff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex b2e2d0f39d..a3b3d8420d 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -17,8 +17,8 @@ import {ForbiddenError,} from "@langfuse/shared";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";-import { assertLegacyBlobExportSourceAllowedForUpsert } from "@/src/features/blobstorage-integration/server/assertLegacyBlobExportSourceAllowedForUpsert";-import { assertEnrichedBlobExportSourceAllowed } from "@/src/features/blobstorage-integration/server/assertEnrichedBlobExportSourceAllowed";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";+import { isEnrichedBlobExportAvailable } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { env } from "@/src/env.mjs";@@ -175,20 +175,20 @@ async function handleUpsertBlobStorageIntegration(select: { createdAt: true, exportSource: true },});- if (internalExportSource) {- assertLegacyBlobExportSourceAllowedForUpsert({- project,- existingIntegration,- nextInternalExportSource: internalExportSource,+ // Explicit sources must pass every check; an omitted source keeps the+ // persisted one, capability-checked only. See export-source-policy.ts.+ assertExportSourceAllowed({+ nextExportSource: internalExportSource,+ persistedExportSource: existingIntegration?.exportSource,+ ctx: {isCloud,- });- }-- assertEnrichedBlobExportSourceAllowed({- nextInternalExportSource: internalExportSource,- existingExportSource: existingIntegration?.exportSource,- isCloud,- isV4PreviewEnabled,+ enrichedAvailable: isEnrichedBlobExportAvailable(+ isCloud,+ isV4PreviewEnabled,+ ),+ projectCreatedAt: project.createdAt,+ integrationCreatedAt: existingIntegration?.createdAt ?? null,+ },});await auditLog({diff --git a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsxindex 4b6e67f2e9..c929529692 100644--- a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx@@ -35,7 +35,7 @@ import {import {AnalyticsIntegrationExportSource,EXPORT_SOURCE_OPTIONS,- isLegacyBlobExportAllowed,+ validateExportSource,} from "@langfuse/shared";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";@@ -152,10 +152,17 @@ const MixpanelIntegrationSettingsForm = ({// 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. Mirrors blob-storage settings (LFE-9688 / 9830).+ // EVENTS via the default below (see export-source-policy.ts).const isPostCutoffCloud =project?.createdAt != null &&- !isLegacyBlobExportAllowed(new Date(project.createdAt), isLangfuseCloud);+ !validateExportSource(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ {+ isCloud: isLangfuseCloud,+ enrichedAvailable: true,+ projectCreatedAt: new Date(project.createdAt),+ },+ ).ok;const showExportSourceField = isBetaEnabled && !isPostCutoffCloud;const mixpanelForm = useForm({diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsxindex 237c32f5ab..1b407311d4 100644--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx@@ -32,7 +32,7 @@ import { posthogIntegrationFormSchema } from "@/src/features/posthog-integrationimport {AnalyticsIntegrationExportSource,EXPORT_SOURCE_OPTIONS,- isLegacyBlobExportAllowed,+ validateExportSource,} from "@langfuse/shared";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";@@ -149,10 +149,17 @@ const PostHogIntegrationSettings = ({// 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. Mirrors blob-storage settings (LFE-9688 / 9830).+ // EVENTS via the default below (see export-source-policy.ts).const isPostCutoffCloud =project?.createdAt != null &&- !isLegacyBlobExportAllowed(new Date(project.createdAt), isLangfuseCloud);+ !validateExportSource(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ {+ isCloud: isLangfuseCloud,+ enrichedAvailable: true,+ projectCreatedAt: new Date(project.createdAt),+ },+ ).ok;const showExportSourceField = isBetaEnabled && !isPostCutoffCloud;const posthogForm = useForm({