Skip to content

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

fix(worker): route analytics score-export trace enrichment by v4 write mode (LFE-11009) (#15298)

Niklas Semmler38d2c5b45fc4
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index a9944c97b3..94a37e96fc 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -3219,7 +3219,8 @@ export const getEventsForAnalyticsIntegrations = async function* (
const records = queryClickhouseStream<Record<string, unknown>>({
query,
params,
- tags: { projectId },
+ // Tagged explicitly: worker baggage isn't active during the deferred stream send.
+ tags: { projectId, surface: "worker", route: "analytics_integration" },
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
},
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 7bc37ad8a3..fe6f95b1be 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1885,7 +1885,8 @@ export const getGenerationsForAnalyticsIntegrations = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
- tags: { projectId },
+ // Tagged explicitly: worker baggage isn't active during the deferred stream send.
+ tags: { projectId, surface: "worker", route: "analytics_integration" },
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
...(options.useGraceHash
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 016710cb30..415b4f4fa4 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -11,6 +11,7 @@ import {
ScoreDataTypeEnum,
} from "../../domain/scores";
import { InvalidRequestError, InternalServerError } from "../../errors";
+import { eventsTableIsRootObservationSql } from "../../eventsTable";
import type { APIScoreV3 } from "../../features/scores/interfaces/api/v3/schemas";
import type { ScoreFieldGroupV3 } from "../../features/scores/interfaces/api/v3/endpoints";
import { filterAndValidateV3GetScoreList } from "../../features/scores/interfaces/api/v3/validation";
@@ -2415,18 +2416,73 @@ const buildAnalyticsScoreTraceAttributesCte = (
},
});
+// Same schema rebuilt from events_core for deployments that no longer write
+// the legacy traces table (write mode events_only). The 7d start_time
+// lookback mirrors the legacy CTE so delayed scores stay enriched.
+//
+// Hand-written rather than eventsTracesAggregation: aggregating only
+// root-span rows keeps the GROUP BY state ~one row per trace (the full-span
+// aggregation OOMed the largest tenants), and the field expressions carry
+// the parity fixes byte-verified against prod dual-write data in the
+// LFE-14383 benchmark — NULL semantics via nullIf, trace-name fallback
+// strictly from parent_span_id = '' rows, tags as sorted union across
+// writes, release latest-write-wins, metadata keys via indexOf instead of
+// per-row map construction. eventsTracesAggregation lacks all five
+// (tracked in LFE-11009).
+const buildAnalyticsScoreTraceAttributesFromEventsCte = (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+): { query: string; params: Record<string, unknown> } => ({
+ query: `
+ SELECT
+ e.project_id as project_id,
+ e.trace_id as id,
+ coalesce(nullIf(argMaxIf(e.trace_name, e.event_ts, e.trace_name <> ''), ''), nullIf(argMaxIf(e.name, e.event_ts, e.parent_span_id = '' AND e.name <> ''), ''), '') as name,
+ nullIf(argMaxIf(e.session_id, e.event_ts, e.session_id <> ''), '') as session_id,
+ nullIf(argMaxIf(e.user_id, e.event_ts, e.user_id <> ''), '') as user_id,
+ nullIf(argMax(e.release, e.event_ts), '') as release,
+ arraySort(groupUniqArrayArrayIf(e.tags, notEmpty(e.tags))) as tags,
+ argMax(e.metadata_values[indexOf(e.metadata_names, '$posthog_session_id')], e.event_ts) as posthog_session_id,
+ argMax(e.metadata_values[indexOf(e.metadata_names, '$mixpanel_session_id')], e.event_ts) as mixpanel_session_id
+ FROM events_core e
+ WHERE e.project_id = {projectId: String}
+ AND e.start_time >= {minTimestamp: DateTime64(3)} - INTERVAL 7 DAY
+ AND e.start_time <= {maxTimestamp: DateTime64(3)}
+ AND e.is_deleted = 0
+ AND ${eventsTableIsRootObservationSql}
+ GROUP BY e.project_id, e.trace_id`,
+ params: {
+ projectId,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+});
+
export const getScoresForAnalyticsIntegrations = async function* (
projectId: string,
projectName: string,
minTimestamp: Date,
maxTimestamp: Date,
- options: { useGraceHash?: boolean } = {},
+ options: {
+ useGraceHash?: boolean;
+ /** Pass "events" when the deployment no longer writes the traces table. */
+ traceAttributesSource?: "traces" | "events";
+ } = {},
) {
- const selectedTraces = buildAnalyticsScoreTraceAttributesCte(
- projectId,
- minTimestamp,
- maxTimestamp,
- );
+ const traceAttributesSource = options.traceAttributesSource ?? "traces";
+ const selectedTraces =
+ traceAttributesSource === "events"
+ ? buildAnalyticsScoreTraceAttributesFromEventsCte(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ )
+ : buildAnalyticsScoreTraceAttributesCte(
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ );
const query = `
WITH selected_traces AS (${selectedTraces.query}
@@ -2473,9 +2529,12 @@ export const getScoresForAnalyticsIntegrations = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
dataTypes: LISTABLE_SCORE_TYPES,
- ...selectedTraces.params,
},
- tags: { projectId },
+ // Tagged explicitly: worker baggage isn't active during the deferred stream send.
+ tags: { projectId, surface: "worker", route: "analytics_integration" },
+ ...(traceAttributesSource === "events"
+ ? { preferredClickhouseService: "EventsReadOnly" as const }
+ : {}),
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
...(options.useGraceHash
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 68c8b02299..e5793ec531 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1427,7 +1427,8 @@ export const getTracesForAnalyticsIntegrations = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
- tags: { projectId },
+ // Tagged explicitly: worker baggage isn't active during the deferred stream send.
+ tags: { projectId, surface: "worker", route: "analytics_integration" },
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
...(options.useGraceHash
diff --git a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
index 6b7b2e31b2..dc1a6ef15d 100644
--- a/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
+++ b/worker/src/__tests__/mixpanelIntegrationProjectJob.test.ts
@@ -94,13 +94,17 @@ vi.mock("@langfuse/shared/encryption", () => ({
}));
// Keep the throttle delay out of the unit test (real value defaults to 500ms).
-// Path is relative to this test file -> resolves to worker/src/env (also the
-// module the exportWriteModeGuard reads its write mode from).
+// Resolves to worker/src/env (read by exportWriteModeGuard and the score
+// routing); the helpers mirror the real implementations.
vi.mock("../env", () => ({
env: {
LANGFUSE_MIXPANEL_FLUSH_DELAY_MS: 0,
- LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy",
+ LANGFUSE_MIGRATION_V4_WRITE_MODE: "dual",
},
+ v4WritesToLegacyTables: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>
+ e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only",
+ v4WritesToEventsTable: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>
+ e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy",
}));
vi.mock("@langfuse/shared/src/db", () => ({
@@ -127,6 +131,7 @@ vi.mock("@langfuse/shared/src/server", () => ({
// Import after mocks are registered.
import { handleMixpanelIntegrationProjectJob } from "../features/mixpanel/handleMixpanelIntegrationProjectJob";
+import { getScoresForAnalyticsIntegrations } from "@langfuse/shared/src/server";
import { env } from "../env";
function makeJob() {
@@ -144,7 +149,8 @@ describe("handleMixpanelIntegrationProjectJob throttling (issue #12786)", () =>
h.state.maxConcurrentStreams = 0;
h.mixpanelIntegrationUpdate.mockClear();
h.db.integration = h.defaultIntegration();
- (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";
+ // dual: the only mode where TRACES_OBSERVATIONS_EVENTS passes the guard
+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
});
it("reuses a single MixpanelClient for the whole job", async () => {
@@ -174,7 +180,7 @@ describe("handleMixpanelIntegrationProjectJob events_only legacy guard (LFE-1014
h.timeline.length = 0;
h.mixpanelIntegrationUpdate.mockClear();
h.db.integration = h.defaultIntegration();
- (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";
+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
});
it("throws before export and does not advance lastSyncAt on events_only + legacy source", async () => {
@@ -194,7 +200,7 @@ describe("handleMixpanelIntegrationProjectJob events_only legacy guard (LFE-1014
expect(h.mixpanelIntegrationUpdate).not.toHaveBeenCalled();
});
- it("exports an EVENTS source normally on events_only", async () => {
+ it("exports an EVENTS source normally on events_only, routing score enrichment to events", async () => {
(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";
h.db.integration = {
...h.defaultIntegration(),
@@ -203,6 +209,61 @@ describe("handleMixpanelIntegrationProjectJob events_only legacy guard (LFE-1014
await handleMixpanelIntegrationProjectJob(makeJob());
+ expect(h.mixpanelIntegrationUpdate).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(getScoresForAnalyticsIntegrations)).toHaveBeenCalledWith(
+ "project-1",
+ "Test Project",
+ expect.any(Date),
+ expect.any(Date),
+ expect.objectContaining({ traceAttributesSource: "events" }),
+ );
+ });
+
+ it("enriches scores from traces on dual write mode", async () => {
+ await handleMixpanelIntegrationProjectJob(makeJob());
+
+ expect(vi.mocked(getScoresForAnalyticsIntegrations)).toHaveBeenCalledWith(
+ "project-1",
+ "Test Project",
+ expect.any(Date),
+ expect.any(Date),
+ expect.objectContaining({ traceAttributesSource: "traces" }),
+ );
+ });
+});
+
+// LFE-11009: enriched sources on legacy write mode must fail loudly instead
+// of silently exporting empty data while lastSyncAt advances.
+describe("handleMixpanelIntegrationProjectJob legacy-mode enriched guard (LFE-11009)", () => {
+ beforeEach(() => {
+ h.timeline.length = 0;
+ h.mixpanelIntegrationUpdate.mockClear();
+ h.db.integration = h.defaultIntegration();
+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";
+ });
+
+ it.each(["EVENTS", "TRACES_OBSERVATIONS_EVENTS"])(
+ "throws before export and does not advance lastSyncAt on legacy + %s source",
+ async (exportSource) => {
+ h.db.integration = { ...h.defaultIntegration(), exportSource };
+
+ await expect(
+ handleMixpanelIntegrationProjectJob(makeJob()),
+ ).rejects.toThrow(/does not write them/);
+
+ expect(h.timeline).toHaveLength(0);
+ expect(h.mixpanelIntegrationUpdate).not.toHaveBeenCalled();
+ },
+ );
+
+ it("exports a TRACES_OBSERVATIONS source normally on legacy write mode", async () => {
+ h.db.integration = {
+ ...h.defaultIntegration(),
+ exportSource: "TRACES_OBSERVATIONS",
+ };
+
+ await handleMixpanelIntegrationProjectJob(makeJob());
+
expect(h.mixpanelIntegrationUpdate).toHaveBeenCalledTimes(1);
});
});
diff --git a/worker/src/__tests__/posthogIntegrationProjectJob.test.ts b/worker/src/__tests__/posthogIntegrationProjectJob.test.ts
index 081c749dc2..52507fbefd 100644
--- a/worker/src/__tests__/posthogIntegrationProjectJob.test.ts
+++ b/worker/src/__tests__/posthogIntegrationProjectJob.test.ts
@@ -87,10 +87,14 @@ vi.mock("posthog-node", () => ({
},
}));
-// Path is relative to this test file -> resolves to worker/src/env (the
-// module the exportWriteModeGuard reads its write mode from).
+// Resolves to worker/src/env (read by exportWriteModeGuard and the score
+// routing); the helpers mirror the real implementations.
vi.mock("../env", () => ({
env: { LANGFUSE_MIGRATION_V4_WRITE_MODE: "legacy" },
+ v4WritesToLegacyTables: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>
+ e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only",
+ v4WritesToEventsTable: (e: { LANGFUSE_MIGRATION_V4_WRITE_MODE: string }) =>
+ e.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy",
}));
// Import after mocks are registered.
@@ -135,7 +139,7 @@ describe("handlePostHogIntegrationProjectJob events_only legacy guard (LFE-10148
expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();
});
- it("exports an EVENTS source normally on events_only", async () => {
+ it("exports an EVENTS source normally on events_only, routing score enrichment to events", async () => {
(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";
h.db.integration = {
...h.defaultIntegration(),
@@ -147,14 +151,67 @@ describe("handlePostHogIntegrationProjectJob events_only legacy guard (LFE-10148
expect(h.getEvents).toHaveBeenCalledTimes(1);
expect(h.getTraces).not.toHaveBeenCalled();
expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);
+ expect(h.getScores).toHaveBeenCalledWith(
+ "project-1",
+ "Test Project",
+ expect.any(Date),
+ expect.any(Date),
+ expect.objectContaining({ traceAttributesSource: "events" }),
+ );
});
- it("exports a legacy source normally on dual write mode", async () => {
+ it("exports a legacy source normally on dual write mode, enriching scores from traces", async () => {
(env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
await handlePostHogIntegrationProjectJob(makeJob());
expect(h.getTraces).toHaveBeenCalledTimes(1);
expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);
+ expect(h.getScores).toHaveBeenCalledWith(
+ "project-1",
+ "Test Project",
+ expect.any(Date),
+ expect.any(Date),
+ expect.objectContaining({ traceAttributesSource: "traces" }),
+ );
+ });
+});
+
+// LFE-11009: enriched sources on legacy write mode must fail loudly instead
+// of silently exporting empty data while lastSyncAt advances.
+describe("handlePostHogIntegrationProjectJob legacy-mode enriched guard (LFE-11009)", () => {
+ beforeEach(() => {
+ h.posthogIntegrationUpdate.mockClear();
+ h.getTraces.mockClear();
+ h.getGenerations.mockClear();
+ h.getScores.mockClear();
+ h.getEvents.mockClear();
+ h.db.integration = h.defaultIntegration();
+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";
+ });
+
+ it.each(["EVENTS", "TRACES_OBSERVATIONS_EVENTS"])(
+ "throws before export and does not advance lastSyncAt on legacy + %s source",
+ async (exportSource) => {
+ h.db.integration = { ...h.defaultIntegration(), exportSource };
+
+ await expect(
+ handlePostHogIntegrationProjectJob(makeJob()),
+ ).rejects.toThrow(/does not write them/);
+
+ expect(h.getScores).not.toHaveBeenCalled();
+ expect(h.getEvents).not.toHaveBeenCalled();
+ expect(h.posthogIntegrationUpdate).not.toHaveBeenCalled();
+ },
+ );
+
+ it("exports an EVENTS source normally on dual write mode", async () => {
+ (env as any).LANGFUSE_MIGRATION_V4_WRITE_MODE = "dual";
+ h.db.integration = { ...h.defaultIntegration(), exportSource: "EVENTS" };
+
+ await handlePostHogIntegrationProjectJob(makeJob());
+
+ expect(h.getEvents).toHaveBeenCalledTimes(1);
+ expect(h.posthogIntegrationUpdate).toHaveBeenCalledTimes(1);
});
});
diff --git a/worker/src/__tests__/scoresAnalyticsIntegrationEnrichment.test.ts b/worker/src/__tests__/scoresAnalyticsIntegrationEnrichment.test.ts
new file mode 100644
index 0000000000..b30e987aa2
--- /dev/null
+++ b/worker/src/__tests__/scoresAnalyticsIntegrationEnrichment.test.ts
@@ -0,0 +1,334 @@
+import { randomUUID } from "crypto";
+import { describe, expect, it } from "vitest";
+import {
+ createEvent,
+ createEventsCh,
+ createScoresCh,
+ createTrace,
+ createTracesCh,
+ createTraceScore,
+ getScoresForAnalyticsIntegrations,
+} from "@langfuse/shared/src/server";
+
+// LFE-11009: score-export trace enrichment must work from both the legacy
+// traces table and the events table, with matching 7d-lookback semantics.
+
+// Events tables only exist when the deployment opts into the V4 preview.
+const maybeDescribe =
+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true"
+ ? describe
+ : describe.skip;
+
+const HOUR_MS = 60 * 60 * 1000;
+const DAY_MS = 24 * HOUR_MS;
+
+type TraceAttributes = {
+ name: string;
+ userId: string;
+ sessionId: string;
+ release: string;
+ tags: string[];
+ posthogSessionId: string;
+ mixpanelSessionId: string;
+};
+
+const makeAttributes = (suffix: string): TraceAttributes => ({
+ name: `trace-${suffix}`,
+ userId: `user-${suffix}`,
+ sessionId: `session-${suffix}`,
+ release: `release-${suffix}`,
+ tags: [`tag-a-${suffix}`, `tag-b-${suffix}`],
+ posthogSessionId: `ph-${suffix}`,
+ mixpanelSessionId: `mp-${suffix}`,
+});
+
+const seedTraceRow = (
+ projectId: string,
+ traceId: string,
+ timestamp: number,
+ attrs: TraceAttributes,
+) =>
+ createTrace({
+ project_id: projectId,
+ id: traceId,
+ timestamp,
+ name: attrs.name,
+ user_id: attrs.userId,
+ session_id: attrs.sessionId,
+ release: attrs.release,
+ tags: attrs.tags,
+ metadata: {
+ $posthog_session_id: attrs.posthogSessionId,
+ $mixpanel_session_id: attrs.mixpanelSessionId,
+ },
+ });
+
+// The events aggregation reads metadata from the root span (parent_span_id = '').
+const seedRootEvent = (
+ projectId: string,
+ traceId: string,
+ timestampMs: number,
+ attrs: TraceAttributes,
+) =>
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ parent_span_id: "",
+ is_app_root: true,
+ type: "SPAN",
+ trace_name: attrs.name,
+ user_id: attrs.userId,
+ session_id: attrs.sessionId,
+ release: attrs.release,
+ tags: attrs.tags,
+ metadata_names: ["$mixpanel_session_id", "$posthog_session_id"],
+ metadata_values: [attrs.mixpanelSessionId, attrs.posthogSessionId],
+ start_time: timestampMs * 1000,
+ end_time: timestampMs * 1000,
+ event_ts: timestampMs * 1000,
+ created_at: timestampMs * 1000,
+ updated_at: timestampMs * 1000,
+ });
+
+const collect = async (
+ generator: ReturnType<typeof getScoresForAnalyticsIntegrations>,
+) => {
+ const rows = [];
+ for await (const row of generator) {
+ rows.push(row);
+ }
+ return rows;
+};
+
+const expectEnriched = (
+ row: Record<string, unknown>,
+ attrs: TraceAttributes,
+) => {
+ expect(row.langfuse_trace_name).toBe(attrs.name);
+ expect(row.langfuse_user_id).toBe(attrs.userId);
+ expect(row.langfuse_session_id).toBe(attrs.sessionId);
+ expect(row.langfuse_release).toBe(attrs.release);
+ expect(row.langfuse_tags).toEqual(attrs.tags);
+ expect(row.posthog_session_id).toBe(attrs.posthogSessionId);
+ expect(row.mixpanel_session_id).toBe(attrs.mixpanelSessionId);
+};
+
+const expectUnenriched = (row: Record<string, unknown>) => {
+ expect(row.langfuse_trace_name).toBeFalsy();
+ expect(row.langfuse_user_id).toBeNull();
+ expect(row.langfuse_release).toBeFalsy();
+ expect(row.posthog_session_id).toBeFalsy();
+ expect(row.mixpanel_session_id).toBeFalsy();
+};
+
+maybeDescribe(
+ "getScoresForAnalyticsIntegrations trace enrichment (LFE-11009)",
+ () => {
+ it("enriches from traces and events sources with identical 7d-lookback semantics", async () => {
+ const projectId = randomUUID();
+ const now = Date.now();
+ const minTimestamp = new Date(now - 1 * HOUR_MS);
+ const maxTimestamp = new Date(now + 1 * HOUR_MS);
+
+ // older than the sync window, within the 7d lookback (delayed score)
+ const recent = { id: randomUUID(), ts: now - 2 * HOUR_MS };
+ const recentAttrs = makeAttributes("recent");
+ // days old, still within the lookback
+ const midAge = { id: randomUUID(), ts: now - 3 * DAY_MS };
+ const midAgeAttrs = makeAttributes("mid");
+ // outside the lookback: unenriched today on the legacy path; the events
+ // path must match, not widen the window
+ const ancient = { id: randomUUID(), ts: now - 10 * DAY_MS };
+ const ancientAttrs = makeAttributes("ancient");
+
+ await createTracesCh([
+ seedTraceRow(projectId, recent.id, recent.ts, recentAttrs),
+ seedTraceRow(projectId, midAge.id, midAge.ts, midAgeAttrs),
+ seedTraceRow(projectId, ancient.id, ancient.ts, ancientAttrs),
+ ]);
+ await createEventsCh([
+ seedRootEvent(projectId, recent.id, recent.ts, recentAttrs),
+ seedRootEvent(projectId, midAge.id, midAge.ts, midAgeAttrs),
+ seedRootEvent(projectId, ancient.id, ancient.ts, ancientAttrs),
+ ]);
+ await createScoresCh(
+ [recent, midAge, ancient].map((trace) =>
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ timestamp: now,
+ }),
+ ),
+ );
+
+ for (const source of ["traces", "events"] as const) {
+ const rows = await collect(
+ getScoresForAnalyticsIntegrations(
+ projectId,
+ "Test Project",
+ minTimestamp,
+ maxTimestamp,
+ { traceAttributesSource: source },
+ ),
+ );
+ expect(rows, `source=${source}`).toHaveLength(3);
+
+ const byTraceId = new Map(rows.map((r) => [r.langfuse_trace_id, r]));
+ expectEnriched(byTraceId.get(recent.id)!, recentAttrs);
+ expectEnriched(byTraceId.get(midAge.id)!, midAgeAttrs);
+ expectUnenriched(byTraceId.get(ancient.id)!);
+ }
+ });
+
+ it("enriches from events when no traces rows exist (events_only deployment data)", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const now = Date.now();
+ const attrs = makeAttributes("events-only");
+
+ await createEventsCh([
+ seedRootEvent(projectId, traceId, now - 2 * HOUR_MS, attrs),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ timestamp: now,
+ }),
+ ]);
+
+ const minTimestamp = new Date(now - 1 * HOUR_MS);
+ const maxTimestamp = new Date(now + 1 * HOUR_MS);
+
+ const fromEvents = await collect(
+ getScoresForAnalyticsIntegrations(
+ projectId,
+ "Test Project",
+ minTimestamp,
+ maxTimestamp,
+ { traceAttributesSource: "events" },
+ ),
+ );
+ expect(fromEvents).toHaveLength(1);
+ expectEnriched(fromEvents[0], attrs);
+
+ // the silent-null gap this routing fixes
+ const fromTraces = await collect(
+ getScoresForAnalyticsIntegrations(
+ projectId,
+ "Test Project",
+ minTimestamp,
+ maxTimestamp,
+ { traceAttributesSource: "traces" },
+ ),
+ );
+ expect(fromTraces).toHaveLength(1);
+ expectUnenriched(fromTraces[0]);
+ });
+
+ // Parity fixes from the LFE-14383 benchmark, byte-verified against prod
+ // dual-write data. Both cases fail on the eventsTracesAggregation field
+ // expressions (no root-name fallback; latest-write-only tags).
+
+ it("falls back to the root span's own name when no explicit trace name exists", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const now = Date.now();
+
+ await createEventsCh([
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ parent_span_id: "",
+ type: "SPAN",
+ name: "root-span-name",
+ trace_name: null,
+ user_id: "user-1",
+ session_id: null,
+ release: null,
+ tags: [],
+ metadata_names: [],
+ metadata_values: [],
+ start_time: (now - 2 * HOUR_MS) * 1000,
+ event_ts: (now - 2 * HOUR_MS) * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ timestamp: now,
+ }),
+ ]);
+
+ const rows = await collect(
+ getScoresForAnalyticsIntegrations(
+ projectId,
+ "Test Project",
+ new Date(now - 1 * HOUR_MS),
+ new Date(now + 1 * HOUR_MS),
+ { traceAttributesSource: "events" },
+ ),
+ );
+
+ expect(rows).toHaveLength(1);
+ // Legacy parity: the traces upsert derives the trace name from the root
+ // span when no explicit trace name was set; absent attributes stay null.
+ expect(rows[0].langfuse_trace_name).toBe("root-span-name");
+ expect(rows[0].langfuse_user_id).toBe("user-1");
+ expect(rows[0].langfuse_release).toBeNull();
+ });
+
+ it("unions tags across trace writes, sorted, like the legacy traces upsert", async () => {
+ const projectId = randomUUID();
+ const traceId = randomUUID();
+ const now = Date.now();
+
+ // two coexisting root-qualifying rows with disjoint tag sets (same
+ // span_id would be a ReplacingMergeTree version and could collapse)
+ await createEventsCh([
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ parent_span_id: "",
+ type: "SPAN",
+ trace_name: "tagged-trace",
+ tags: ["zulu", "alpha"],
+ start_time: (now - 2 * HOUR_MS) * 1000,
+ event_ts: (now - 2 * HOUR_MS) * 1000,
+ }),
+ createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ parent_span_id: "external-parent",
+ is_app_root: true,
+ type: "SPAN",
+ trace_name: "tagged-trace",
+ tags: ["mike"],
+ start_time: (now - 2 * HOUR_MS) * 1000,
+ event_ts: (now - 1 * HOUR_MS) * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ timestamp: now,
+ }),
+ ]);
+
+ const rows = await collect(
+ getScoresForAnalyticsIntegrations(
+ projectId,
+ "Test Project",
+ new Date(now - 1 * HOUR_MS),
+ new Date(now + 1 * HOUR_MS),
+ { traceAttributesSource: "events" },
+ ),
+ );
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].langfuse_tags).toEqual(["alpha", "mike", "zulu"]);
+ });
+ },
+);
diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
index 50a73ddcb9..15fa90ab26 100644
--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -72,7 +72,7 @@ import { env as sharedEnv } from "@langfuse/shared/src/env";
import { randomUUID } from "crypto";
import { SpanKind } from "@opentelemetry/api";
import { env, v4AllowPreviewOptIn } from "../../env";
-import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";
+import { assertExportSourceWritable } from "../exportWriteModeGuard";
import { recordExportVolume } from "../../services/exportVolumeMetric";
import {
buildBlobExportManifest,
@@ -1279,9 +1279,9 @@ export const handleBlobStorageIntegrationProjectJob = async (
);
}
- // Symmetric legacy-side guard (LFE-10148); the catch persists lastError
- // and notifies admins.
- assertLegacyExportSourceWritable(
+ // Write-mode guard, both directions (LFE-10148, LFE-11009); the catch
+ // persists lastError and notifies admins.
+ assertExportSourceWritable(
blobStorageIntegration.exportSource,
"Select the enriched export source (OBSERVATIONS_V2) in the blob storage integration settings.",
);
diff --git a/worker/src/features/exportWriteModeGuard.ts b/worker/src/features/exportWriteModeGuard.ts
index 4108c896f9..0d15956cb1 100644
--- a/worker/src/features/exportWriteModeGuard.ts
+++ b/worker/src/features/exportWriteModeGuard.ts
@@ -3,35 +3,37 @@ import {
validateExportSource,
type AnalyticsIntegrationExportSource,
} from "@langfuse/shared";
-import { env } from "../env";
+import { env, v4WritesToEventsTable } from "../env";
/**
- * Legacy-source write-mode guard for the export workers (blob storage,
- * PostHog, Mixpanel) — thin adapter over validateExportSource; policy and
- * rationale in export-source-policy.ts. Throws BEFORE any export work so each
- * handler's normal failure path (log + rethrow, BullMQ retry, and for blob
- * storage lastError persistence + admin notification) takes over instead of
- * silently exporting stale/empty data while sync state advances (LFE-10148).
- *
- * The env read lives here in worker code. `remediation` is the
- * operator-actionable closing sentence, per integration.
+ * Write-mode guard for the export workers (blob storage, PostHog, Mixpanel);
+ * policy in export-source-policy.ts. Throws BEFORE any export work so the
+ * handler's failure path takes over instead of silently exporting stale/empty
+ * data while sync state advances. Guards both directions: legacy sources on
+ * events_only (LFE-10148), enriched sources on legacy mode (LFE-11009).
+ * `legacyRemediation` is the per-integration closing sentence of the
+ * legacy-source error; the enriched error is integration-neutral (the fix is
+ * the write mode, not an integration setting).
*/
-export function assertLegacyExportSourceWritable(
+export function assertExportSourceWritable(
exportSource: AnalyticsIntegrationExportSource,
- remediation: string,
+ legacyRemediation: string,
): void {
const validation = validateExportSource(exportSource, {
- // Capability-only context: no dates → the Cloud cutoffs never fire here
- // (they gate writes, not running exports), and enriched availability has
- // its own dedicated worker guard.
+ // No dates: the Cloud cutoffs gate writes, not running exports.
isCloud: false,
- enrichedAvailable: true,
+ enrichedAvailable: v4WritesToEventsTable(env),
legacyWritesActive: areLegacyWritesActive(
env.LANGFUSE_MIGRATION_V4_WRITE_MODE,
),
});
if (validation.ok) return;
+ if (validation.reason === "enriched-unavailable") {
+ throw new Error(
+ "The configured export source reads the enriched events tables, but this deployment runs LANGFUSE_MIGRATION_V4_WRITE_MODE=legacy and does not write them. Set LANGFUSE_MIGRATION_V4_WRITE_MODE to dual or events_only, or select a legacy export source.",
+ );
+ }
throw new Error(
- `The configured export source reads the legacy traces/observations tables, but this deployment runs LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only and no longer writes them. ${remediation}`,
+ `The configured export source reads the legacy traces/observations tables, but this deployment runs LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only and no longer writes them. ${legacyRemediation}`,
);
}
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index 1acbd1be10..c95e4676d8 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -19,8 +19,8 @@ import {
transformScoreForMixpanel,
transformEventForMixpanel,
} from "./transformers";
-import { env } from "../../env";
-import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";
+import { env, v4WritesToLegacyTables } from "../../env";
+import { assertExportSourceWritable } from "../exportWriteModeGuard";
const sleep = (ms: number) =>
ms > 0
@@ -132,7 +132,11 @@ const processMixpanelScores = async (
config.projectName,
config.minTimestamp,
config.maxTimestamp,
- { useGraceHash: config.useGraceHash },
+ {
+ useGraceHash: config.useGraceHash,
+ // events_only no longer writes the traces table (LFE-11009)
+ traceAttributesSource: v4WritesToLegacyTables(env) ? "traces" : "events",
+ },
);
logger.info(
@@ -250,8 +254,8 @@ export const handleMixpanelIntegrationProjectJob = async (
try {
// Fail loudly before exporting empty data and advancing lastSyncAt
- // (LFE-10148); the catch below logs and BullMQ retries.
- assertLegacyExportSourceWritable(
+ // (LFE-10148, LFE-11009); the catch below logs and BullMQ retries.
+ assertExportSourceWritable(
mixpanelIntegration.exportSource,
"Select the enriched observations export source in the Mixpanel integration settings.",
);
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index 7e93789e2f..fca4731bbe 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -20,7 +20,8 @@ import {
import { decrypt } from "@langfuse/shared/encryption";
import { PostHog } from "posthog-node";
import { recordExportVolume } from "../../services/exportVolumeMetric";
-import { assertLegacyExportSourceWritable } from "../exportWriteModeGuard";
+import { assertExportSourceWritable } from "../exportWriteModeGuard";
+import { env, v4WritesToLegacyTables } from "../../env";
type PostHogExecutionConfig = {
projectId: string;
@@ -174,7 +175,11 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
- { useGraceHash: config.useGraceHash },
+ {
+ useGraceHash: config.useGraceHash,
+ // events_only no longer writes the traces table (LFE-11009)
+ traceAttributesSource: v4WritesToLegacyTables(env) ? "traces" : "events",
+ },
);
logger.info(
@@ -366,8 +371,8 @@ export const handlePostHogIntegrationProjectJob = async (
try {
// Fail loudly before exporting empty data and advancing lastSyncAt
- // (LFE-10148); the catch below logs and BullMQ retries.
- assertLegacyExportSourceWritable(
+ // (LFE-10148, LFE-11009); the catch below logs and BullMQ retries.
+ assertExportSourceWritable(
postHogIntegration.exportSource,
"Select the enriched observations export source in the PostHog integration settings.",
);