🪢 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
fix(traces): Use events-based tables for checking access to traces (#15721)
Ben Bachemdac41cfd4650
diff --git a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.tsindex c589c8e204..bbd62032d0 100644--- a/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts+++ b/web/src/__tests__/server/admin-access-webhook-middleware.servertest.ts@@ -13,6 +13,7 @@ vi.mock("@langfuse/shared/src/server", async () => {return {...originalModule,getTraceById: vi.fn(),+ getTraceByIdFromEventsTable: vi.fn(),};});@@ -20,11 +21,15 @@ import {createTRPCRouter,createInnerTRPCContext,protectedProjectProcedureWithoutTracing,+ protectedGetEventsTraceProcedure,protectedGetTraceProcedure,protectedGetSessionProcedure,} from "@/src/server/api/trpc";import { resetAdminAccessWebhookCacheForTests } from "@/src/server/adminAccessWebhook";-import { getTraceById } from "@langfuse/shared/src/server";+import {+ getTraceById,+ getTraceByIdFromEventsTable,+} from "@langfuse/shared/src/server";const middlewareTestRouter = createTRPCRouter({project: protectedProjectProcedureWithoutTracing@@ -33,6 +38,15 @@ const middlewareTestRouter = createTRPCRouter({trace: protectedGetTraceProcedure.input(z.object({ traceId: z.string(), projectId: z.string() })).query(() => ({ ok: true })),+ eventsTrace: protectedGetEventsTraceProcedure+ .input(+ z.object({+ traceId: z.string(),+ projectId: z.string(),+ timestamp: z.date().optional(),+ }),+ )+ .query(({ ctx }) => ({ timestamp: ctx.trace?.timestamp })),session: protectedGetSessionProcedure.input(z.object({ sessionId: z.string(), projectId: z.string() })).query(() => ({ ok: true })),@@ -74,7 +88,7 @@ const createAdminSession = (});const createTestCaller = (params: {- session: Session;+ session: Session | null;projectOrgId?: string;traceSession?: { public: boolean } | null;}) => {@@ -109,8 +123,17 @@ const createTestCaller = (params: {describe("admin access webhook in tRPC authorization middleware", () => {const mockGetTraceById = vi.mocked(getTraceById);+ const mockGetTraceByIdFromEventsTable = vi.mocked(+ getTraceByIdFromEventsTable,+ );const originalWebhook = env.LANGFUSE_ADMIN_ACCESS_WEBHOOK;const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalWriteMode = env.LANGFUSE_MIGRATION_V4_WRITE_MODE;+ const setWriteMode = (+ writeMode: typeof env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ ) => {+ Object.assign(env, { LANGFUSE_MIGRATION_V4_WRITE_MODE: writeMode });+ };beforeAll(() => {(env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = "https://example.com/hook";@@ -121,6 +144,7 @@ describe("admin access webhook in tRPC authorization middleware", () => {resetAdminAccessWebhookCacheForTests();vi.restoreAllMocks();vi.clearAllMocks();+ setWriteMode("dual");vi.spyOn(globalThis, "fetch").mockResolvedValue({ ok: true } as Response);mockGetTraceById.mockResolvedValue({id: "trace-id",@@ -128,12 +152,21 @@ describe("admin access webhook in tRPC authorization middleware", () => {output: "{}",public: false,sessionId: null,- } as any);+ } as unknown as Awaited<ReturnType<typeof getTraceById>>);+ mockGetTraceByIdFromEventsTable.mockResolvedValue({+ id: "trace-id",+ input: null,+ output: null,+ public: true,+ sessionId: null,+ timestamp: new Date("2025-01-01T00:00:00.000Z"),+ } as unknown as Awaited<ReturnType<typeof getTraceByIdFromEventsTable>>);});afterAll(() => {(env as any).LANGFUSE_ADMIN_ACCESS_WEBHOOK = originalWebhook;(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ setWriteMode(originalWriteMode);});it("sends webhook when admin accesses a project they are not a member of", async () => {@@ -188,6 +221,102 @@ describe("admin access webhook in tRPC authorization middleware", () => {});});+ it.each(["dual", "events_only"] as const)(+ "uses a minimal canonical events trace lookup for authorization in %s mode",+ async (writeMode) => {+ setWriteMode(writeMode);+ const timestamp = new Date("2025-01-01T12:00:00.000Z");+ const { caller } = createTestCaller({+ session: null,+ traceSession: null,+ });++ const result = await caller.eventsTrace({+ traceId: "trace-id",+ projectId: "project-id",+ timestamp,+ });++ expect(mockGetTraceByIdFromEventsTable).toHaveBeenCalledWith({+ traceId: "trace-id",+ projectId: "project-id",+ excludeInputOutput: true,+ excludeMetadata: true,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ });+ expect(mockGetTraceById).not.toHaveBeenCalled();+ expect(result.timestamp).toEqual(new Date("2025-01-01T00:00:00.000Z"));+ },+ );++ it("uses the legacy trace lookup for events procedures in legacy mode", async () => {+ setWriteMode("legacy");+ const timestamp = new Date("2025-01-01T12:00:00.000Z");+ mockGetTraceById.mockResolvedValueOnce({+ id: "trace-id",+ input: "{}",+ output: "{}",+ public: true,+ sessionId: null,+ } as unknown as Awaited<ReturnType<typeof getTraceById>>);+ const { caller } = createTestCaller({+ session: null,+ traceSession: null,+ });++ await caller.eventsTrace({+ traceId: "trace-id",+ projectId: "project-id",+ timestamp,+ });++ expect(mockGetTraceById).toHaveBeenCalledWith({+ traceId: "trace-id",+ projectId: "project-id",+ timestamp,+ fromTimestamp: undefined,+ renderingProps: {+ truncated: false,+ shouldJsonParse: false,+ },+ });+ expect(mockGetTraceByIdFromEventsTable).not.toHaveBeenCalled();+ });++ it("rejects unauthenticated access to a private events trace", async () => {+ mockGetTraceByIdFromEventsTable.mockResolvedValueOnce({+ id: "private-trace-id",+ input: null,+ output: null,+ public: false,+ sessionId: null,+ timestamp: new Date("2025-01-01T00:00:00.000Z"),+ } as unknown as Awaited<ReturnType<typeof getTraceByIdFromEventsTable>>);+ const { caller } = createTestCaller({ session: null });++ await expect(+ caller.eventsTrace({+ traceId: "private-trace-id",+ projectId: "project-id",+ }),+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });+ });++ it("does not resolve an events trace from another project", async () => {+ mockGetTraceByIdFromEventsTable.mockResolvedValueOnce(undefined);+ const { caller } = createTestCaller({ session: null });++ await expect(+ caller.eventsTrace({+ traceId: "trace-id",+ projectId: "wrong-project-id",+ }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });+ });+it("sends webhook when admin accesses session in a project they are not a member of", async () => {const projectId = "session-project-id";const { caller, mockPrisma } = createTestCaller({diff --git a/web/src/__tests__/server/otel-api.servertest.ts b/web/src/__tests__/server/otel-api.servertest.tsindex 8635462efa..6b2fa10a36 100644--- a/web/src/__tests__/server/otel-api.servertest.ts+++ b/web/src/__tests__/server/otel-api.servertest.ts@@ -3,15 +3,21 @@ import waitForExpect from "wait-for-expect";import {clickhouseClient,createBasicAuthHeader,+ createEvent,+ createEventsCh,getObservationById,getObservationByIdFromEventsTable,getS3EventStorageClient,getTraceById,+ getTraceByIdFromEventsTable,} from "@langfuse/shared/src/server";import { env as sharedEnv } from "@langfuse/shared/src/env";import { randomBytes } from "crypto";import { env } from "@/src/env.mjs";import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const eventsTableAvailable =@@ -126,6 +132,174 @@ describe("/api/public/otel/v1/traces API Endpoint", () => {}, 25_000);}, 30_000);+ maybeEventsTable(+ "should allow unauthenticated access to an OTel trace made public by a child span",+ async () => {+ const traceId = randomBytes(16);+ const rootSpanId = randomBytes(8);+ const childSpanId = randomBytes(8);+ const traceIdHex = traceId.toString("hex");+ const rootSpanIdHex = rootSpanId.toString("hex");+ const childSpanIdHex = childSpanId.toString("hex");+ const traceTimestamp = new Date("2025-04-30T15:28:50.686Z");++ // Event propagation intentionally lags ingestion, so seed its output with+ // only the child public to reproduce the state before a UI re-share.+ await createEventsCh([+ createEvent({+ id: rootSpanIdHex,+ span_id: rootSpanIdHex,+ trace_id: traceIdHex,+ project_id: projectId,+ parent_span_id: null,+ start_time: traceTimestamp.getTime() * 1000,+ name: "public-trace-root",+ public: false,+ }),+ createEvent({+ id: childSpanIdHex,+ span_id: childSpanIdHex,+ trace_id: traceIdHex,+ project_id: projectId,+ parent_span_id: rootSpanIdHex,+ start_time: traceTimestamp.getTime() * 1000 + 100,+ name: "public-trace-child",+ public: true,+ }),+ ]);++ await waitForExpect(async () => {+ const childEvent = await getObservationByIdFromEventsTable({+ projectId,+ id: childSpanIdHex,+ });+ expect(childEvent).toBeDefined();+ });++ const response = await makeAPICall("POST", "/api/public/otel/v1/traces", {+ resourceSpans: [+ {+ resource: { attributes: [] },+ scopeSpans: [+ {+ scope: {+ name: "langfuse-sdk",+ version: "2.60.3",+ attributes: [+ {+ key: "public_key",+ value: { stringValue: "pk-lf-1234567890" },+ },+ ],+ },+ spans: [+ {+ traceId,+ spanId: rootSpanId,+ name: "public-trace-root",+ kind: 1,+ startTimeUnixNano: {+ low: 466848096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467248096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [],+ status: {},+ },+ {+ traceId,+ spanId: childSpanId,+ parentSpanId: rootSpanId,+ name: "public-trace-child",+ kind: 1,+ startTimeUnixNano: {+ low: 466948096,+ high: 406528574,+ unsigned: true,+ },+ endTimeUnixNano: {+ low: 467148096,+ high: 406528574,+ unsigned: true,+ },+ attributes: [+ {+ key: "langfuse.trace.public",+ value: { boolValue: true },+ },+ ],+ status: {},+ },+ ],+ },+ ],+ },+ ],+ });++ expect(response.status).toBe(200);++ await waitForExpect(async () => {+ const [trace, rootEvent, childEvent] = await Promise.all([+ getTraceById({ projectId, traceId: traceIdHex }),+ getObservationByIdFromEventsTable({+ projectId,+ id: rootSpanIdHex,+ }),+ getObservationByIdFromEventsTable({+ projectId,+ id: childSpanIdHex,+ }),+ ]);+ expect(trace?.public).toBe(false);+ expect(rootEvent?.name).toBe("public-trace-root");+ expect(childEvent?.name).toBe("public-trace-child");++ const eventTrace = await getTraceByIdFromEventsTable({+ projectId,+ traceId: traceIdHex,+ });+ expect(eventTrace?.public).toBe(true);+ }, 25_000);++ const unAuthedContext = createInnerTRPCContext({+ session: null,+ headers: {},+ });+ const unAuthedCaller = appRouter.createCaller({+ ...unAuthedContext,+ prisma,+ });++ const result = await unAuthedCaller.events.byTraceId({+ projectId,+ traceId: traceIdHex,+ });++ expect(result.observations.map(({ id }) => id)).toEqual(+ expect.arrayContaining([rootSpanIdHex, childSpanIdHex]),+ );+ expect(result.observations).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: rootSpanIdHex,+ name: "public-trace-root",+ }),+ expect.objectContaining({+ id: childSpanIdHex,+ name: "public-trace-child",+ }),+ ]),+ );+ },+ 60_000,+ );+it("should process a json payload with usage details correctly", async () => {const traceId = randomBytes(16);const spanId = randomBytes(8);diff --git a/web/src/components/layouts/app-layout/index.tsx b/web/src/components/layouts/app-layout/index.tsxindex a94616f4be..06d8ece397 100644--- a/web/src/components/layouts/app-layout/index.tsx+++ b/web/src/components/layouts/app-layout/index.tsx@@ -85,7 +85,7 @@ export function AppLayout(props: PropsWithChildren) {// For publishable paths (shared traces/sessions), render minimal layout without sidebar// This allows authenticated users to view shared content without seeing project navigationif (isPublishable) {- return <MinimalLayout>{props.children}</MinimalLayout>;+ return <MinimalLayout fullBleed>{props.children}</MinimalLayout>;}// For non-publishable paths, show error page. This is an EXPECTED state (an@@ -114,7 +114,7 @@ export function AppLayout(props: PropsWithChildren) {// Publishable paths (traces, sessions) when unauthenticated// Render minimal layout without navigation/sidebarif (isPublishable && session.status === "unauthenticated") {- return <MinimalLayout>{props.children}</MinimalLayout>;+ return <MinimalLayout fullBleed>{props.children}</MinimalLayout>;}// Render minimal layout (onboarding, public routes)diff --git a/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx b/web/src/components/layouts/app-layout/variants/MinimalLayout.tsxindex 9cde684d3c..3771f3d887 100644--- a/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx+++ b/web/src/components/layouts/app-layout/variants/MinimalLayout.tsx@@ -7,10 +7,15 @@import type { PropsWithChildren } from "react";import { SidebarProvider } from "@/src/components/ui/sidebar";-export function MinimalLayout({ children }: PropsWithChildren) {+export function MinimalLayout({+ children,+ fullBleed = false,+}: PropsWithChildren<{ fullBleed?: boolean }>) {return (<SidebarProvider className="bg-primary-foreground">- <main className="min-h-dvh w-full overflow-y-auto p-3 px-4 py-4 sm:px-6 lg:px-8">+ <main+ className={`min-h-dvh w-full overflow-y-auto ${fullBleed ? "" : "p-3 px-4 py-4 sm:px-6 lg:px-8"}`}+ >{children}</main></SidebarProvider>diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex 565388c65c..cae4ba55ee 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -3,7 +3,7 @@ import { z as zodSchema } from "zod";import {createTRPCRouter,protectedProjectProcedure,- protectedGetTraceProcedure,+ protectedGetEventsTraceProcedure,} from "@/src/server/api/trpc";import {type OrderByState,@@ -90,7 +90,7 @@ export const BatchIOInput = zodSchema.object({maxStartTime: zodSchema.date(),truncated: zodSchema.boolean().optional(), // Defaults to true for performanceincludeToolCalls: zodSchema.boolean().optional(), // Defaults to false; tool-call arrays can be large- // Opts into trace-level auth (public traces) in protectedGetTraceProcedure+ // Opts into trace-level auth (public traces) in protectedGetEventsTraceProceduretraceId: zodSchema.string().optional(),});@@ -193,7 +193,7 @@ export const eventsRouter = createTRPCRouter({},);}),- batchIO: protectedGetTraceProcedure+ batchIO: protectedGetEventsTraceProcedure.input(BatchIOInput).query(async ({ input }) => {return instrumentAsync(@@ -248,7 +248,7 @@ export const eventsRouter = createTRPCRouter({* Fetch scores and corrections for a trace.* Used by the v4 trace detail view where trace data comes from events table.*/- scoresForTrace: protectedGetTraceProcedure+ scoresForTrace: protectedGetEventsTraceProcedure.input(zodSchema.object({projectId: zodSchema.string(),@@ -278,7 +278,7 @@ export const eventsRouter = createTRPCRouter({* Returns up to MAX_OBSERVATIONS_PER_TRACE observations.* Sets cutoffObservationsAfterMaxCount=true if trace exceeds the cap.*/- byTraceId: protectedGetTraceProcedure+ byTraceId: protectedGetEventsTraceProcedure.input(zodSchema.object({projectId: zodSchema.string(),@@ -315,7 +315,7 @@ export const eventsRouter = createTRPCRouter({* Used by v4 events-based trace detail view for graph visualization.* Returns same shape as traces.getAgentGraphData for frontend compatibility.*/- getAgentGraphData: protectedGetTraceProcedure+ getAgentGraphData: protectedGetEventsTraceProcedure.input(zodSchema.object({projectId: zodSchema.string(),diff --git a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsxindex 2d37f42705..89ff8c92b6 100644--- a/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx+++ b/web/src/features/traces/components/ObservationDetailView/ObservationDetailView.tsx@@ -64,6 +64,8 @@ import {getDescendantIds,} from "@/src/features/traces/fns/trace-aggregation";import TagList from "@/src/features/tag/components/TagList";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useSession } from "next-auth/react";export interface ObservationDetailViewProps {observation: ObservationReturnTypeWithMetadata;@@ -257,6 +259,11 @@ export function ObservationDetailView({observationId: observation.id,});+ const session = useSession();+ const hasCommentsReadAccess = useHasProjectAccess({+ projectId,+ scope: "comments:read",+ });const observationComments = api.comments.getByObjectId.useQuery({projectId,@@ -265,6 +272,7 @@ export function ObservationDetailView({},{refetchOnMount: false,+ enabled: hasCommentsReadAccess && session.status === "authenticated",},);diff --git a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsxindex 94cff2f8d1..d1c64257d0 100644--- a/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx+++ b/web/src/features/traces/components/TraceDetailView/TraceDetailView.tsx@@ -41,6 +41,8 @@ import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencimport { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";import { useCommentedPaths } from "@/src/features/comments/hooks/useCommentedPaths";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useSession } from "next-auth/react";// Extracted componentsimport { TraceDetailViewHeader } from "./components/TraceDetailViewHeader";@@ -147,6 +149,11 @@ export function TraceDetailView({});// Fetch comments for this trace (for inline comment highlighting)+ const session = useSession();+ const hasCommentsReadAccess = useHasProjectAccess({+ projectId,+ scope: "comments:read",+ });const traceComments = api.comments.getByObjectId.useQuery({projectId,@@ -155,6 +162,7 @@ export function TraceDetailView({},{refetchOnMount: false,+ enabled: hasCommentsReadAccess && session.status === "authenticated",},);diff --git a/web/src/features/traces/useTraceDetailData.clienttest.tsx b/web/src/features/traces/useTraceDetailData.clienttest.tsxindex 39f37ab6a7..eb0d192d63 100644--- a/web/src/features/traces/useTraceDetailData.clienttest.tsx+++ b/web/src/features/traces/useTraceDetailData.clienttest.tsx@@ -4,17 +4,26 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { useTraceDetailData } from "@/src/features/traces/useTraceDetailData";// Created via vi.hoisted so they exist before the hoisted vi.mock factories run.-const { mockUseV4Beta, mockUseEventsTraceData, mockTracesQuery } = vi.hoisted(- () => ({- mockUseV4Beta: vi.fn(),- mockUseEventsTraceData: vi.fn(),- mockTracesQuery: vi.fn(),- }),-);+const {+ mockUseV4Beta,+ mockUseSession,+ mockUseEventsTraceData,+ mockTracesQuery,+ mockTraceReadConfigQuery,+} = vi.hoisted(() => ({+ mockUseV4Beta: vi.fn(),+ mockUseSession: vi.fn(),+ mockUseEventsTraceData: vi.fn(),+ mockTracesQuery: vi.fn(),+ mockTraceReadConfigQuery: vi.fn(),+}));vi.mock("@/src/features/events/hooks/useV4Beta", () => ({useV4Beta: () => mockUseV4Beta(),}));+vi.mock("next-auth/react", () => ({+ useSession: () => mockUseSession(),+}));vi.mock("@/src/features/events/hooks/useEventsTraceData", () => ({useEventsTraceData: (args: unknown) => mockUseEventsTraceData(args),}));@@ -22,8 +31,17 @@ vi.mock("@/src/features/events/hooks/useEventsTraceData", () => ({// beta path), so it only needs to return a query-shaped object.vi.mock("@/src/utils/api", () => ({api: {+ public: {+ traceReadConfig: {+ useQuery: (input: unknown, options: unknown) =>+ mockTraceReadConfigQuery(input, options),+ },+ },traces: {- byIdWithObservationsAndScores: { useQuery: () => mockTracesQuery() },+ byIdWithObservationsAndScores: {+ useQuery: (input: unknown, options: unknown) =>+ mockTracesQuery(input, options),+ },},},}));@@ -34,7 +52,13 @@ const render = () =>describe("useTraceDetailData (beta / events path)", () => {beforeEach(() => {+ vi.clearAllMocks();mockUseV4Beta.mockReturnValue({ isBetaEnabled: true });+ mockUseSession.mockReturnValue({ status: "authenticated" });+ mockTraceReadConfigQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ });mockTracesQuery.mockReturnValue({data: undefined,isLoading: false,@@ -83,3 +107,124 @@ describe("useTraceDetailData (beta / events path)", () => {expect(r.isUnauthorized).toBe(false);});});++describe("useTraceDetailData endpoint routing", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockUseV4Beta.mockReturnValue({ isBetaEnabled: false });+ mockTraceReadConfigQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ });+ mockTracesQuery.mockReturnValue({+ data: undefined,+ isLoading: false,+ isError: false,+ error: null,+ });+ mockUseEventsTraceData.mockReturnValue({+ data: undefined,+ isLoading: false,+ error: null,+ cutoffObservationsAfterMaxCount: false,+ });+ });++ it.each(["dual", "events_only"] as const)(+ "uses events endpoints for unauthenticated users in %s mode",+ (v4WriteMode) => {+ mockUseSession.mockReturnValue({ status: "unauthenticated" });+ mockTraceReadConfigQuery.mockReturnValue({+ data: { v4WriteMode },+ isLoading: false,+ });++ render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: false,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: true }),+ );+ },+ );++ it("uses legacy endpoints for unauthenticated users in legacy mode", () => {+ mockUseSession.mockReturnValue({ status: "unauthenticated" });+ mockTraceReadConfigQuery.mockReturnValue({+ data: { v4WriteMode: "legacy" },+ isLoading: false,+ });++ render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: true,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: false }),+ );+ });++ it("uses events endpoints for authenticated beta users", () => {+ mockUseSession.mockReturnValue({ status: "authenticated" });+ mockUseV4Beta.mockReturnValue({ isBetaEnabled: true });++ render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: false,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: true }),+ );+ });++ it("uses legacy endpoints for authenticated non-beta users", () => {+ mockUseSession.mockReturnValue({ status: "authenticated" });++ render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: true,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: false }),+ );+ });++ it("waits for authentication status before selecting endpoints", () => {+ mockUseSession.mockReturnValue({ status: "loading" });++ const result = render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: false,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: false }),+ );+ expect(result.isLoading).toBe(true);+ expect(result.isNotFound).toBe(false);+ });++ it("waits for runtime config before routing unauthenticated users", () => {+ mockUseSession.mockReturnValue({ status: "unauthenticated" });+ mockTraceReadConfigQuery.mockReturnValue({+ data: undefined,+ isLoading: true,+ });++ const result = render();++ expect(mockTracesQuery.mock.calls[0]?.[1]).toMatchObject({+ enabled: false,+ });+ expect(mockUseEventsTraceData).toHaveBeenCalledWith(+ expect.objectContaining({ enabled: false }),+ );+ expect(result.isLoading).toBe(true);+ expect(result.isNotFound).toBe(false);+ });+});diff --git a/web/src/features/traces/useTraceDetailData.ts b/web/src/features/traces/useTraceDetailData.tsindex 1315f9f103..af542b7455 100644--- a/web/src/features/traces/useTraceDetailData.ts+++ b/web/src/features/traces/useTraceDetailData.ts@@ -1,6 +1,7 @@import { api } from "@/src/utils/api";import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { useEventsTraceData } from "@/src/features/events/hooks/useEventsTraceData";+import { useSession } from "next-auth/react";/*** Single source of truth for fetching a trace's detail data, beta-aware (events@@ -21,6 +22,20 @@ export function useTraceDetailData({enabled?: boolean;}) {const { isBetaEnabled } = useV4Beta();+ const { status: sessionStatus } = useSession();+ const isUnauthenticated = sessionStatus === "unauthenticated";+ const traceReadConfig = api.public.traceReadConfig.useQuery(undefined, {+ enabled: isUnauthenticated,+ staleTime: Infinity,+ });+ const isTraceSourceLoading =+ sessionStatus === "loading" ||+ (isUnauthenticated && traceReadConfig.isLoading);+ const unauthenticatedEventsReadEnabled =+ traceReadConfig.data?.v4WriteMode === "dual" ||+ traceReadConfig.data?.v4WriteMode === "events_only";+ const useEventsTraceSource =+ isBetaEnabled || (isUnauthenticated && unauthenticatedEventsReadEnabled);// Old path: traces table (beta OFF).const tracesQuery = api.traces.byIdWithObservationsAndScores.useQuery(@@ -30,7 +45,8 @@ export function useTraceDetailData({timestamp,},{- enabled: enabled && !!traceId && !isBetaEnabled,+ enabled:+ enabled && !!traceId && !isTraceSourceLoading && !useEventsTraceSource,retry(failureCount, error) {if (error.data?.code === "UNAUTHORIZED" ||@@ -48,10 +64,23 @@ export function useTraceDetailData({projectId,traceId: traceId ?? "",timestamp,- enabled: enabled && !!traceId && isBetaEnabled,+ enabled:+ enabled && !!traceId && !isTraceSourceLoading && useEventsTraceSource,});- if (isBetaEnabled) {+ if (isTraceSourceLoading) {+ return {+ data: undefined,+ isLoading: true,+ error: null,+ isError: false,+ isNotFound: false,+ isUnauthorized: false,+ cutoffObservationsAfterMaxCount: false,+ };+ }++ if (useEventsTraceSource) {// useEventsTraceData types its error as `unknown`; narrow to the trpc shape// to read the code (the non-beta branch gets this for free from the typed// tracesQuery.error).diff --git a/web/src/server/api/routers/public.ts b/web/src/server/api/routers/public.tsindex f793c09e3c..b26a217cf0 100644--- a/web/src/server/api/routers/public.ts+++ b/web/src/server/api/routers/public.ts@@ -18,6 +18,9 @@ const ReleaseApiRes = z.array();export const publicRouter = createTRPCRouter({+ traceReadConfig: publicProcedure.query(() => ({+ v4WriteMode: env.LANGFUSE_MIGRATION_V4_WRITE_MODE,+ })),tracingSearchConfig: protectedProjectProcedure.input(z.object({ projectId: z.string() })).query(() => ({diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 51ce8dc1c5..503fb5e856 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -490,135 +490,161 @@ const inputTraceSchema = z.object({verbosity: z.enum(["compact", "truncated", "full"]).default("full"),});-const enforceTraceAccess = t.middleware(async (opts) => {- const { ctx, next } = opts;- const actualInput = await opts.getRawInput();- const result = inputTraceSchema.safeParse(actualInput);-- if (!result.success) {- logger.error("Invalid input when parsing request body", result.error);- throw new TRPCError({- code: "BAD_REQUEST",- message: `Invalid input, ${result.error.message}`,- });- }-- const traceId = result.data.traceId;- const projectId = result.data.projectId;- const timestamp = result.data.timestamp;- const fromTimestamp = result.data.fromTimestamp;- const verbosity = result.data.verbosity;- const isEventsOnly = env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only";+const enforceTraceAccess = (readSource: "v3" | "v4") =>+ t.middleware(async (opts) => {+ const { ctx, next } = opts;+ const actualInput = await opts.getRawInput();+ const result = inputTraceSchema.safeParse(actualInput);++ if (!result.success) {+ logger.error("Invalid input when parsing request body", result.error);+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Invalid input, ${result.error.message}`,+ });+ }- let clickhouseTrace = traceId- ? // eslint-disable-next-line @typescript-eslint/no-deprecated- await getTraceById({+ const traceId = result.data.traceId;+ const projectId = result.data.projectId;+ const timestamp = result.data.timestamp;+ const fromTimestamp = result.data.fromTimestamp;+ const verbosity = result.data.verbosity;+ const isEventsOnly = env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only";++ const useEventsTraceSource =+ readSource === "v4" && env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "legacy";++ let clickhouseTrace = traceId+ ? useEventsTraceSource+ ? await getTraceByIdFromEventsTable({+ traceId,+ projectId,+ excludeInputOutput: true,+ excludeMetadata: true,+ renderingProps: {+ truncated: true,+ shouldJsonParse: false,+ },+ })+ : // eslint-disable-next-line @typescript-eslint/no-deprecated+ await getTraceById({+ traceId,+ projectId,+ timestamp: isEventsOnly ? undefined : (timestamp ?? undefined),+ fromTimestamp:+ fromTimestamp ??+ (isEventsOnly ? timestamp : undefined) ??+ undefined,+ renderingProps: {+ truncated: verbosity === "truncated",+ shouldJsonParse: false, // we do not want to parse the input/output for tRPC+ },+ })+ : null;++ // In dual write mode the lookup above reads the legacy traces table, but+ // internally produced traces (e.g. code-eval execution traces) were written+ // to the events tables only — fall back so trace-level auth does not 404 on+ // a trace the events-backed views can render (LFE-10884). The timestamp can+ // identify a clicked observation, so use it as a bounded lookup anchor rather+ // than as the synthesized trace timestamp (LFE-10947).+ if (+ traceId &&+ !clickhouseTrace &&+ readSource === "v3" &&+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual"+ ) {+ clickhouseTrace = await getTraceByIdFromEventsTable({traceId,projectId,- timestamp: isEventsOnly ? undefined : (timestamp ?? undefined),- fromTimestamp:- fromTimestamp ?? (isEventsOnly ? timestamp : undefined) ?? undefined,+ fromTimestamp: fromTimestamp ?? timestamp ?? undefined,renderingProps: {truncated: verbosity === "truncated",- shouldJsonParse: false, // we do not want to parse the input/output for tRPC+ shouldJsonParse: false,},- })- : null;-- // In dual write mode the lookup above reads the legacy traces table, but- // internally produced traces (e.g. code-eval execution traces) were written- // to the events tables only — fall back so trace-level auth does not 404 on- // a trace the events-backed views can render (LFE-10884). The timestamp can- // identify a clicked observation, so use it as a bounded lookup anchor rather- // than as the synthesized trace timestamp (LFE-10947).- if (- traceId &&- !clickhouseTrace &&- env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual"- ) {- clickhouseTrace = await getTraceByIdFromEventsTable({- traceId,- projectId,- fromTimestamp: fromTimestamp ?? timestamp ?? undefined,- renderingProps: {- truncated: verbosity === "truncated",- shouldJsonParse: false,- },- });- }+ });+ }- if (traceId && !clickhouseTrace) {- logger.error(`Trace with id ${traceId} not found for project ${projectId}`);- throw new TRPCError({- code: "NOT_FOUND",- message: "Trace not found",- });- }+ if (traceId && !clickhouseTrace) {+ logger.error(+ `Trace with id ${traceId} not found for project ${projectId}`,+ );+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Trace not found",+ });+ }- const trace = clickhouseTrace- ? {- ...clickhouseTrace,- input: parseIO(clickhouseTrace.input, verbosity),- output: parseIO(clickhouseTrace.output, verbosity),- }- : null;+ const trace = clickhouseTrace+ ? {+ ...clickhouseTrace,+ input: parseIO(clickhouseTrace.input, verbosity),+ output: parseIO(clickhouseTrace.output, verbosity),+ }+ : null;++ const sessionProject = ctx.session?.user?.organizations+ .flatMap((org) => org.projects)+ .find(({ id }) => id === projectId);++ const traceSession = !!trace?.sessionId+ ? await ctx.prisma.traceSession.findFirst({+ where: {+ id: trace.sessionId,+ projectId,+ },+ select: {+ public: true,+ },+ })+ : null;++ const isSessionPublic = traceSession?.public === true;++ if (+ !trace?.public &&+ !sessionProject &&+ !isSessionPublic &&+ ctx.session?.user?.admin !== true+ ) {+ logger.error(+ `User ${ctx.session?.user?.id} is not a member of project ${projectId}`,+ );+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message:+ "User is not a member of this project and this trace is not public",+ });+ }- const sessionProject = ctx.session?.user?.organizations- .flatMap((org) => org.projects)- .find(({ id }) => id === projectId);+ if (ctx.session?.user?.admin === true) {+ await sendAdminAccessWebhook({+ email: ctx.session.user.email,+ projectId,+ });+ }- const traceSession = !!trace?.sessionId- ? await ctx.prisma.traceSession.findFirst({- where: {- id: trace.sessionId,- projectId,- },- select: {- public: true,+ return next({+ ctx: {+ session: {+ ...ctx.session,+ projectRole:+ ctx.session?.user?.admin === true+ ? Role.OWNER+ : sessionProject?.role,},- })- : null;-- const isSessionPublic = traceSession?.public === true;-- if (- !trace?.public &&- !sessionProject &&- !isSessionPublic &&- ctx.session?.user?.admin !== true- ) {- logger.error(- `User ${ctx.session?.user?.id} is not a member of project ${projectId}`,- );- throw new TRPCError({- code: "UNAUTHORIZED",- message:- "User is not a member of this project and this trace is not public",- });- }-- if (ctx.session?.user?.admin === true) {- await sendAdminAccessWebhook({- email: ctx.session.user.email,- projectId,- });- }-- return next({- ctx: {- session: {- ...ctx.session,- projectRole:- ctx.session?.user?.admin === true ? Role.OWNER : sessionProject?.role,+ trace, // pass the trace to the next middleware so we do not need to fetch it again},- trace, // pass the trace to the next middleware so we do not need to fetch it again- },+ });});-});export const protectedGetTraceProcedure = withOtelTracingProcedure.use(withErrorHandling)- .use(enforceTraceAccess);+ .use(enforceTraceAccess("v3"));++export const protectedGetEventsTraceProcedure = withOtelTracingProcedure+ .use(withErrorHandling)+ .use(enforceTraceAccess("v4"));/** Protect session-level getter routes.