🪢 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(v4): populate environment filter options from events tables in non-legacy write modes (#14959)
Steffen Schmitzbbe04fcb3550
diff --git a/packages/shared/src/server/repositories/environments.ts b/packages/shared/src/server/repositories/environments.tsindex 829d838384..4f8648a840 100644--- a/packages/shared/src/server/repositories/environments.ts+++ b/packages/shared/src/server/repositories/environments.ts@@ -1,4 +1,5 @@import { LISTABLE_SCORE_TYPES } from "../../domain/scores";+import { env } from "../../env";import { queryClickhouse } from "./clickhouse";export type EnvironmentFilterProps = {@@ -11,38 +12,61 @@ export const getEnvironmentsForProject = async (): Promise<{ environment: string }[]> => {const { projectId, fromTimestamp } = props;- const query = `- (- SELECT distinct environment- FROM traces- WHERE project_id = {projectId: String}- ${fromTimestamp ? "AND timestamp >= {fromTimestamp: DateTime64(3)}" : ""}- ) UNION ALL (- SELECT distinct environment- FROM observations- WHERE project_id = {projectId: String}- ${fromTimestamp ? "AND start_time >= {fromTimestamp: DateTime64(3)}" : ""}- ) UNION ALL (+ // In dual and events_only write modes all tracing data lands in the events+ // tables: a single events_core scan covers traces and observations and is+ // the only populated source under events_only. Scores keep their own table+ // in every write mode. The events read may be routed to a dedicated+ // ClickHouse service (CLICKHOUSE_EVENTS_READ_ONLY_URL), so it cannot share+ // a query with the scores read.+ const tracingEnvironmentsPromise =+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "legacy"+ ? queryClickhouse<{ environment: string }>({+ query: `+ (+ SELECT distinct environment+ FROM traces+ WHERE project_id = {projectId: String}+ ${fromTimestamp ? "AND timestamp >= {fromTimestamp: DateTime64(3)}" : ""}+ ) UNION ALL (+ SELECT distinct environment+ FROM observations+ WHERE project_id = {projectId: String}+ ${fromTimestamp ? "AND start_time >= {fromTimestamp: DateTime64(3)}" : ""}+ )+ `,+ params: { projectId, fromTimestamp },+ tags: { projectId },+ preferredClickhouseService: "ReadOnly",+ })+ : queryClickhouse<{ environment: string }>({+ query: `+ SELECT distinct environment+ FROM events_core+ WHERE project_id = {projectId: String}+ ${fromTimestamp ? "AND start_time >= {fromTimestamp: DateTime64(3)}" : ""}+ `,+ params: { projectId, fromTimestamp },+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",+ });++ const scoreEnvironmentsPromise = queryClickhouse<{ environment: string }>({+ query: `SELECT distinct environmentFROM scoresWHERE project_id = {projectId: String}AND data_type IN ({dataTypes: Array(String)})${fromTimestamp ? "AND timestamp >= {fromTimestamp: DateTime64(3)}" : ""}- )- `;-- const results = await queryClickhouse<{- environment: string;- }>({- query,- params: {- projectId,- fromTimestamp,- dataTypes: LISTABLE_SCORE_TYPES,- },+ `,+ params: { projectId, fromTimestamp, dataTypes: LISTABLE_SCORE_TYPES },tags: { projectId },preferredClickhouseService: "ReadOnly",});++ const results = (+ await Promise.all([tracingEnvironmentsPromise, scoreEnvironmentsPromise])+ ).flat();+// Always add default environment to listresults.push({ environment: "default" });diff --git a/web/src/__tests__/server/repositories/environment-repository-events-only.servertest.ts b/web/src/__tests__/server/repositories/environment-repository-events-only.servertest.tsnew file mode 100644index 0000000000..2ab4afe5ce--- /dev/null+++ b/web/src/__tests__/server/repositories/environment-repository-events-only.servertest.ts@@ -0,0 +1,125 @@+/**+ * Events-only write-mode routing for getEnvironmentsForProject.+ *+ * In events_only mode tracing data is written ONLY to the events tables; the+ * legacy traces/observations tables stay empty. The environment filter options+ * must read events_core, otherwise the dropdown only shows environments that+ * appear on scores (which keep their own table in every write mode).+ *+ * The write mode is read from the parsed env at module load, so it is forced+ * via process.env BEFORE any module is imported. Split into its own file+ * because the env is process-wide; the legacy-mode tests live in+ * environment-repository.servertest.ts.+ */+import { vi } from "vitest";++// The events tables are created only by the ClickHouse dev-tables setup (CI's+// "Setup Dev Tables" step), which runs in the default deploy-mode where+// .env.dev.example enables the v4 preview opt-in. The -azure and+// -redis-cluster CI runs skip that setup, so the events tables are absent and+// the reads below would error. Capture the ORIGINAL opt-in flag BEFORE the+// override forces it on.+const eventsTableAvailable = vi.hoisted(() => {+ const enabled =+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "events_only";+ // events_only requires the preview opt-in (web read paths gate on it, and+ // worker/web env validation enforces the pairing).+ process.env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ return enabled;+});++import {+ createEvent,+ createEventsCh,+ createTraceScore,+ createScoresCh,+ getEnvironmentsForProject,+} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";+import { randomUUID } from "crypto";++// Skip on environments without the events dev tables (azure / redis-cluster+// CI). Mirrors the gating used across the other events-table server tests.+const maybe = eventsTableAvailable ? describe : describe.skip;++// At least one always-running test so the file does not hang on the redis+// connections opened by the shared server imports when the events-table tests+// below are skipped via `maybe`.+describe("environment repository (events_only write mode) liveness", () => {+ it("should not hang when the events table is unavailable", () => {});+});++maybe("environment repository (events_only write mode)", () => {+ // Sanity check that the forced write mode reached the parsed shared env that+ // getEnvironmentsForProject routes on. If this ever regresses, the+ // assertions below would silently read the (empty) legacy tables.+ it("forces events_only write mode", () => {+ expect(env.LANGFUSE_MIGRATION_V4_WRITE_MODE).toBe("events_only");+ });++ it("should return environments from the events table and scores", async () => {+ const projectId = randomUUID();+ const eventEnvironment = randomUUID();+ const scoreEnvironment = randomUUID();++ // events_only deployments write tracing data exclusively to the events+ // tables (events_core is populated from events_full via MV).+ await createEventsCh([+ createEvent({+ project_id: projectId,+ environment: eventEnvironment,+ }),+ ]);+ await createScoresCh([+ createTraceScore({+ project_id: projectId,+ environment: scoreEnvironment,+ }),+ ]);++ const environments = await getEnvironmentsForProject({ projectId });++ expect(environments).toEqual(+ expect.arrayContaining([+ { environment: eventEnvironment },+ { environment: scoreEnvironment },+ { environment: "default" },+ ]),+ );+ expect(environments).toHaveLength(3);+ });++ it("should respect fromTimestamp on the events table read", async () => {+ const projectId = randomUUID();+ const oldEnvironment = randomUUID();+ const recentEnvironment = randomUUID();+ const now = Date.now();++ await createEventsCh([+ createEvent({+ project_id: projectId,+ environment: oldEnvironment,+ start_time: (now - 10 * 24 * 60 * 60 * 1000) * 1000, // micros+ }),+ createEvent({+ project_id: projectId,+ environment: recentEnvironment,+ start_time: now * 1000, // micros+ }),+ ]);++ const environments = await getEnvironmentsForProject({+ projectId,+ fromTimestamp: new Date(now - 24 * 60 * 60 * 1000),+ });++ expect(environments).toEqual(+ expect.arrayContaining([+ { environment: recentEnvironment },+ { environment: "default" },+ ]),+ );+ expect(environments).toHaveLength(2);+ });+});diff --git a/web/src/__tests__/server/repositories/environment-repository.servertest.ts b/web/src/__tests__/server/repositories/environment-repository.servertest.tsindex e5c1f7c560..0cde2ec2cc 100644--- a/web/src/__tests__/server/repositories/environment-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/environment-repository.servertest.ts@@ -1,11 +1,30 @@+/**+ * Legacy write-mode coverage for getEnvironmentsForProject: reads come from+ * the legacy traces/observations tables. The write mode is read from the+ * parsed env at module load, so it is forced via process.env BEFORE any module+ * is imported — the dev/CI default is dual, which would route the read to the+ * events tables instead. The events_only tests live in+ * environment-repository-events-only.servertest.ts.+ */+import { vi } from "vitest";++vi.hoisted(() => {+ process.env.LANGFUSE_MIGRATION_V4_WRITE_MODE = "legacy";+});+import {createTracesCh,createTrace,getEnvironmentsForProject,} from "@langfuse/shared/src/server";+import { env } from "@langfuse/shared/src/env";import { randomUUID } from "crypto";describe("Clickhouse Project Repository Test", () => {+ it("forces legacy write mode", () => {+ expect(env.LANGFUSE_MIGRATION_V4_WRITE_MODE).toBe("legacy");+ });+it("should return default if no environments are found", async () => {const projectId = randomUUID();const environments = await getEnvironmentsForProject({ projectId });