🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(api): add performance controls for GET /api/public/traces (#12062)
Steffen Schmitz8491f3bd0a6d
diff --git a/.env.prod.example b/.env.prod.exampleindex 925b4cda5b..875011f560 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -220,6 +220,15 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=# LANGFUSE_INGESTION_CLICKHOUSE_MAX_ATTEMPTS=+# API Traces endpoint controls (may induce breaking changes on API when changed!)+# Reject GET /api/public/traces requests that do not include a fromTimestamp parameter (returns 400)+# LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE=false+# Apply a default date range (in days) to GET /api/public/traces when no fromTimestamp is provided+# LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS=+# Comma-separated default field groups for GET /api/public/traces when no fields param is provided+# Valid values: core, io, scores, observations, metrics+# LANGFUSE_API_TRACES_DEFAULT_FIELDS=+### START Enterprise Edition Configuration# Allowlisted users that can create new organizations, by default all users can create organizationsdiff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.tsindex 1dcfc47059..edd5f50528 100644--- a/web/src/__tests__/async/traces-api.servertest.ts+++ b/web/src/__tests__/async/traces-api.servertest.ts@@ -2128,6 +2128,141 @@ describe("/api/public/traces API Endpoint", () => {}});+ describe.skip("GET /api/public/traces env var controls", () => {+ const originalRejectNoDateRange =+ env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE;+ const originalDefaultDateRangeDays =+ env.LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS;+ const originalDefaultFields = env.LANGFUSE_API_TRACES_DEFAULT_FIELDS;++ afterEach(() => {+ (env as any).LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE =+ originalRejectNoDateRange;+ (env as any).LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS =+ originalDefaultDateRangeDays;+ (env as any).LANGFUSE_API_TRACES_DEFAULT_FIELDS = originalDefaultFields;+ });++ it("should return 400 when REJECT_NO_DATE_RANGE=true and no fromTimestamp", async () => {+ (env as any).LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE = "true";++ const response = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ "/api/public/traces",+ );++ expect(response.status).toBe(400);+ });++ it("should allow request when REJECT_NO_DATE_RANGE=true and fromTimestamp is provided", async () => {+ (env as any).LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE = "true";++ const fromTimestamp = new Date(+ Date.now() - 7 * 24 * 60 * 60 * 1000,+ ).toISOString();+ const response = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ `/api/public/traces?fromTimestamp=${fromTimestamp}`,+ );++ expect(response.status).toBe(200);+ });++ it("should reject even when DEFAULT_DATE_RANGE_DAYS is also set (rejection takes precedence)", async () => {+ (env as any).LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE = "true";+ (env as any).LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS = 7;++ const response = await makeZodVerifiedAPICallSilent(+ GetTracesV1Response,+ "GET",+ "/api/public/traces",+ );++ expect(response.status).toBe(400);+ });++ it("should apply DEFAULT_FIELDS when no fields query param is provided", async () => {+ (env as any).LANGFUSE_API_TRACES_DEFAULT_FIELDS = "core";++ const traceId = randomUUID();+ const createdTrace = createTrace({+ id: traceId,+ name: "default-fields-test",+ project_id: projectId,+ input: JSON.stringify({ prompt: "test" }),+ output: JSON.stringify({ response: "test response" }),+ });++ const observation = createObservation({+ trace_id: traceId,+ project_id: projectId,+ name: "test-obs",+ start_time: new Date().getTime() - 1000,+ end_time: new Date().getTime(),+ });++ const score = createTraceScore({+ trace_id: traceId,+ project_id: projectId,+ name: "test-score",+ value: 0.8,+ });++ await createTracesCh([createdTrace]);+ await createObservationsCh([observation]);+ await createScoresCh([score]);++ const response = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ "/api/public/traces",+ );++ const trace = response.body.data.find((t) => t.id === traceId);+ expect(trace).toBeTruthy();+ if (!trace) return;++ // With core only, IO/scores/observations/metrics should be defaults+ expect(trace.input).toBeNull();+ expect(trace.output).toBeNull();+ expect(trace.observations).toEqual([]);+ expect(trace.scores).toEqual([]);+ expect(trace.totalCost).toBe(-1);+ expect(trace.latency).toBe(-1);+ });++ it("should override DEFAULT_FIELDS when explicit fields param is provided", async () => {+ (env as any).LANGFUSE_API_TRACES_DEFAULT_FIELDS = "core";++ const traceId = randomUUID();+ const createdTrace = createTrace({+ id: traceId,+ name: "explicit-fields-test",+ project_id: projectId,+ input: JSON.stringify({ prompt: "test" }),+ output: JSON.stringify({ response: "test response" }),+ });++ await createTracesCh([createdTrace]);++ const response = await makeZodVerifiedAPICall(+ GetTracesV1Response,+ "GET",+ "/api/public/traces?fields=core,io",+ );++ const trace = response.body.data.find((t) => t.id === traceId);+ expect(trace).toBeTruthy();+ if (!trace) return;++ // Explicit fields=core,io should override the env default of core-only+ expect(trace.input).toEqual({ prompt: "test" });+ expect(trace.output).toEqual({ response: "test response" });+ });+ });+// Comprehensive filter column tests - verify all documented filter columns don't crashdescribe("Filter Columns - Doesn't Fail Tests", () => {const runFilterTests = (useEventsTable: boolean) => {diff --git a/web/src/env.mjs b/web/src/env.mjsindex 36f0aa4c9e..8fd46871ce 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -363,6 +363,17 @@ export const env = createEnv({.enum(["true", "false"]).default("false"),+ // API Traces endpoint controls (may induce breaking changes on API when changed!)+ LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS: z.coerce+ .number()+ .int()+ .positive()+ .optional(),+ LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE: z+ .enum(["true", "false"])+ .default("false"),+ LANGFUSE_API_TRACES_DEFAULT_FIELDS: z.string().optional(),+// Events table migrationLANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS: z.enum(["true", "false"])@@ -721,6 +732,13 @@ export const env = createEnv({process.env.LANGFUSE_AI_FEATURES_SECRET_KEY,LANGFUSE_AI_FEATURES_PROJECT_ID:process.env.LANGFUSE_AI_FEATURES_PROJECT_ID,+ // API Traces endpoint controls+ LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS:+ process.env.LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS,+ LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE:+ process.env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE,+ LANGFUSE_API_TRACES_DEFAULT_FIELDS:+ process.env.LANGFUSE_API_TRACES_DEFAULT_FIELDS,// Events table migrationLANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS:process.env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS,diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex 85f2b47985..142149ca06 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -5,7 +5,10 @@ import {PostTracesV1Response,DeleteTracesV1Body,DeleteTracesV1Response,+ TRACE_FIELD_GROUPS,+ type TraceFieldGroup,} from "@/src/features/public-api/types/traces";+import { InvalidRequestError } from "@langfuse/shared";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { processEventBatch } from "@langfuse/shared/src/server";@@ -63,11 +66,48 @@ export default withMiddlewares({querySchema: GetTracesV1Query,responseSchema: GetTracesV1Response,fn: async ({ query, auth }) => {+ // Api-performance controls.+ // 1. Reject if no date range and rejection is enabled+ if (+ env.LANGFUSE_API_TRACES_REJECT_NO_DATE_RANGE === "true" &&+ !query.fromTimestamp+ ) {+ throw new InvalidRequestError(+ "fromTimestamp is required. Set the fromTimestamp query parameter to filter traces by date.",+ );+ }++ // 2. Apply default date range if configured and no fromTimestamp provided+ const defaultDateRangeDays =+ env.LANGFUSE_API_TRACES_DEFAULT_DATE_RANGE_DAYS;+ let effectiveFromTimestamp = query.fromTimestamp ?? undefined;+ if (!query.fromTimestamp && defaultDateRangeDays) {+ const referenceDateMs = query.toTimestamp+ ? new Date(query.toTimestamp).getTime()+ : Date.now();+ effectiveFromTimestamp = new Date(+ referenceDateMs - defaultDateRangeDays * 24 * 60 * 60 * 1000,+ ).toISOString();+ }++ // 3. Apply default fields if configured and no fields query param provided+ let effectiveFields = query.fields ?? undefined;+ if (!query.fields && env.LANGFUSE_API_TRACES_DEFAULT_FIELDS) {+ const parsed = env.LANGFUSE_API_TRACES_DEFAULT_FIELDS.split(",")+ .map((f) => f.trim())+ .filter((f): f is TraceFieldGroup =>+ TRACE_FIELD_GROUPS.includes(f as TraceFieldGroup),+ );+ if (parsed.length > 0) {+ effectiveFields = parsed;+ }+ }+const filterProps = {projectId: auth.scope.projectId,page: query.page ?? undefined,limit: query.limit ?? undefined,- fields: query.fields ?? undefined,+ fields: effectiveFields,userId: query.userId ?? undefined,name: query.name ?? undefined,tags: query.tags ?? undefined,@@ -75,7 +115,7 @@ export default withMiddlewares({sessionId: query.sessionId ?? undefined,version: query.version ?? undefined,release: query.release ?? undefined,- fromTimestamp: query.fromTimestamp ?? undefined,+ fromTimestamp: effectiveFromTimestamp,toTimestamp: query.toTimestamp ?? undefined,};