Skip to content

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

feat: create new environment materialized views for quick lookups (#5895)

Steffen Schmitz1e64d97b75f9
diff --git a/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.down.sql b/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.down.sql
new file mode 100644
index 0000000000..0486b8e1db
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.down.sql
@@ -0,0 +1,7 @@
+-- Drop materialized views
+DROP VIEW IF EXISTS project_environments_traces_mv ON CLUSTER default;
+DROP VIEW IF EXISTS project_environments_observations_mv ON CLUSTER default;
+DROP VIEW IF EXISTS project_environments_scores_mv ON CLUSTER default;
+
+-- Drop the project_environments table
+DROP TABLE IF EXISTS project_environments ON CLUSTER default;
diff --git a/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.up.sql b/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.up.sql
new file mode 100644
index 0000000000..6fadd913ec
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0009_add_project_environments.up.sql
@@ -0,0 +1,30 @@
+-- Create the project_environments table with AggregatingMergeTree engine
+CREATE TABLE project_environments ON CLUSTER default (
+ `project_id` String,
+ `environments` SimpleAggregateFunction(groupUniqArrayArray, Array(String))
+) ENGINE = ReplicatedAggregatingMergeTree
+ORDER BY (project_id);
+
+-- Create materialized view for traces
+CREATE MATERIALIZED VIEW project_environments_traces_mv ON CLUSTER default TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM traces
+GROUP BY project_id;
+
+-- Create materialized view for observations
+CREATE MATERIALIZED VIEW project_environments_observations_mv ON CLUSTER default TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM observations
+GROUP BY project_id;
+
+-- Create materialized view for scores
+CREATE MATERIALIZED VIEW project_environments_scores_mv ON CLUSTER default TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM scores
+GROUP BY project_id;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.down.sql b/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.down.sql
new file mode 100644
index 0000000000..a1622de24d
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.down.sql
@@ -0,0 +1,7 @@
+-- Drop materialized views
+DROP VIEW IF EXISTS project_environments_traces_mv;
+DROP VIEW IF EXISTS project_environments_observations_mv;
+DROP VIEW IF EXISTS project_environments_scores_mv;
+
+-- Drop the project_environments table
+DROP TABLE IF EXISTS project_environments;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.up.sql b/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.up.sql
new file mode 100644
index 0000000000..50c55b4690
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0009_add_project_environments.up.sql
@@ -0,0 +1,30 @@
+-- Create the project_environments table with AggregatingMergeTree engine
+CREATE TABLE project_environments (
+ `project_id` String,
+ `environments` SimpleAggregateFunction(groupUniqArrayArray, Array(String))
+) ENGINE = AggregatingMergeTree
+ORDER BY (project_id);
+
+-- Create materialized view for traces
+CREATE MATERIALIZED VIEW project_environments_traces_mv TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM traces
+GROUP BY project_id;
+
+-- Create materialized view for observations
+CREATE MATERIALIZED VIEW project_environments_observations_mv TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM observations
+GROUP BY project_id;
+
+-- Create materialized view for scores
+CREATE MATERIALIZED VIEW project_environments_scores_mv TO project_environments AS
+SELECT
+ project_id,
+ groupUniqArray(environment) AS environments
+FROM scores
+GROUP BY project_id;
diff --git a/packages/shared/src/server/repositories/environments.ts b/packages/shared/src/server/repositories/environments.ts
index 812dfa4f50..ec96d7baf0 100644
--- a/packages/shared/src/server/repositories/environments.ts
+++ b/packages/shared/src/server/repositories/environments.ts
@@ -1,56 +1,36 @@
import { queryClickhouse } from "./clickhouse";
-import { convertDateToClickhouseDateTime } from "../clickhouse/client";
export type EnvironmentFilterProps = {
projectId: string;
- minTimestamp?: Date;
};
-export const getEnvironmentsForProjectAndTimeFilter = async (
+export const getEnvironmentsForProject = async (
props: EnvironmentFilterProps,
-) => {
- const { projectId, minTimestamp } = props;
+): Promise<{ environment: string }[]> => {
+ const { projectId } = props;
const query = `
- with environments as (
- (
- SELECT DISTINCT environment AS environment
- FROM traces t
- WHERE project_id = {projectId: String}
- ${minTimestamp ? `AND timestamp >= {minTimestamp: DateTime64(3)}` : ""}
- LIMIT 100
- ) UNION ALL (
- SELECT DISTINCT environment AS environment
- FROM observations
- WHERE project_id = {projectId: String}
- ${minTimestamp ? `AND start_time >= {minTimestamp: DateTime64(3)}` : ""}
- LIMIT 100
- ) UNION ALL (
- SELECT DISTINCT environment AS environment
- FROM scores
- WHERE project_id = {projectId: String}
- ${minTimestamp ? `AND timestamp >= {minTimestamp: DateTime64(3)}` : ""}
- LIMIT 100
- )
- )
- select distinct environment from environments;
+ SELECT environments
+ FROM project_environments FINAL
+ WHERE project_id = {projectId: String}
`;
- return queryClickhouse<{
- environment: string;
+ const results = await queryClickhouse<{
+ environments: string[];
}>({
- query: query,
- params: {
- projectId: projectId,
- ...(minTimestamp
- ? { minTimestamp: convertDateToClickhouseDateTime(minTimestamp) }
- : {}),
- },
+ query,
+ params: { projectId },
tags: {
feature: "tracing",
type: "environment",
- kind: "analytic",
+ kind: "byId",
projectId,
},
});
+
+ const environments = results.length > 0 ? results[0].environments : [];
+ environments.push("default");
+ return Array.from(new Set(environments)).map((environment) => ({
+ environment,
+ }));
};
diff --git a/web/src/__tests__/async/repositories/environment-repository.servertest.ts b/web/src/__tests__/async/repositories/environment-repository.servertest.ts
new file mode 100644
index 0000000000..e5c1f7c560
--- /dev/null
+++ b/web/src/__tests__/async/repositories/environment-repository.servertest.ts
@@ -0,0 +1,46 @@
+import {
+ createTracesCh,
+ createTrace,
+ getEnvironmentsForProject,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+describe("Clickhouse Project Repository Test", () => {
+ it("should return default if no environments are found", async () => {
+ const projectId = randomUUID();
+ const environments = await getEnvironmentsForProject({ projectId });
+ expect(environments).toHaveLength(1);
+ expect(environments[0].environment).toEqual("default");
+ });
+
+ it("should return environment from project_environments table after new trace was inserted", async () => {
+ const projectId = randomUUID();
+ const environmentId1 = randomUUID();
+ const environmentId2 = randomUUID();
+ await createTracesCh([
+ createTrace({
+ project_id: projectId,
+ environment: environmentId1,
+ }),
+ createTrace({
+ project_id: projectId,
+ environment: environmentId1,
+ }),
+ createTrace({
+ project_id: projectId,
+ environment: environmentId2,
+ }),
+ ]);
+
+ const environments = await getEnvironmentsForProject({ projectId });
+
+ expect(environments).toHaveLength(3);
+ expect(environments).toEqual(
+ expect.arrayContaining([
+ { environment: environmentId1 },
+ { environment: environmentId2 },
+ { environment: "default" },
+ ]),
+ );
+ });
+});
diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.ts
index 230958f38b..b195b7f0e9 100644
--- a/web/src/features/projects/server/projectsRouter.ts
+++ b/web/src/features/projects/server/projectsRouter.ts
@@ -14,10 +14,9 @@ import {
QueueJobs,
redis,
ProjectDeleteQueue,
- getEnvironmentsForProjectAndTimeFilter,
+ getEnvironmentsForProject,
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
-import { timeFilter } from "@langfuse/shared";
export const projectsRouter = createTRPCRouter({
create: protectedOrganizationProcedure
@@ -279,16 +278,6 @@ export const projectsRouter = createTRPCRouter({
}),
environmentFilterOptions: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- timestampFilter: timeFilter.optional(),
- }),
- )
- .query(async ({ input }) => {
- return getEnvironmentsForProjectAndTimeFilter({
- projectId: input.projectId,
- minTimestamp: input.timestampFilter?.value,
- });
- }),
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input }) => getEnvironmentsForProject(input)),
});