πͺ’ 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(integrations): share one export-source default across integration families (#16253)
Niklas Semmlerf1d74d2331b0
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 62ae9eb87d..38773bc7b9 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@@ -4,22 +4,27 @@ import * as exportSourcePolicy from "./export-source-policy";import {areEnrichedWritesActive,areLegacyWritesActive,+ defaultExportSource,getAvailableExportSources,- isEnrichedBlobExportSource,- isLegacyBlobExporter,- isLegacyBlobExportSource,- LEGACY_BLOB_EXPORT_CUTOFF,+ isEnrichedExportSource,+ isLegacyExporter,+ isLegacyExportSource,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_ANALYTICS_EXPORTER_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,validateExportSource,- type BlobExportWriteMode,+ type V4WriteMode,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 PROJECT_PRE = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const PROJECT_AT = LEGACY_EXPORT_PROJECT_CUTOFF;+const PROJECT_POST = new Date(+ LEGACY_EXPORT_PROJECT_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;@@ -196,14 +201,10 @@ describe("getAvailableExportSources", () => {// sources hold data. Neither the V4 frontend preview flag nor a per-user beta// opt-in may re-enter this decision.describe("write mode drives export-source availability", () => {- const WRITE_MODES: readonly BlobExportWriteMode[] = [- "legacy",- "dual",- "events_only",- ];+ const WRITE_MODES: readonly V4WriteMode[] = ["legacy", "dual", "events_only"];const ctxFor = (- writeMode: BlobExportWriteMode,+ writeMode: V4WriteMode,over: Partial<ExportSourceContext> = {},): ExportSourceContext => ({isCloud: false,@@ -271,7 +272,7 @@ describe("write mode drives export-source availability", () => {// No special case: the combined source needs both halves, so only dual can// offer it. A hand-rolled rule for it would drift from the two predicates.it("TRACES_OBSERVATIONS_EVENTS requires dual, purely from the two rules", () => {- const ok = (mode: BlobExportWriteMode) =>+ const ok = (mode: V4WriteMode) =>validateExportSource("TRACES_OBSERVATIONS_EVENTS", ctxFor(mode)).ok;expect(ok("legacy")).toBe(false);expect(ok("dual")).toBe(true);@@ -307,30 +308,30 @@ describe("write mode drives export-source availability", () => {});});-describe("isLegacyBlobExportSource", () => {+describe("isLegacyExportSource", () => {it("is true for the legacy sources", () => {- expect(isLegacyBlobExportSource("TRACES_OBSERVATIONS")).toBe(true);- expect(isLegacyBlobExportSource("TRACES_OBSERVATIONS_EVENTS")).toBe(true);+ expect(isLegacyExportSource("TRACES_OBSERVATIONS")).toBe(true);+ expect(isLegacyExportSource("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);+ expect(isLegacyExportSource("EVENTS")).toBe(false);+ expect(isLegacyExportSource(null)).toBe(false);+ expect(isLegacyExportSource(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);+ expect(isLegacyExportSource(source)).toBe(true);+ expect(isEnrichedExportSource(source)).toBe(true);});it("EVENTS is enriched-only, never legacy", () => {const source = "EVENTS";- expect(isLegacyBlobExportSource(source)).toBe(false);- expect(isEnrichedBlobExportSource(source)).toBe(true);+ expect(isLegacyExportSource(source)).toBe(false);+ expect(isEnrichedExportSource(source)).toBe(true);});});@@ -391,7 +392,7 @@ describe("per-family exporter cutoff", () => {it("self-hosted is exempt from every exporter cutoff", () => {expect(- isLegacyBlobExporter(null, false, LEGACY_ANALYTICS_EXPORTER_CUTOFF),+ isLegacyExporter(null, false, LEGACY_ANALYTICS_EXPORTER_CUTOFF),).toBe(true);expect(reasonOf(@@ -431,3 +432,70 @@ describe("per-family exporter cutoff", () => {);});});++describe("defaultExportSource", () => {+ const forWriteMode = (+ writeMode: V4WriteMode,+ over: Partial<ExportSourceContext> = {},+ ) =>+ defaultExportSource(+ ctx({+ enrichedAvailable: areEnrichedWritesActive(writeMode),+ legacyWritesActive: areLegacyWritesActive(writeMode),+ ...over,+ }),+ );++ it("prefers enriched wherever the deployment writes it", () => {+ // `dual` is the case that used to disagree between the settings page and+ // the routers: the page defaulted to EVENTS while the routers created+ // TRACES_OBSERVATIONS. One rule now answers both.+ expect(forWriteMode("dual")).toBe("EVENTS");+ expect(forWriteMode("events_only")).toBe("EVENTS");+ });++ it("falls back to legacy only when enriched cannot be served", () => {+ expect(forWriteMode("legacy")).toBe("TRACES_OBSERVATIONS");+ });++ it("pins enriched on Cloud where the cutoffs block legacy", () => {+ // A brand-new Cloud row is post-cutoff, so legacy is not selectable even+ // under a write mode that cannot serve enriched β returning legacy would+ // hand back a value the caller is forbidden to save.+ expect(+ forWriteMode("legacy", { isCloud: true, integrationCreatedAt: null }),+ ).toBe("EVENTS");+ expect(+ forWriteMode("legacy", { isCloud: true, projectCreatedAt: PROJECT_POST }),+ ).toBe("EVENTS");+ });++ it("still allows legacy for a grandfathered Cloud row", () => {+ expect(+ forWriteMode("legacy", {+ isCloud: true,+ projectCreatedAt: PROJECT_PRE,+ integrationCreatedAt: ROW_PRE,+ }),+ ).toBe("TRACES_OBSERVATIONS");+ });++ it("never returns a source it just declared unselectable", () => {+ const modes: V4WriteMode[] = ["legacy", "dual", "events_only"];+ for (const mode of modes) {+ for (const isCloud of [false, true]) {+ // Write mode `legacy` on Cloud cannot serve enriched and cannot use+ // legacy either, so no source is selectable; the default is then a+ // misconfiguration signal rather than a usable value.+ if (mode === "legacy" && isCloud) continue;+ const c = ctx({+ isCloud,+ enrichedAvailable: areEnrichedWritesActive(mode),+ legacyWritesActive: areLegacyWritesActive(mode),+ integrationCreatedAt: null,+ });+ expect(validateExportSource(defaultExportSource(c), c).ok).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.tsindex 640587d594..40c05cde0c 100644--- a/packages/shared/src/features/analytics-integrations/export-source-policy.ts+++ b/packages/shared/src/features/analytics-integrations/export-source-policy.ts@@ -9,11 +9,11 @@// The reasoning, in one place://// - CLOUD DATE CUTOFFS ("cloud-cutoff"): Cloud projects created on or after-// LEGACY_BLOB_EXPORT_CUTOFF, and Cloud integration rows created on or after+// LEGACY_EXPORT_PROJECT_CUTOFF, and Cloud integration rows created on or after// their family's 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+// perspective. 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@@ -32,10 +32,15 @@// anything, it would export nothing. TRACES_OBSERVATIONS_EVENTS is both// families at once, so it needs dual β that falls out of the two rules// rather than being special-cased.-// - PERSISTED VALUES ARE NEVER SILENTLY REWRITTEN (LFE-10296): the UI keeps a+// - PERSISTED VALUES ARE NEVER SILENTLY REWRITTEN: 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.+// - ONE DEFAULT FOR A NEW ROW: defaultExportSource is the single answer to+// "which source should a brand-new integration get". Settings pages, tRPC+// routers and the public REST API all call it, so a create through any of+// them lands the same source. It prefers the enriched path wherever the+// deployment writes it.//// Check order inside validateExportSource doubles as the user-facing reason// precedence: enriched-unavailable first (such a source cannot export at all),@@ -58,7 +63,7 @@ function cutoffFromEnv(}// The NEXT_PUBLIC_* overrides exist for local dev testing of the cutoffs.-export const LEGACY_BLOB_EXPORT_CUTOFF = cutoffFromEnv(+export const LEGACY_EXPORT_PROJECT_CUTOFF = cutoffFromEnv(process.env.NEXT_PUBLIC_LANGFUSE_BLOB_EXPORT_CUTOFF,"2026-05-20T00:00:00.000Z",);@@ -79,23 +84,23 @@ export const LEGACY_ANALYTICS_EXPORTER_CUTOFF = cutoffFromEnv(// 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 = [+export const LEGACY_EXPORT_SOURCES = [AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;-export const ENRICHED_BLOB_EXPORT_SOURCES = [+export const ENRICHED_EXPORT_SOURCES = [AnalyticsIntegrationExportSource.EVENTS,AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS,] as const satisfies ReadonlyArray<AnalyticsIntegrationExportSource>;-export function isEnrichedBlobExportSource(+export function isEnrichedExportSource(source: AnalyticsIntegrationExportSource | null | undefined,): boolean {return (source != null &&(- ENRICHED_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]+ ENRICHED_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]).includes(source));}@@ -105,15 +110,15 @@ export function isEnrichedBlobExportSource(* 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.+ * Symmetric with isEnrichedExportSource.*/-export function isLegacyBlobExportSource(+export function isLegacyExportSource(source: AnalyticsIntegrationExportSource | null | undefined,): boolean {return (source != null &&(- LEGACY_BLOB_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]+ LEGACY_EXPORT_SOURCES as readonly AnalyticsIntegrationExportSource[]).includes(source));}@@ -134,7 +139,7 @@ export function isLegacyBlobExportSource(* predicate; it is also exported for row-age heuristics outside the policy* (e.g. the worker's deprecation-notice cleanup).*/-export function isLegacyBlobExporter(+export function isLegacyExporter(integrationCreatedAt: Date | null,isCloud: boolean,exporterCutoff: Date = LEGACY_BLOB_EXPORTER_CUTOFF,@@ -148,17 +153,15 @@ export function isLegacyBlobExporter(* 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";+export type V4WriteMode = "legacy" | "dual" | "events_only";/** Whether the deployment still writes the v3 traces/observations tables. */-export function areLegacyWritesActive(writeMode: BlobExportWriteMode): boolean {+export function areLegacyWritesActive(writeMode: V4WriteMode): boolean {return writeMode !== "events_only";}/** Whether the deployment already writes the v4 events table. */-export function areEnrichedWritesActive(- writeMode: BlobExportWriteMode,-): boolean {+export function areEnrichedWritesActive(writeMode: V4WriteMode): boolean {return writeMode !== "legacy";}@@ -191,8 +194,12 @@ export type ExportSourceValidation =| { ok: true }| { ok: false; reason: ExportSourceBlockedReason; message: string };+// Self-hosted-operator-facing: enriched writes are only absent under the legacy+// write mode, which Cloud never runs, so naming the env var is appropriate.+// Worded integration-neutrally β blob storage, PostHog and Mixpanel all reach+// it, so it must not name any one of them.const ENRICHED_UNAVAILABLE_MESSAGE =- "Enriched blob export is not available on this deployment";+ "Enriched export sources are not available while LANGFUSE_MIGRATION_V4_WRITE_MODE=legacy, because the enriched observations table is not written. Switch to a legacy export source instead.";// Distinct messages for the two Cloud-cutoff paths so rejections can be// counted separately in logs. Customer-facing via the public REST PUT.@@ -209,8 +216,7 @@ const exporterCutoffMessage = (// 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.)+// it.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.";@@ -219,17 +225,17 @@ export function validateExportSource(source: AnalyticsIntegrationExportSource,ctx: ExportSourceContext,): ExportSourceValidation {- if (isEnrichedBlobExportSource(source) && !ctx.enrichedAvailable) {+ if (isEnrichedExportSource(source) && !ctx.enrichedAvailable) {return {ok: false,reason: "enriched-unavailable",message: ENRICHED_UNAVAILABLE_MESSAGE,};}- if (isLegacyBlobExportSource(source) && ctx.isCloud) {+ if (isLegacyExportSource(source) && ctx.isCloud) {if (ctx.projectCreatedAt !== undefined &&- ctx.projectCreatedAt >= LEGACY_BLOB_EXPORT_CUTOFF+ ctx.projectCreatedAt >= LEGACY_EXPORT_PROJECT_CUTOFF) {return {ok: false,@@ -239,7 +245,7 @@ export function validateExportSource(}if (ctx.integrationCreatedAt !== undefined &&- !isLegacyBlobExporter(+ !isLegacyExporter(ctx.integrationCreatedAt,ctx.isCloud,ctx.exporterCutoff,@@ -252,7 +258,7 @@ export function validateExportSource(};}}- if (isLegacyBlobExportSource(source) && !ctx.legacyWritesActive) {+ if (isLegacyExportSource(source) && !ctx.legacyWritesActive) {return {ok: false,reason: "legacy-writes-disabled",@@ -285,3 +291,31 @@ export function getAvailableExportSources(: { source, blockedReason: validation.reason };});}++/**+ * The source a brand-new integration should be created with β the one default+ * shared by the settings pages, the tRPC routers and the public REST API, so a+ * create through any of them lands the same value.+ *+ * Enriched wins wherever the deployment writes it: it is the recommended source+ * and the only one that survives the v4 migration. The legacy source is only+ * chosen when the deployment cannot serve enriched at all (write mode `legacy`)+ * *and* legacy is actually selectable here β on a post-cutoff Cloud project it+ * is not, so enriched is returned even though it cannot export yet. That case+ * is a misconfigured deployment, and returning a source the caller is forbidden+ * to pick would fail the save with no selectable value left to offer.+ *+ * Callers must not substitute this for a persisted value; it answers CREATE+ * only. See the "persisted values are never silently rewritten" note above.+ */+export function defaultExportSource(+ ctx: ExportSourceContext,+): AnalyticsIntegrationExportSource {+ const legacySelectable = validateExportSource(+ AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,+ ctx,+ ).ok;+ return ctx.enrichedAvailable || !legacySelectable+ ? AnalyticsIntegrationExportSource.EVENTS+ : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS;+}diff --git a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.tsindex b2a3ddb793..e3f1e1ae32 100644--- a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts@@ -11,14 +11,18 @@ import {} from "@langfuse/shared/src/server";import {OBSERVATION_FIELD_GROUPS_FULL,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,} from "@langfuse/shared";import { decrypt } from "@langfuse/shared/encryption";const MS_PER_DAY = 24 * 60 * 60 * 1000;-const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);-const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const PRE_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const POST_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);const INTEGRATION_PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY,);@@ -645,7 +649,7 @@ describe("Blob Storage Integrations API", () => {describe("PUT/GET exportSource + exportFieldGroups behavior", () => {// Pin projects to a pre-cutoff date so legacy-source tests remain valid- // once the clock crosses LEGACY_BLOB_EXPORT_CUTOFF (CI runs with+ // once the clock crosses LEGACY_EXPORT_PROJECT_CUTOFF (CI runs with// NEXT_PUBLIC_LANGFUSE_CLOUD_REGION set, so the gate would otherwise// reject LEGACY_TRACES_OBSERVATIONS for projects created at now()).beforeAll(async () => {diff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.tsindex 19214ea808..b24f863639 100644--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts@@ -13,15 +13,19 @@ import {} from "@langfuse/shared/src/server";import {OBSERVATION_FIELD_GROUPS_FULL,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,} from "@langfuse/shared";import { env } from "@/src/env.mjs";import { env as sharedEnv } from "@langfuse/shared/src/env";const MS_PER_DAY = 24 * 60 * 60 * 1000;-const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);-const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const PRE_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const POST_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);// Integration-level cutoff applied to BlobStorageIntegration.createdAt.const INTEGRATION_PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY,@@ -986,7 +990,7 @@ describe("Blob Storage Integration tRPC Router", () => {});});- // LFE-10296: an update that omits exportSource must preserve the persisted+ // An update that omits exportSource must preserve the persisted// value (parity with the public REST handler) β never rewrite it to the// legacy default β and must be rejected when preserving would keep a stale// enriched source alive on a deployment without the enriched export path.@@ -1066,8 +1070,8 @@ describe("Blob Storage Integration tRPC Router", () => {it("creates with EVENTS when exportSource is omitted for a post-cutoff Cloud project", async () => {// The legacy gate only checks explicit values, so an omitted// exportSource on CREATE must not fall through to the Prisma column- // default (TRACES_OBSERVATIONS) β mirror of the REST handler's- // forceEventsOnCreate behavior.+ // default (TRACES_OBSERVATIONS) β mirror of the REST handler's resolved+ // create default.(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";const { caller, project } = await prepare();@@ -1087,6 +1091,26 @@ describe("Blob Storage Integration tRPC Router", () => {expect(row.exportSource).toBe("EVENTS");});+ it("creates with EVENTS when exportSource is omitted on a self-hosted dual deployment", async () => {+ // No Cloud cutoff applies here, so nothing forces enriched β the shared+ // default does, because dual writes the enriched table. This is the case+ // where the routers used to create TRACES_OBSERVATIONS while the settings+ // page offered EVENTS.+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";+ const { caller, project } = await prepare();++ await caller.blobStorageIntegration.update({+ projectId: project.id,+ ...configWithoutExportSource,+ });++ const row = await prisma.blobStorageIntegration.findUniqueOrThrow({+ where: { projectId: project.id },+ });+ expect(row.exportSource).toBe("EVENTS");+ });+it("still allows an explicit downgrade to a legacy source on a legacy-write-mode deployment", async () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";diff --git a/web/src/__tests__/server/mixpanel-integration.servertest.ts b/web/src/__tests__/server/mixpanel-integration.servertest.tsindex 65b334dd7d..7c139cd006 100644--- a/web/src/__tests__/server/mixpanel-integration.servertest.ts+++ b/web/src/__tests__/server/mixpanel-integration.servertest.ts@@ -5,15 +5,19 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import {LEGACY_ANALYTICS_EXPORTER_CUTOFF,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,} from "@langfuse/shared";import { decrypt } from "@langfuse/shared/encryption";import { env } from "@/src/env.mjs";const MS_PER_DAY = 24 * 60 * 60 * 1000;-const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);-const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const PRE_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const POST_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);// Row ages derive from the cutoff constants, never from literals, so the// NEXT_PUBLIC_LANGFUSE_*_CUTOFF dev overrides cannot fail the suite.const ROW_PRE_ANALYTICS_CUTOFF = new Date(@@ -244,7 +248,7 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {}});- // LFE-10148: events_only no longer writes the v3 tables, so legacy sources+ // The events_only write mode 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;@@ -393,7 +397,7 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {);});- // LFE-10148 review: the form schema's zod default must not be injected into+ // 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", () => {@@ -450,11 +454,11 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {expect(result.config?.exportSource).toBe("EVENTS");});- // Router default for an omitted exportSource: legacy writes active ?- // TRACES_OBSERVATIONS : EVENTS. It deliberately differs from the- // settings-page default (EVENTS on dual) β a pre-existing divergence this- // change does not touch, pinned here so a later fix has to flip it.- it("create without exportSource defaults to TRACES_OBSERVATIONS on dual", async () => {+ // Router default for an omitted exportSource comes from the shared policy's+ // defaultExportSource, the same rule the settings page uses: enriched+ // wherever the deployment writes it. Previously the router defaulted to+ // TRACES_OBSERVATIONS here while the page offered EVENTS.+ it("create without exportSource defaults to EVENTS on dual", async () => {const { caller, project } = await prepare();await caller.mixpanelIntegration.update({projectId: project.id,@@ -463,7 +467,7 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {const result = await caller.mixpanelIntegration.get({projectId: project.id,});- expect(result.config?.exportSource).toBe("TRACES_OBSERVATIONS");+ expect(result.config?.exportSource).toBe("EVENTS");});it("create without exportSource defaults to TRACES_OBSERVATIONS on legacy", async () => {@@ -743,7 +747,7 @@ describe("Mixpanel Integration legacy export source cutoff gate", () => {});});- // LFE-14384: the credential is write-only β get returns only a masked+ // The credential is write-only β get returns only a masked// display value; a blank token on update keeps the persisted encrypted value.describe("Mixpanel credential masking", () => {const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;diff --git a/web/src/__tests__/server/posthog-integration.servertest.ts b/web/src/__tests__/server/posthog-integration.servertest.tsindex 754a146873..7f4f7a8bdd 100644--- a/web/src/__tests__/server/posthog-integration.servertest.ts+++ b/web/src/__tests__/server/posthog-integration.servertest.ts@@ -5,15 +5,19 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import {LEGACY_ANALYTICS_EXPORTER_CUTOFF,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,} from "@langfuse/shared";import { decrypt } from "@langfuse/shared/encryption";import { env } from "@/src/env.mjs";const MS_PER_DAY = 24 * 60 * 60 * 1000;-const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);-const POST_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + MS_PER_DAY);+const PRE_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const POST_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);// Row ages derive from the cutoff constants, never from literals, so the// NEXT_PUBLIC_LANGFUSE_*_CUTOFF dev overrides cannot fail the suite.const ROW_PRE_ANALYTICS_CUTOFF = new Date(@@ -288,7 +292,7 @@ describe("PostHog Integration legacy export source cutoff gate", () => {}});- // LFE-10148: events_only no longer writes the v3 tables, so legacy sources+ // The events_only write mode 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;@@ -437,7 +441,7 @@ describe("PostHog Integration legacy export source cutoff gate", () => {);});- // LFE-10148 review: the form schema's zod default must not be injected into+ // 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", () => {@@ -494,11 +498,11 @@ describe("PostHog Integration legacy export source cutoff gate", () => {expect(result.config?.exportSource).toBe("EVENTS");});- // Router default for an omitted exportSource: legacy writes active ?- // TRACES_OBSERVATIONS : EVENTS. It deliberately differs from the- // settings-page default (EVENTS on dual) β a pre-existing divergence this- // change does not touch, pinned here so a later fix has to flip it.- it("create without exportSource defaults to TRACES_OBSERVATIONS on dual", async () => {+ // Router default for an omitted exportSource comes from the shared policy's+ // defaultExportSource, the same rule the settings page uses: enriched+ // wherever the deployment writes it. Previously the router defaulted to+ // TRACES_OBSERVATIONS here while the page offered EVENTS.+ it("create without exportSource defaults to EVENTS on dual", async () => {const { caller, project } = await prepare();await caller.posthogIntegration.update({projectId: project.id,@@ -507,7 +511,7 @@ describe("PostHog Integration legacy export source cutoff gate", () => {const result = await caller.posthogIntegration.get({projectId: project.id,});- expect(result.config?.exportSource).toBe("TRACES_OBSERVATIONS");+ expect(result.config?.exportSource).toBe("EVENTS");});it("create without exportSource defaults to TRACES_OBSERVATIONS on legacy", async () => {@@ -787,7 +791,7 @@ describe("PostHog Integration legacy export source cutoff gate", () => {});});- // LFE-14384: the credential is write-only β get returns only a masked+ // The credential is write-only β get returns only a masked// display value; a blank key on update keeps the persisted encrypted value.describe("PostHog credential masking", () => {const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;diff --git a/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.tsindex 2c9f39d4cf..e5c6abd008 100644--- a/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts+++ b/web/src/__tests__/server/unit/assertExportSourceAllowed.servertest.ts@@ -5,9 +5,9 @@ import {areLegacyWritesActive,InvalidRequestError,LEGACY_ANALYTICS_EXPORTER_CUTOFF,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,- type BlobExportWriteMode,+ type V4WriteMode,type ExportSourceContext,} from "@langfuse/shared";@@ -15,7 +15,9 @@ import {// (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 POST_CUTOFF = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);const cloudPostCutoff: ExportSourceContext = {isCloud: true,@@ -70,7 +72,7 @@ describe("assertExportSourceAllowed", () => {legacyWritesActive: true,},}),- ).toThrow(/Enriched blob export is not available/);+ ).toThrow(/Enriched export sources are not available/);expect(() =>assertExportSourceAllowed({nextExportSource: undefined,@@ -87,14 +89,14 @@ describe("assertExportSourceAllowed", () => {// The write-mode gate every save path funnels through (tRPC routers and the// public REST PUT). It must accept exactly what the UI offers for the mode.describe("write mode gate", () => {- const ctxFor = (writeMode: BlobExportWriteMode): ExportSourceContext => ({+ const ctxFor = (writeMode: V4WriteMode): ExportSourceContext => ({isCloud: false,enrichedAvailable: areEnrichedWritesActive(writeMode),legacyWritesActive: areLegacyWritesActive(writeMode),});const attempt = (- writeMode: BlobExportWriteMode,+ writeMode: V4WriteMode,nextExportSource:| "TRACES_OBSERVATIONS"| "TRACES_OBSERVATIONS_EVENTS"@@ -104,7 +106,7 @@ describe("assertExportSourceAllowed", () => {const cases: Array<[- BlobExportWriteMode,+ V4WriteMode,"TRACES_OBSERVATIONS" | "TRACES_OBSERVATIONS_EVENTS" | "EVENTS",boolean,]@@ -163,7 +165,7 @@ describe("assertExportSourceAllowed", () => {isCloud: true,enrichedAvailable: true,legacyWritesActive: true,- projectCreatedAt: new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - 1),+ projectCreatedAt: new Date(LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - 1),integrationCreatedAt: between,},};diff --git a/web/src/features/analytics-integrations/exportSource.clienttest.ts b/web/src/features/analytics-integrations/exportSource.clienttest.tsindex 7f84948a8d..7e6d063992 100644--- a/web/src/features/analytics-integrations/exportSource.clienttest.ts+++ b/web/src/features/analytics-integrations/exportSource.clienttest.ts@@ -1,9 +1,9 @@import {AnalyticsIntegrationExportSource,LEGACY_ANALYTICS_EXPORTER_CUTOFF,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,LEGACY_BLOB_EXPORTER_CUTOFF,- type BlobExportWriteMode,+ type V4WriteMode,type ExportSourceContext,} from "@langfuse/shared";@@ -22,14 +22,18 @@ import {// 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 PROJECT_PRE = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() - MS_PER_DAY,+);+const PROJECT_POST = new Date(+ LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + MS_PER_DAY,+);const ROW_PRE = new Date(LEGACY_BLOB_EXPORTER_CUTOFF.getTime() - MS_PER_DAY);// Self-hosted unless a case overrides it, so the two capability flags always// come from the real builder rather than being hand-set per case.const ctxFor = (- writeMode: BlobExportWriteMode,+ writeMode: V4WriteMode,over: Partial<Omit<ExportSourceContext, "enrichedAvailable" | "legacyWritesActive">> = {},@@ -60,7 +64,7 @@ const selfHostedRolledBack: ExportSourceContext = {enrichedAvailable: false,legacyWritesActive: true,};-// Self-hosted events_only: v3 tables no longer written (LFE-10148). Enriched+// Self-hosted events_only: v3 tables no longer written. Enriched// stays available (events_only requires the V4 preview opt-in).const selfHostedEventsOnly: ExportSourceContext = {isCloud: false,@@ -69,7 +73,7 @@ const selfHostedEventsOnly: ExportSourceContext = {};describe("getExportSourceFormValue", () => {- it("keeps any persisted value regardless of deployment state (LFE-10296)", () => {+ it("keeps any persisted value regardless of deployment state", () => {for (const persisted of Object.values(AnalyticsIntegrationExportSource)) {for (const ctx of [cloudPreCutoff,@@ -100,7 +104,7 @@ describe("getExportSourceFormValue", () => {);});- it("defaults new configurations to EVENTS on events_only, keeps a persisted legacy value (LFE-10148)", () => {+ it("defaults new configurations to EVENTS on events_only, keeps a persisted legacy value", () => {expect(getExportSourceFormValue(undefined, selfHostedEventsOnly)).toBe(AnalyticsIntegrationExportSource.EVENTS,);@@ -159,7 +163,7 @@ describe("isExportSourceSelectable", () => {}});- it("rejects legacy sources on events_only, EVENTS stays (LFE-10148)", () => {+ it("rejects legacy sources on events_only, EVENTS stays", () => {expect(isExportSourceSelectable(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,@@ -193,7 +197,7 @@ describe("getExportSourceOptions", () => {]);});- it("marks a persisted legacy source unavailable on events_only, EVENTS selectable (LFE-10148)", () => {+ it("marks a persisted legacy source unavailable on events_only, EVENTS selectable", () => {const options = getExportSourceOptions(AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS,selfHostedEventsOnly,@@ -210,7 +214,7 @@ describe("getExportSourceOptions", () => {expect(shouldHideExportSourceSelector(options)).toBe(false);});- it("includes a stale persisted enriched source, marked unavailable (LFE-10296)", () => {+ it("includes a stale persisted enriched source, marked unavailable", () => {const options = getExportSourceOptions(AnalyticsIntegrationExportSource.EVENTS,selfHostedRolledBack,@@ -272,16 +276,14 @@ describe("shouldHideExportSourceSelector", () => {// env var. Driving these cases through the real builder is what covers that// wiring; the builder takes no session or beta input at all.describe("write mode drives the settings-page selector", () => {- const WRITE_MODES: BlobExportWriteMode[] = ["legacy", "dual", "events_only"];+ const WRITE_MODES: V4WriteMode[] = ["legacy", "dual", "events_only"];const selectableValues = (ctx: ExportSourceContext) =>getExportSourceOptions(undefined, ctx).filter((o) => !o.unavailable).map((o) => o.value);- const offered: Array<- [BlobExportWriteMode, AnalyticsIntegrationExportSource[]]- > = [+ const offered: Array<[V4WriteMode, AnalyticsIntegrationExportSource[]]> = [["legacy", [AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS]],["dual",@@ -301,18 +303,15 @@ describe("write mode drives the settings-page selector", () => {},);- const defaults: Array<- [BlobExportWriteMode, AnalyticsIntegrationExportSource]- > = [+ const defaults: Array<[V4WriteMode, AnalyticsIntegrationExportSource]> = [["legacy", AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS],["dual", AnalyticsIntegrationExportSource.EVENTS],["events_only", AnalyticsIntegrationExportSource.EVENTS],];- // The settings-page create default: areEnrichedWritesActive(writeMode)- // ? EVENTS : TRACES_OBSERVATIONS. The tRPC/REST routers keep their own,- // older default for an omitted exportSource (TRACES_OBSERVATIONS on dual);- // that divergence predates this change and is tracked separately.+ // The create default comes from the shared policy's defaultExportSource, so+ // the settings page, the tRPC routers and the public REST API all land the+ // same source. Its own matrix lives in export-source-policy.test.ts.it.each(defaults)("write mode %s picks %s as the settings-page create default",(mode, expected) => {@@ -360,7 +359,7 @@ describe("write mode drives the settings-page selector", () => {// A source that was legal when it was saved must never silently vanish: the// user has to see why their save is blocked and what to switch to.const blockedPersisted: Array<- [BlobExportWriteMode, AnalyticsIntegrationExportSource]+ [V4WriteMode, AnalyticsIntegrationExportSource]> = [["legacy", AnalyticsIntegrationExportSource.EVENTS],["legacy", AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS_EVENTS],@@ -409,7 +408,7 @@ describe("write mode drives the settings-page selector", () => {// The pages consume only this composite, so the pieces being correct// individually is not enough β visibility and the default must agree.describe("getExportSourceFieldState", () => {- it.each<BlobExportWriteMode>(["legacy", "dual", "events_only"])(+ it.each<V4WriteMode>(["legacy", "dual", "events_only"])("%s: a hidden selector always leaves a selectable default",(mode) => {const ctx = ctxFor(mode);@@ -433,7 +432,7 @@ describe("getExportSourceFieldState", () => {expect(defaultValue).toBe(AnalyticsIntegrationExportSource.EVENTS);});- it.each<[BlobExportWriteMode, AnalyticsIntegrationExportSource]>([+ it.each<[V4WriteMode, AnalyticsIntegrationExportSource]>([["legacy", AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS],["events_only", AnalyticsIntegrationExportSource.EVENTS],])("%s hides the selector and defaults to %s", (mode, expected) => {@@ -498,7 +497,7 @@ describe("getExportSourceFieldState", () => {// Pre-cutoff projects are exempt from the cutoff, leaving only the write// mode.- it.each<BlobExportWriteMode>(["legacy", "dual", "events_only"])(+ it.each<V4WriteMode>(["legacy", "dual", "events_only"])("%s: pre-cutoff Cloud matches self-hosted",(mode) => {expect(diff --git a/web/src/features/analytics-integrations/exportSource.ts b/web/src/features/analytics-integrations/exportSource.tsindex 8dd86bb743..8e96f060ef 100644--- a/web/src/features/analytics-integrations/exportSource.ts+++ b/web/src/features/analytics-integrations/exportSource.ts@@ -1,11 +1,12 @@import {- AnalyticsIntegrationExportSource,areEnrichedWritesActive,areLegacyWritesActive,+ defaultExportSource,EXPORT_SOURCE_OPTIONS,getAvailableExportSources,validateExportSource,- type BlobExportWriteMode,+ type AnalyticsIntegrationExportSource,+ type V4WriteMode,type ExportSourceBlockedReason,type ExportSourceContext,type ExportSourceOption,@@ -24,7 +25,7 @@ export function buildExportSourceContext({integrationCreatedAt,exporterCutoff,}: {- writeMode: BlobExportWriteMode;+ writeMode: V4WriteMode;isCloud: boolean;projectCreatedAt?: Date;integrationCreatedAt?: Date | null;@@ -48,19 +49,14 @@ export function isExportSourceSelectable(}// The persisted value always wins so initialize+save can never silently-// rewrite it (LFE-10296); validation blocks the save if it is not selectable.+// rewrite it; validation blocks the save if it is not selectable. A create+// falls through to the shared policy default, which the routers use too, so the+// page and the server agree on what a new integration gets.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;+ return persisted ?? defaultExportSource(ctx);}export type SelectableExportSourceOption = ExportSourceOption & {@@ -79,7 +75,7 @@ export function shouldHideExportSourceSelector(// 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).+// rewritten.export function getExportSourceOptions(persisted: AnalyticsIntegrationExportSource | null | undefined,ctx: ExportSourceContext,diff --git a/web/src/features/analytics-integrations/server/analyticsExportSource.ts b/web/src/features/analytics-integrations/server/analyticsExportSource.tsdeleted file mode 100644index 00a8ef767a..0000000000--- a/web/src/features/analytics-integrations/server/analyticsExportSource.ts+++ /dev/null@@ -1,146 +0,0 @@-import {- AnalyticsIntegrationExportSource,- areEnrichedWritesActive,- areLegacyWritesActive,- InvalidRequestError,- LEGACY_ANALYTICS_EXPORTER_CUTOFF,- validateExportSource,- type ExportSourceContext,-} from "@langfuse/shared";-import { type Prisma } from "@langfuse/shared/src/db";--import { env } from "@/src/env.mjs";-import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";--/**- * Write-time export-source handling for the PostHog and Mixpanel routers, whose- * upserts are otherwise identical here. Assembles the ExportSourceContext both- * routers need β see export-source-policy.ts for the policy itself.- */--type ExistingAnalyticsIntegration = {- exportSource: AnalyticsIntegrationExportSource;- createdAt: Date;-};--type Deployment = {- isCloud: boolean;- enrichedAvailable: boolean;- legacyWritesActive: boolean;-};--function readDeployment(): Deployment {- const writeMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;- return {- isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),- enrichedAvailable: areEnrichedWritesActive(writeMode),- legacyWritesActive: areLegacyWritesActive(writeMode),- };-}--function buildContext(- deployment: Deployment,- projectCreatedAt: Date | undefined,- integrationCreatedAt: Date | null,-): ExportSourceContext {- return {- ...deployment,- projectCreatedAt,- integrationCreatedAt,- exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,- };-}--/**- * Validates the requested source (throwing InvalidRequestError when blocked)- * and returns the value the upsert's CREATE branch should carry. That value- * prefers the persisted source, because a concurrent delete can turn an upsert- * meant as an UPDATE into a CREATE; assertRacedCreateAllowed judges what lands.- */-export async function resolveAnalyticsExportSource({- db,- projectId,- requestedExportSource,- existingIntegration,-}: {- db: Prisma.TransactionClient;- projectId: string;- requestedExportSource: AnalyticsIntegrationExportSource | undefined;- existingIntegration: ExistingAnalyticsIntegration | null | undefined;-}): Promise<AnalyticsIntegrationExportSource> {- const deployment = readDeployment();- // On Cloud the legacy source is unavailable to a new row, so defaulting to it- // would only produce a rejection.- const createDefaultExportSource =- deployment.isCloud || !deployment.legacyWritesActive- ? AnalyticsIntegrationExportSource.EVENTS- : AnalyticsIntegrationExportSource.TRACES_OBSERVATIONS;-- const nextExportSource =- requestedExportSource ??- (existingIntegration ? undefined : createDefaultExportSource);- // The Cloud cutoffs need the project only for explicitly chosen (or- // create-defaulted) sources.- const projectCreatedAt = nextExportSource- ? (- await db.project.findUniqueOrThrow({- where: { id: projectId },- select: { createdAt: true },- })- ).createdAt- : undefined;-- assertExportSourceAllowed({- nextExportSource,- persistedExportSource: existingIntegration?.exportSource,- ctx: buildContext(- deployment,- projectCreatedAt,- existingIntegration?.createdAt ?? null,- ),- });-- return (- requestedExportSource ??- existingIntegration?.exportSource ??- createDefaultExportSource- );-}--/**- * In-transaction backstop (mirrors blob storage's service.ts). The pre-flight- * read is racy: a concurrent delete can flip the expected UPDATE into a CREATE.- * A changed createdAt detects that, and the row is re-validated as the brand-new- * row it is β not as the grandfathered one the pre-flight read saw.- *- * This runs whether or not the request named a source: an explicit source is- * also validated against the existing row's age, so a raced create leaves it- * judged by a row that no longer exists.- */-export async function assertRacedCreateAllowed({- tx,- projectId,- existingIntegration,- result,-}: {- tx: Prisma.TransactionClient;- projectId: string;- existingIntegration: ExistingAnalyticsIntegration | null | undefined;- result: ExistingAnalyticsIntegration;-}): Promise<void> {- if (- !existingIntegration ||- result.createdAt.getTime() === existingIntegration.createdAt.getTime()- ) {- return;- }- const project = await tx.project.findUniqueOrThrow({- where: { id: projectId },- select: { createdAt: true },- });- const validation = validateExportSource(- result.exportSource,- buildContext(readDeployment(), project.createdAt, null),- );- if (!validation.ok) throw new InvalidRequestError(validation.message);-}diff --git a/web/src/features/analytics-integrations/server/exportSource.ts b/web/src/features/analytics-integrations/server/exportSource.tsnew file mode 100644index 0000000000..477950bb2d--- /dev/null+++ b/web/src/features/analytics-integrations/server/exportSource.ts@@ -0,0 +1,173 @@+import {+ type AnalyticsIntegrationExportSource,+ areEnrichedWritesActive,+ areLegacyWritesActive,+ defaultExportSource,+ InvalidRequestError,+ validateExportSource,+ type ExportSourceContext,+} from "@langfuse/shared";+import { type Prisma } from "@langfuse/shared/src/db";++import { env } from "@/src/env.mjs";+import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";++/**+ * Write-time export-source handling shared by every integration family's upsert+ * (blob storage, PostHog, Mixpanel). Assembles the ExportSourceContext they all+ * need from server env β see export-source-policy.ts for the policy itself.+ *+ * Each family passes its own `exporterCutoff`; omitting it falls back to the+ * blob date, matching the policy default.+ */++type ExistingIntegration = {+ exportSource: AnalyticsIntegrationExportSource;+ createdAt: Date;+};++type Deployment = {+ isCloud: boolean;+ enrichedAvailable: boolean;+ legacyWritesActive: boolean;+};++function readDeployment(): Deployment {+ const writeMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ return {+ isCloud: Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION),+ enrichedAvailable: areEnrichedWritesActive(writeMode),+ legacyWritesActive: areLegacyWritesActive(writeMode),+ };+}++function buildContext(+ deployment: Deployment,+ projectCreatedAt: Date | undefined,+ integrationCreatedAt: Date | null,+ exporterCutoff: Date | undefined,+): ExportSourceContext {+ return {+ ...deployment,+ projectCreatedAt,+ integrationCreatedAt,+ exporterCutoff,+ };+}++/**+ * Validates the requested source (throwing InvalidRequestError when blocked)+ * and returns the value the upsert's CREATE branch should carry. That value+ * prefers the persisted source, because a concurrent delete can turn an upsert+ * meant as an UPDATE into a CREATE; assertPersistedExportSourceAllowed judges+ * what actually lands.+ *+ * The returned value is always concrete, never undefined, so the CREATE payload+ * can never fall through to the legacy Prisma column default.+ *+ * Callers that already hold the project row (the public REST handler loads it+ * for its org-ownership check) pass `projectCreatedAt` to skip the lookup below.+ * The tRPC routers have no project in scope and omit it.+ */+export async function resolveExportSource({+ db,+ projectId,+ projectCreatedAt: prefetchedProjectCreatedAt,+ requestedExportSource,+ existingIntegration,+ exporterCutoff,+}: {+ db: Prisma.TransactionClient;+ projectId: string;+ projectCreatedAt?: Date;+ requestedExportSource: AnalyticsIntegrationExportSource | undefined;+ existingIntegration: ExistingIntegration | null | undefined;+ exporterCutoff?: Date;+}): Promise<AnalyticsIntegrationExportSource> {+ const deployment = readDeployment();++ // The Cloud cutoffs need the project only when this call chooses a source β+ // an explicit request, or the create default for a row that does not exist+ // yet. A partial update that keeps the persisted value needs no project date+ // at all, so it stays undefined even when the caller prefetched one: that is+ // what lets the cutoffs grandfather a persisted legacy value.+ const choosesSource =+ requestedExportSource !== undefined || !existingIntegration;+ const projectCreatedAt = !choosesSource+ ? undefined+ : (prefetchedProjectCreatedAt ??+ (+ await db.project.findUniqueOrThrow({+ where: { id: projectId },+ select: { createdAt: true },+ })+ ).createdAt);++ // The create default is judged by new-integration rules, hence the null+ // integrationCreatedAt: the Cloud cutoffs must not grandfather a row that+ // does not exist yet.+ const createDefault = defaultExportSource(+ buildContext(deployment, projectCreatedAt, null, exporterCutoff),+ );++ assertExportSourceAllowed({+ nextExportSource:+ requestedExportSource ??+ (existingIntegration ? undefined : createDefault),+ persistedExportSource: existingIntegration?.exportSource,+ ctx: buildContext(+ deployment,+ projectCreatedAt,+ existingIntegration?.createdAt ?? null,+ exporterCutoff,+ ),+ });++ return (+ requestedExportSource ?? existingIntegration?.exportSource ?? createDefault+ );+}++/**+ * In-transaction backstop over the row that actually landed. The pre-flight read+ * is racy under READ COMMITTED: a concurrent delete can flip the expected UPDATE+ * into a CREATE, and a concurrent create can flip the expected CREATE into an+ * UPDATE. Validating `result` closes both windows, and it runs unconditionally+ * so no path escapes the check.+ *+ * `result.createdAt` alone is not enough to decide how strictly to judge the+ * row: while a family's exporter cutoff is still in the future, a row created+ * *now* is still before the cutoff and would be grandfathered by date, defeating+ * the rule that a brand-new Cloud integration never gets a legacy source. So a+ * row this transaction created is passed as null (new-integration rules) and+ * only a row that predates the transaction is judged by its own date.+ *+ * projectCreatedAt is deliberately omitted: the project-level cutoff gates newly+ * chosen values, and applying it here would reject grandfathered rows on every+ * partial update. A raced create is still caught, because a new row on Cloud+ * fails the integration-level check above.+ */+export function assertPersistedExportSourceAllowed({+ existingIntegration,+ result,+ exporterCutoff,+}: {+ existingIntegration: ExistingIntegration | null | undefined;+ result: ExistingIntegration;+ exporterCutoff?: Date;+}): void {+ const createdByThisTransaction =+ !existingIntegration ||+ result.createdAt.getTime() !== existingIntegration.createdAt.getTime();++ const validation = validateExportSource(+ result.exportSource,+ buildContext(+ readDeployment(),+ undefined,+ createdByThisTransaction ? null : result.createdAt,+ exporterCutoff,+ ),+ );+ 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 04ec2c4ba3..dd83f7395c 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -12,7 +12,7 @@ import {validateExportFieldGroups,} from "@/src/features/blobstorage-integration/validation";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";-import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";+import { resolveExportSource } from "@/src/features/analytics-integrations/server/exportSource";import { TRPCError } from "@trpc/server";import { env } from "@/src/env.mjs";import {@@ -27,8 +27,6 @@ import { randomUUID } from "crypto";import { decrypt } from "@langfuse/shared/encryption";import {AnalyticsIntegrationExportSource,- areEnrichedWritesActive,- areLegacyWritesActive,BlobStorageIntegrationType,BlobStorageIntegrationFileType,InvalidRequestError,@@ -119,39 +117,20 @@ export const blobStorageIntegrationRouter = createTRPCRouter({scope: "integrations:CRUD",});- const isCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);-const existingIntegration =await ctx.prisma.blobStorageIntegration.findUnique({where: { projectId: input.projectId },select: { createdAt: true, exportSource: true },});- // 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,- enrichedAvailable: areEnrichedWritesActive(- env.LANGFUSE_MIGRATION_V4_WRITE_MODE,- ),- legacyWritesActive: areLegacyWritesActive(- env.LANGFUSE_MIGRATION_V4_WRITE_MODE,- ),- projectCreatedAt,- integrationCreatedAt: existingIntegration?.createdAt ?? null,- },+ // Validates the requested source and resolves what a CREATE should+ // carry. Shared with the PostHog and Mixpanel routers and the public+ // REST handler, so every write path agrees. See export-source-policy.ts.+ const createExportSource = await resolveExportSource({+ db: ctx.prisma,+ projectId: input.projectId,+ requestedExportSource: input.exportSource,+ existingIntegration,});await auditLog({@@ -166,11 +145,7 @@ export const blobStorageIntegrationRouter = createTRPCRouter({return await upsertBlobStorageIntegration({prisma: ctx.prisma,projectId,- // Mirror the REST handler: substitute EVENTS for an omitted source on- // a new Cloud row, and refuse a legacy source if a concurrent DELETE- // flips this upsert to CREATE.- forceEventsOnCreate: input.exportSource === undefined && isCloud,- refuseLegacyOnCreate: isCloud,+ createExportSource,data: {type: rest.type,bucketName: rest.bucketName,diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsxindex 309a6d46c3..a16ee8d837 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationContainer.tsx@@ -6,7 +6,7 @@ import { showSuccessToast } from "@/src/features/notifications/showSuccessToast"import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { api } from "@/src/utils/api";import {- type BlobExportWriteMode,+ type V4WriteMode,type BlobStorageIntegration,type ExportSourceContext,} from "@langfuse/shared";@@ -31,7 +31,7 @@ export const BlobStorageIntegrationContainer = ({}: {config: Partial<BlobStorageIntegration> | null;projectId: string;- writeMode: BlobExportWriteMode;+ writeMode: V4WriteMode;}) => {const capture = usePostHogClientCapture();const { isLangfuseCloud } = useLangfuseCloudRegion();diff --git a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsxindex 527d28d80a..2c15d3c82b 100644--- a/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx+++ b/web/src/features/blobstorage-integration/components/BlobStorageIntegrationForm.clienttest.tsx@@ -2,7 +2,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";import {BlobStorageIntegrationFileType,BlobStorageIntegrationType,- LEGACY_BLOB_EXPORT_CUTOFF,+ LEGACY_EXPORT_PROJECT_CUTOFF,type BlobStorageIntegration,type ExportSourceContext,} from "@langfuse/shared";@@ -20,7 +20,7 @@ const exportSourceCtx: ExportSourceContext = {isCloud: true,enrichedAvailable: true,legacyWritesActive: true,- projectCreatedAt: new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() + 1),+ projectCreatedAt: new Date(LEGACY_EXPORT_PROJECT_CUTOFF.getTime() + 1),integrationCreatedAt: null,};diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex 115a354393..2d33f07d6f 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -3,13 +3,11 @@ import {BlobStorageExportMode,BlobStorageIntegrationType,InvalidRequestError,- AnalyticsIntegrationExportSource,- areEnrichedWritesActive,- areLegacyWritesActive,- validateExportSource,+ type AnalyticsIntegrationExportSource,BlobStorageIntegrationFileType,type ObservationFieldGroupFull,} from "@langfuse/shared";+import { assertPersistedExportSourceAllowed } from "@/src/features/analytics-integrations/server/exportSource";import { encrypt } from "@langfuse/shared/encryption";import { env } from "@/src/env.mjs";import { validateBlobStorageEndpoint } from "@langfuse/shared/src/server";@@ -58,17 +56,11 @@ export async function upsertBlobStorageIntegration(params: {prisma: PrismaClient;projectId: string;data: UpsertBlobStorageIntegrationInput;- // When true and no existing row is found inside the transaction, the CREATE- // branch uses EVENTS instead of the Prisma column default (TRACES_OBSERVATIONS).- // Evaluated inside the transaction so the row-state check and the INSERT are- // atomic β no TOCTOU window.- forceEventsOnCreate?: boolean;- // When true and no existing row is found inside the transaction, the CREATE- // branch refuses a legacy export source (throws). Evaluated in-transaction so- // a concurrent DELETE between the router's pre-flight read and this upsert- // cannot slip a new post-cutoff row in with a legacy source. Symmetric with- // forceEventsOnCreate; set by both the tRPC and REST paths on Cloud.- refuseLegacyOnCreate?: boolean;+ // The source a CREATE lands, already validated and resolved by the caller via+ // resolveExportSource. Always concrete, so the CREATE branch never falls+ // through to the Prisma column default (TRACES_OBSERVATIONS). An UPDATE keeps+ // using data.exportSource, where undefined preserves the persisted value.+ createExportSource: AnalyticsIntegrationExportSource;}) {const { prisma, projectId, data } = params;@@ -121,7 +113,14 @@ export async function upsertBlobStorageIntegration(params: {return prisma.$transaction(async (tx) => {const existing = await tx.blobStorageIntegration.findUnique({where: { projectId },- select: { exportMode: true, lastError: true, runStartedAt: true },+ // createdAt/exportSource feed the post-upsert backstop below.+ select: {+ exportMode: true,+ lastError: true,+ runStartedAt: true,+ createdAt: true,+ exportSource: true,+ },});// Require secret key for new integrations (unless using host credentials)@@ -138,31 +137,21 @@ export async function upsertBlobStorageIntegration(params: {const modeChanged = existing && existing.exportMode !== data.exportMode;const encryptedSecret = secretAccessKey ? encrypt(secretAccessKey) : null;- // exportSource for the CREATE payload. The !existing guard was previously- // here, but it created a residual TOCTOU: READ COMMITTED isolation means+ // The CREATE payload always carries a concrete source, resolved by the+ // caller through resolveExportSource. Applying it unconditionally (rather+ // than behind a `!existing` guard) closes a TOCTOU: under READ COMMITTED,// tx.findUnique and tx.upsert take independent snapshots, so a concurrent- // DELETE between the two could leave createExportSource = undefined and let+ // DELETE between the two could otherwise leave this undefined and let// Postgres apply the @default(TRACES_OBSERVATIONS) column default on INSERT.- // Dropping the guard is safe: ON CONFLICT atomically decides CREATE vs UPDATE- // 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 writeMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;- const legacyWritesActive = areLegacyWritesActive(writeMode);- const createExportSource =- data.exportSource ??- (params.forceEventsOnCreate || !legacyWritesActive- ? AnalyticsIntegrationExportSource.EVENTS- : undefined);-+ // ON CONFLICT decides CREATE vs UPDATE atomically regardless of what+ // findUnique saw, and UPDATE uses writeData.exportSource (undefined β Prisma+ // omits the column β preserves the existing value), so caller intent is+ // honored on both paths.const result = await tx.blobStorageIntegration.upsert({where: { projectId },create: {...writeData,- exportSource: createExportSource,+ exportSource: params.createExportSource,// Parquet is the default export format; apply it when the caller omits// fileType on CREATE. This app-level fallback (not the Prisma column// default) is the source of truth for the default across every write path.@@ -191,24 +180,15 @@ export async function upsertBlobStorageIntegration(params: {},});- // 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: areEnrichedWritesActive(writeMode),- legacyWritesActive,- integrationCreatedAt: params.refuseLegacyOnCreate- ? result.createdAt- : undefined,+ // Race-free backstop over the row that actually landed, shared with the+ // PostHog and Mixpanel routers. 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. Throwing here+ // rolls the transaction back. See export-source-policy.ts.+ assertPersistedExportSourceAllowed({+ existingIntegration: existing,+ result,});- 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 f4a537464c..d498130c93 100644--- a/web/src/features/mixpanel-integration/mixpanel-integration-router.ts+++ b/web/src/features/mixpanel-integration/mixpanel-integration-router.ts@@ -2,9 +2,9 @@ import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";import {- assertRacedCreateAllowed,- resolveAnalyticsExportSource,-} from "@/src/features/analytics-integrations/server/analyticsExportSource";+ assertPersistedExportSourceAllowed,+ resolveExportSource,+} from "@/src/features/analytics-integrations/server/exportSource";import { isPrismaRecordNotFoundError } from "@/src/features/analytics-integrations/server/isPrismaRecordNotFoundError";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {@@ -19,6 +19,7 @@ import { getDisplayCredential } from "@/src/features/analytics-integrations/servimport {AnalyticsIntegrationExportSource,LangfuseNotFoundError,+ LEGACY_ANALYTICS_EXPORTER_CUTOFF,} from "@langfuse/shared";export const mixpanelIntegrationRouter = createTRPCRouter({@@ -45,7 +46,7 @@ export const mixpanelIntegrationRouter = createTRPCRouter({const { encryptedMixpanelProjectToken, exportSource, ...config } =dbConfig;- // Write-only credential: never return the plaintext token (LFE-14384).+ // Write-only credential: never return the plaintext token (write-only credential).return {config: {...config,@@ -105,7 +106,7 @@ export const mixpanelIntegrationRouter = createTRPCRouter({});// Write-only credential: blank/omitted keeps the persisted encrypted- // value (LFE-14384).+ // value (write-only credential).const encryptedMixpanelProjectToken = input.mixpanelProjectToken? encrypt(input.mixpanelProjectToken): existingIntegration?.encryptedMixpanelProjectToken;@@ -115,11 +116,12 @@ export const mixpanelIntegrationRouter = createTRPCRouter({message: "Mixpanel Project Token is required",});}- const createExportSource = await resolveAnalyticsExportSource({+ const createExportSource = await resolveExportSource({db: ctx.prisma,projectId: input.projectId,requestedExportSource: input.exportSource,existingIntegration,+ exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,});await auditLog({@@ -147,16 +149,15 @@ export const mixpanelIntegrationRouter = createTRPCRouter({mixpanelRegion: config.mixpanelRegion,enabled: config.enabled,// undefined β Prisma omits the column β preserves the persisted- // value on partial updates (LFE-10296).+ // value on partial updates.exportSource: config.exportSource,},});- await assertRacedCreateAllowed({- tx,- projectId: input.projectId,+ assertPersistedExportSourceAllowed({existingIntegration,result,+ exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,});});}),diff --git a/web/src/features/posthog-integration/posthog-integration-router.ts b/web/src/features/posthog-integration/posthog-integration-router.tsindex c80afb1595..2ee62afdb1 100644--- a/web/src/features/posthog-integration/posthog-integration-router.ts+++ b/web/src/features/posthog-integration/posthog-integration-router.ts@@ -2,9 +2,9 @@ import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";import {- assertRacedCreateAllowed,- resolveAnalyticsExportSource,-} from "@/src/features/analytics-integrations/server/analyticsExportSource";+ assertPersistedExportSourceAllowed,+ resolveExportSource,+} from "@/src/features/analytics-integrations/server/exportSource";import { isPrismaRecordNotFoundError } from "@/src/features/analytics-integrations/server/isPrismaRecordNotFoundError";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {@@ -20,6 +20,7 @@ import { getDisplayCredential } from "@/src/features/analytics-integrations/servimport {AnalyticsIntegrationExportSource,LangfuseNotFoundError,+ LEGACY_ANALYTICS_EXPORTER_CUTOFF,} from "@langfuse/shared";export const posthogIntegrationRouter = createTRPCRouter({@@ -45,7 +46,7 @@ export const posthogIntegrationRouter = createTRPCRouter({const { encryptedPosthogApiKey, exportSource, ...config } = dbConfig;- // Write-only credential: never return the plaintext key (LFE-14384).+ // Write-only credential: never return the plaintext key (write-only credential).return {config: {...config,@@ -118,7 +119,7 @@ export const posthogIntegrationRouter = createTRPCRouter({});// Write-only credential: blank/omitted keeps the persisted encrypted- // value (LFE-14384).+ // value (write-only credential).const encryptedPosthogApiKey = input.posthogProjectApiKey? encrypt(input.posthogProjectApiKey): existingIntegration?.encryptedPosthogApiKey;@@ -128,11 +129,12 @@ export const posthogIntegrationRouter = createTRPCRouter({message: "PostHog Project API Key is required",});}- const createExportSource = await resolveAnalyticsExportSource({+ const createExportSource = await resolveExportSource({db: ctx.prisma,projectId: input.projectId,requestedExportSource: input.exportSource,existingIntegration,+ exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,});await auditLog({@@ -160,18 +162,17 @@ export const posthogIntegrationRouter = createTRPCRouter({posthogHostName: config.posthogHostname,enabled: config.enabled,// undefined β Prisma omits the column β preserves the persisted- // value on partial updates (LFE-10296).+ // value on partial updates.exportSource: config.exportSource,// lastError is deliberately left intact so the last fault stays// visible until a successful run clears it.},});- await assertRacedCreateAllowed({- tx,- projectId: input.projectId,+ assertPersistedExportSourceAllowed({existingIntegration,result,+ exporterCutoff: LEGACY_ANALYTICS_EXPORTER_CUTOFF,});});}),diff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex 7bbf8fc8d8..435ee13838 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -17,13 +17,8 @@ import {ForbiddenError,} from "@langfuse/shared";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";-import { assertExportSourceAllowed } from "@/src/features/analytics-integrations/server/assertExportSourceAllowed";-import {- areEnrichedWritesActive,- areLegacyWritesActive,-} from "@langfuse/shared";+import { resolveExportSource } from "@/src/features/analytics-integrations/server/exportSource";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { env } from "@/src/env.mjs";export default withMiddlewares({GET: handleGetBlobStorageIntegrations,@@ -160,8 +155,6 @@ async function handleUpsertBlobStorageIntegration(throw new LangfuseNotFoundError("Project not found");}- const isCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);-const internalExportSource =validatedData.exportSource != null? toInternalExportSource(validatedData.exportSource)@@ -177,21 +170,17 @@ async function handleUpsertBlobStorageIntegration(});// 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,- enrichedAvailable: areEnrichedWritesActive(- env.LANGFUSE_MIGRATION_V4_WRITE_MODE,- ),- legacyWritesActive: areLegacyWritesActive(- env.LANGFUSE_MIGRATION_V4_WRITE_MODE,- ),- projectCreatedAt: project.createdAt,- integrationCreatedAt: existingIntegration?.createdAt ?? null,- },+ // persisted one, capability-checked only, and a create falls back to the+ // shared default. Same call the tRPC routers make, so a PUT and a settings+ // save agree. See export-source-policy.ts.+ const createExportSource = await resolveExportSource({+ db: prisma,+ projectId: validatedData.projectId,+ // Already loaded above for the org-ownership check; reuse it rather than+ // making the helper re-read the same row.+ projectCreatedAt: project.createdAt,+ requestedExportSource: internalExportSource,+ existingIntegration,});await auditLog({@@ -205,14 +194,7 @@ async function handleUpsertBlobStorageIntegration(const integration = await upsertBlobStorageIntegration({prisma,projectId: validatedData.projectId,- // New Cloud rows default to EVENTS when exportSource is omitted: a- // brand-new row is post-cutoff, so the legacy column default would trip- // refuseLegacyOnCreate and fail a partial PUT that never mentioned- // exportSource. Substituted in-transaction to avoid a TOCTOU window.- forceEventsOnCreate: validatedData.exportSource == null && isCloud,- // In-transaction backstop: a concurrent DELETE can flip this upsert to- // CREATE; never let a new Cloud row be born with a legacy source.- refuseLegacyOnCreate: isCloud,+ createExportSource,data: {type: validatedData.type,bucketName: validatedData.bucketName,diff --git a/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsx b/web/src/pages/project/[projectId]/settings/integrations/mixpanel.tsxindex d0b484344e..63e042066b 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 {LEGACY_ANALYTICS_EXPORTER_CUTOFF,validateExportSource,- type BlobExportWriteMode,+ type V4WriteMode,type ExportSourceContext,} from "@langfuse/shared";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";@@ -163,7 +163,7 @@ const MixpanelIntegrationSettingsForm = ({}: {state?: NonNullable<RouterOutput["mixpanelIntegration"]["get"]["config"]>;projectId: string;- writeMode: BlobExportWriteMode;+ writeMode: V4WriteMode;// Raw ISO string, not a Date: a Date built in the parent's JSX would be a new// reference on every render and would defeat the memo below.projectCreatedAt: string;@@ -190,12 +190,12 @@ const MixpanelIntegrationSettingsForm = ({defaultValue: defaultExportSource,} = getExportSourceFieldState(state?.exportSource, exportSourceCtx);- // Blocked-save validation instead of silent rewrite (LFE-10296).+ // Blocked-save validation instead of silent rewrite.const formSchema = useMemo(() =>mixpanelIntegrationFormSchema.superRefine((data, ctx) => {// The credential is write-only: blank keeps the saved token, so it is- // only required when no integration exists yet (LFE-14384).+ // only required when no integration exists yet.if (!state && !data.mixpanelProjectToken) {ctx.addIssue({code: "custom",diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsxindex d4f2660e7d..1c45b2b64b 100644--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx@@ -33,7 +33,7 @@ import { PostHogStatusSection } from "@/src/features/posthog-integration/componeimport {LEGACY_ANALYTICS_EXPORTER_CUTOFF,validateExportSource,- type BlobExportWriteMode,+ type V4WriteMode,type ExportSourceContext,} from "@langfuse/shared";import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";@@ -157,7 +157,7 @@ const PostHogIntegrationSettings = ({}: {state?: NonNullable<RouterOutput["posthogIntegration"]["get"]["config"]>;projectId: string;- writeMode: BlobExportWriteMode;+ writeMode: V4WriteMode;// Raw ISO string, not a Date: a Date built in the parent's JSX would be a new// reference on every render and would defeat the memo below.projectCreatedAt: string;@@ -184,12 +184,12 @@ const PostHogIntegrationSettings = ({defaultValue: defaultExportSource,} = getExportSourceFieldState(state?.exportSource, exportSourceCtx);- // Blocked-save validation instead of silent rewrite (LFE-10296).+ // Blocked-save validation instead of silent rewrite.const formSchema = useMemo(() =>posthogIntegrationFormSchema.superRefine((data, ctx) => {// The credential is write-only: blank keeps the saved key, so it is- // only required when no integration exists yet (LFE-14384).+ // only required when no integration exists yet.if (!state && !data.posthogProjectApiKey) {ctx.addIssue({code: "custom",diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex 2596a44582..dc1ef5506e 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -60,8 +60,8 @@ import {BlobStorageExportMode,OBSERVATION_FIELD_GROUPS_FULL,type ObservationFieldGroupFull,- isLegacyBlobExportSource,- isLegacyBlobExporter,+ isLegacyExportSource,+ isLegacyExporter,resolveBlobExportTuning,DEFAULT_BLOB_EXPORT_PART_SIZE_BYTES,} from "@langfuse/shared";@@ -91,7 +91,7 @@ export const BlobExportFormat = {CSV_GZIP: "csv-gzip",JSONL_RAW: "jsonl-raw",JSONL_GZIP: "jsonl-gzip",- // LFE-10463: ClickHouse-native columnar export; compression is internal to+ // ClickHouse-native columnar export; compression is internal to// Parquet, so there is no separate raw/gzip split.PARQUET: "parquet",} as const;@@ -430,7 +430,7 @@ const processBlobStorageExport = async (config: {span.setAttribute("blob.config.rawPassthrough", config.rawPassthrough);// Event-loop delay during the stream: if it spikes, lock renewal can't- // fire and the job re-enqueues as stalled (LFE-10063). Torn down below.+ // fire and the job re-enqueues as stalled. Torn down below.const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });eventLoopDelay.enable();@@ -464,7 +464,7 @@ const processBlobStorageExport = async (config: {const parquetEligible =config.fileType === BlobStorageIntegrationFileType.PARQUET;- // Raw passthrough (LFE-10402) is opt-in per project and only valid for+ // Raw passthrough is opt-in per project and only valid for// JSONL output of the enriched-observation tables β the only formats// where ClickHouse FORMAT JSONEachRow bytes map 1:1 to the file. Any// other request falls back to the standard path. The integration-level@@ -566,7 +566,7 @@ const processBlobStorageExport = async (config: {let fileStream: Readable;if (parquetEligible) {- // LFE-10463: stream raw FORMAT Parquet bytes straight to upload β no JS+ // Stream raw FORMAT Parquet bytes straight to upload β no JS// parse/enrich/serialize, no gzip, no row counting (binary has no row// boundaries, so sourceStats.rows stays 0). Field-group projection,// latency msβs, and dropped price columns are baked into the SQL. The@@ -1104,7 +1104,7 @@ const writeBlobExportManifest = async (params: {);};-// LFE-10896: drop a plain-text deprecation notice into the export destination+// Drop a plain-text deprecation notice into the export destination// for legacy-source projects. Best-effort β a failure to write the notice must// not fail the export run, so it is called after the manifest commit point and// swallows its own error.@@ -1265,7 +1265,7 @@ export const handleBlobStorageIntegrationProjectJob = async (return;}- // Legacy-source deprecation is a Cloud policy (isLegacyBlobExporter exempts+ // Legacy-source deprecation is a Cloud policy (isLegacyExporter exempts// self-hosted), so the deprecation notice below is Cloud-only too.const isCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);@@ -1429,7 +1429,7 @@ export const handleBlobStorageIntegrationProjectJob = async (// Cloud-only v3-deprecation notice; both sides best-effort (never fail the run).if (isCloud) {- if (isLegacyBlobExportSource(blobStorageIntegration.exportSource)) {+ if (isLegacyExportSource(blobStorageIntegration.exportSource)) {await writeBlobExportDeprecationNotice({storageService,prefix: blobStorageIntegration.prefix || undefined,@@ -1439,7 +1439,7 @@ export const handleBlobStorageIntegrationProjectJob = async (// Gate cleanup on "old enough to have written a notice": otherwise every// enriched-only export adds a needless per-run s3:DeleteObject on the// destination, which is write-only for many customers.- isLegacyBlobExporter(blobStorageIntegration.createdAt, isCloud)+ isLegacyExporter(blobStorageIntegration.createdAt, isCloud)) {await removeBlobExportDeprecationNotice({storageService,