🪢 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: create virtual timestamp column in AMT query to support all filters (#7676)
Steffen Schmitz43fc305d5b00
diff --git a/.cursor/rules/tests.mdc b/.cursor/rules/tests.mdcnew file mode 100644index 0000000000..3f0dd71d6e--- /dev/null+++ b/.cursor/rules/tests.mdc@@ -0,0 +1,9 @@+---+description:+globs:+alwaysApply: true+---+# Writing tests++- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.+- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.\ No newline at end of filediff --git a/AGENTS.md b/AGENTS.mdindex b9df02d38e..1843ab476f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -8,6 +8,8 @@ Langfuse is an **open source LLM engineering** platform for developing, monitori## Tests- Codex cannot run the test suite because it depends on Docker-based infrastructure that is unavailable in this environment.+- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.+- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.## Cursor Rules- Additional folder-specific rules live in `.cursor/rules/`.diff --git a/CLAUDE.md b/CLAUDE.mdindex 5e1f2017f1..04b23f311a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -152,6 +152,8 @@ pnpm run nuke # Remove all node_modules, build files, wipe database- Jest for API tests, Playwright for E2E tests- For backend/API changes, tests must pass before pushes- Add tests for new API endpoints and features+- When writing tests, focus on decoupling each `it` or `test` block to ensure that they can run independently and concurrently. Tests must never depend on the action or outcome of previous or subsequent tests.+- When writing tests, especially in the __tests__/async directory, ensure that you avoid `pruneDatabase` calls.### Code Conventions- **Pages Router** (not App Router)diff --git a/packages/shared/src/server/clickhouse/measureAndReturn.ts b/packages/shared/src/server/clickhouse/measureAndReturn.tsindex 7076e5cd57..6452be0b60 100644--- a/packages/shared/src/server/clickhouse/measureAndReturn.ts+++ b/packages/shared/src/server/clickhouse/measureAndReturn.ts@@ -12,7 +12,10 @@ const executionWrapper = async <T, Y>(const startTime = Date.now();const res = await fn(input);const duration = Date.now() - startTime;- span?.setAttribute(`${attributePrefix}-duration`, duration);+ span?.setAttribute(+ `langfuse.experiment.amts.${attributePrefix}-duration`,+ duration,+ );return [res, duration];};@@ -35,7 +38,7 @@ export const measureAndReturn = async <T, Y>(args: {env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES !=="true") {- currentSpan.setAttribute(`run-experiment`, "disabled");+ currentSpan.setAttribute(`langfuse.experiment.amts.run`, "disabled");return existingExecution(input);}@@ -46,11 +49,11 @@ export const measureAndReturn = async <T, Y>(args: {) &&Math.random() > env.LANGFUSE_EXPERIMENT_SAMPLING_RATE) {- currentSpan.setAttribute(`run-experiment`, "sampled-out");+ currentSpan.setAttribute(`langfuse.experiment.amts.run`, "sampled-out");return existingExecution(input);}- currentSpan.setAttribute(`run-experiment`, "true");+ currentSpan.setAttribute(`langfuse.experiment.amts.run`, "true");try {const [[existingResult, existingDuration], [newResult, newDuration]] =@@ -61,7 +64,7 @@ export const measureAndReturn = async <T, Y>(args: {// Positive duration difference means new is fasterconst durationDifference = existingDuration - newDuration;currentSpan?.setAttribute(- "execution-time-difference",+ "langfuse.experiment.amts.execution-time-difference",durationDifference,);@@ -71,10 +74,13 @@ export const measureAndReturn = async <T, Y>(args: {)) {currentSpan?.setAttribute(- "existing-result",+ "langfuse.experiment.amts.existing-result",JSON.stringify(existingResult),);- currentSpan?.setAttribute("new-result", JSON.stringify(newResult));+ currentSpan?.setAttribute(+ "langfuse.experiment.amts.new-result",+ JSON.stringify(newResult),+ );}return env.LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT === "true"diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 3c3fc88a64..e2b88b8a31 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -196,12 +196,13 @@ export const checkTraceExists = async ({${observations_cte}SELECTt.id as id,- t.project_id as project_id+ t.project_id as project_id,+ -- Add a timestamp alias to ensure we can filter on it+ t.start_time as timestampFROM ${traceAmt} t${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}WHERE ${tracesFilterRes.query}AND t.project_id = {projectId: String}- GROUP BY t.id, t.project_id`;const rows = await queryClickhouse<{ id: string; project_id: string }>({diff --git a/packages/shared/src/server/test-utils/clickhouse-helpers.ts b/packages/shared/src/server/test-utils/clickhouse-helpers.tsindex 728f5fe101..e4726862d8 100644--- a/packages/shared/src/server/test-utils/clickhouse-helpers.ts+++ b/packages/shared/src/server/test-utils/clickhouse-helpers.ts@@ -11,7 +11,7 @@ export const createTracesCh = async (trace: TraceRecordInsertType[]) => {if (env.LANGFUSE_EXPERIMENT_COMPARE_READ_FROM_AGGREGATING_MERGE_TREES === "true") {- return await clickhouseClient().insert({+ await clickhouseClient().insert({table: "traces_mt",format: "JSONEachRow",values: trace.map(convertTraceToTraceMt),diff --git a/web/src/__tests__/async/observations-trpc.servertest.ts b/web/src/__tests__/async/observations-trpc.servertest.tsindex 4f635eaf63..b7dae5ae11 100644--- a/web/src/__tests__/async/observations-trpc.servertest.ts+++ b/web/src/__tests__/async/observations-trpc.servertest.ts@@ -2,7 +2,6 @@/* eslint-disable @typescript-eslint/no-unsafe-member-access */import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -19,8 +18,6 @@ import { randomUUID } from "crypto";describe("traces trpc", () => {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- beforeEach(async () => await pruneDatabase());-const session: Session = {expires: "1",user: {@@ -34,6 +31,7 @@ describe("traces trpc", () => {role: "OWNER",plan: "cloud:hobby",cloudConfig: undefined,+ metadata: {},projects: [{id: projectId,@@ -41,6 +39,7 @@ describe("traces trpc", () => {retentionDays: 30,deletedAt: null,name: "Test Project",+ metadata: {},},],},diff --git a/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/async/organizations-api-key-trpc.servertest.tsindex 47dce859e7..ddaebea30e 100644--- a/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/async/organizations-api-key-trpc.servertest.ts@@ -2,7 +2,6 @@/* eslint-disable @typescript-eslint/no-unsafe-member-access */import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -11,8 +10,6 @@ import { TRPCError } from "@trpc/server";describe("organization API keys trpc", () => {const organizationId = "seed-org-id";- beforeEach(async () => await pruneDatabase());-const ownerSession: Session = {expires: "1",user: {diff --git a/web/src/__tests__/async/repositories/observation-repository.servertest.ts b/web/src/__tests__/async/repositories/observation-repository.servertest.tsindex 5b260ccac3..5a41ec448c 100644--- a/web/src/__tests__/async/repositories/observation-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/observation-repository.servertest.ts@@ -2,7 +2,6 @@ import {createObservation,createObservationsCh,} from "@langfuse/shared/src/server";-import { pruneDatabase } from "@/src/__tests__/test-utils";import {getObservationById,getObservationsForTrace,@@ -12,10 +11,6 @@ import { v4 } from "uuid";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";describe("Clickhouse Observations Repository Test", () => {- beforeEach(async () => {- await pruneDatabase();- });-it("should throw if no observations are found", async () => {await expect(getObservationById({diff --git a/web/src/__tests__/async/repositories/score-repository.servertest.ts b/web/src/__tests__/async/repositories/score-repository.servertest.tsindex 015fb26da4..ac4b0fbf6d 100644--- a/web/src/__tests__/async/repositories/score-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/score-repository.servertest.ts@@ -1,13 +1,8 @@import { createScoresCh, getScoreById } from "@langfuse/shared/src/server";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { v4 } from "uuid";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";describe("Clickhouse Scores Repository Test", () => {- beforeEach(async () => {- await pruneDatabase();- });-it("should return null if no scores are found", async () => {const result = await getScoreById({projectId,diff --git a/web/src/__tests__/async/repositories/trace-repository.servertest.ts b/web/src/__tests__/async/repositories/trace-repository.servertest.tsindex cee983761e..444e02fcfe 100644--- a/web/src/__tests__/async/repositories/trace-repository.servertest.ts+++ b/web/src/__tests__/async/repositories/trace-repository.servertest.ts@@ -1,5 +1,4 @@import { checkTraceExists, createTracesCh } from "@langfuse/shared/src/server";-import { pruneDatabase } from "@/src/__tests__/test-utils";import {getTraceById,getTracesBySessionId,@@ -11,10 +10,6 @@ import { createObservationsCh } from "@langfuse/shared/src/server";const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";describe("Clickhouse Traces Repository Test", () => {- beforeEach(async () => {- await pruneDatabase();- });-it("should throw if no traces are found", async () => {expect(await getTraceById({ traceId: v4(), projectId: v4() }),@@ -386,4 +381,35 @@ describe("Clickhouse Traces Repository Test", () => {});expect(exists).toBe(true);});++ it("should handle timestamp filter in checkTraceExists", async () => {+ const traceId = v4();+ const trace = createTrace({+ id: traceId,+ user_id: "user-1",+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ metadata: { key: "value" },+ release: "1.0.0",+ version: "2.0.0",+ timestamp: Date.now(),+ });++ await createTracesCh([trace]);++ const exists = await checkTraceExists({+ projectId,+ traceId,+ timestamp: new Date(),+ filter: [+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: new Date(Date.now() - 3600000),+ },+ ],+ maxTimeStamp: undefined,+ });+ expect(exists).toBe(true);+ });});diff --git a/web/src/__tests__/async/sessions-trpc.servertest.ts b/web/src/__tests__/async/sessions-trpc.servertest.tsindex 6dba69d5c3..c5d81afe9e 100644--- a/web/src/__tests__/async/sessions-trpc.servertest.ts+++ b/web/src/__tests__/async/sessions-trpc.servertest.ts@@ -2,7 +2,6 @@/* eslint-disable @typescript-eslint/no-unsafe-member-access */import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -17,8 +16,6 @@ import { randomUUID } from "crypto";describe("traces trpc", () => {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- beforeEach(async () => await pruneDatabase());-const session: Session = {expires: "1",user: {diff --git a/web/src/__tests__/async/traces-trpc.servertest.ts b/web/src/__tests__/async/traces-trpc.servertest.tsindex ebd9d2f36f..8d3d2a063b 100644--- a/web/src/__tests__/async/traces-trpc.servertest.ts+++ b/web/src/__tests__/async/traces-trpc.servertest.ts@@ -2,7 +2,6 @@/* eslint-disable @typescript-eslint/no-unsafe-member-access */import type { Session } from "next-auth";-import { pruneDatabase } from "@/src/__tests__/test-utils";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -17,8 +16,6 @@ import { randomUUID } from "crypto";describe("traces trpc", () => {const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";- beforeEach(async () => await pruneDatabase());-const session: Session = {expires: "1",user: {