🪢 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(filters): add comment filtering to traces, sessions, and observations (#10629)
Michael Fröhlich10c32f2f1493
diff --git a/packages/shared/prisma/migrations/20251126000000_add_comment_search_indexes/migration.sql b/packages/shared/prisma/migrations/20251126000000_add_comment_search_indexes/migration.sqlnew file mode 100644index 0000000000..1135af215d--- /dev/null+++ b/packages/shared/prisma/migrations/20251126000000_add_comment_search_indexes/migration.sql@@ -0,0 +1,5 @@+-- Full-text search index for comment content filtering+-- This enables efficient text search queries on comment content+-- Uses PostgreSQL's built-in full-text search with GIN index+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comments_content_gin+ON comments USING gin(to_tsvector('english', content));diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsindex 178ac64719..535bdeecd8 100644--- a/packages/shared/src/eventsTable.ts+++ b/packages/shared/src/eventsTable.ts@@ -3,6 +3,13 @@ import { type ColumnDefinition } from "./tableDefinitions";// Column definitions for the ClickHouse events table// Used for filtering, sorting, and mapping UI columns to ClickHouse columnsexport const eventsTableCols: ColumnDefinition[] = [+ {+ name: "ID",+ id: "id",+ type: "stringOptions",+ internal: "e.span_id",+ options: [], // to be added at runtime+ },{name: "Trace ID",id: "traceId",@@ -216,4 +223,16 @@ export const eventsTableCols: ColumnDefinition[] = [options: [], // to be added at runtimenullable: true,},+ {+ name: "Comment Count",+ id: "commentCount",+ type: "number",+ internal: "", // handled by comment filter helpers+ },+ {+ name: "Comment Content",+ id: "commentContent",+ type: "string",+ internal: "", // handled by comment filter helpers+ },];diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.tsindex 28b9226f27..32d3771e45 100644--- a/packages/shared/src/observationsTable.ts+++ b/packages/shared/src/observationsTable.ts@@ -11,8 +11,10 @@ export const observationsTableCols: ColumnDefinition[] = [{name: "ID",id: "id",- type: "string",+ // stringOptions type needed for comment filtering to inject "any of" filter with matching object IDs+ type: "stringOptions",internal: 'o."id"',+ options: [], // to be added at runtime},{name: "Name",@@ -218,6 +220,18 @@ export const observationsTableCols: ColumnDefinition[] = [internal: "t.tags",options: [], // to be added at runtime},+ {+ name: "Comment Count",+ id: "commentCount",+ type: "number",+ internal: "", // handled by comment filter helpers+ },+ {+ name: "Comment Content",+ id: "commentContent",+ type: "string",+ internal: "", // handled by comment filter helpers+ },];// to be used client side, insert options for use in filter-builderdiff --git a/packages/shared/src/server/repositories/comments.ts b/packages/shared/src/server/repositories/comments.tsnew file mode 100644index 0000000000..e456505500--- /dev/null+++ b/packages/shared/src/server/repositories/comments.ts@@ -0,0 +1,175 @@+import type { PrismaClient } from "../../db";+import { Prisma } from "../../db";+import { filterOperators } from "../../interfaces/filters";++/**+ * Supported object types for comment filtering+ */+export type CommentObjectType = "TRACE" | "OBSERVATION" | "SESSION" | "PROMPT";++/**+ * Operators for comment count filters.+ * Extends filterOperators.number with "!=" for additional filtering capability.+ */+export type CommentCountOperator =+ | (typeof filterOperators.number)[number]+ | "!=";++/**+ * Operators for comment content filters.+ * Uses the same operators as filterOperators.string.+ */+export type CommentContentOperator = (typeof filterOperators.string)[number];++/**+ * Query PostgreSQL for object IDs that have a specific number of comments.+ * Uses GROUP BY + HAVING to efficiently filter by comment count.+ *+ * @example+ * // Get traces with >= 3 comments+ * await getObjectIdsByCommentCount({+ * prisma,+ * projectId: "abc123",+ * objectType: "TRACE",+ * operator: ">=",+ * value: 3+ * });+ */+export async function getObjectIdsByCommentCount({+ prisma,+ projectId,+ objectType,+ operator,+ value,+}: {+ prisma: PrismaClient;+ projectId: string;+ objectType: CommentObjectType;+ operator: CommentCountOperator;+ value: number;+}): Promise<string[]> {+ // Validate operator to prevent SQL injection+ const validOperators: CommentCountOperator[] = [+ ">=",+ "<=",+ "=",+ ">",+ "<",+ "!=",+ ];+ if (!validOperators.includes(operator)) {+ throw new Error(`Invalid operator: ${operator}`);+ }++ const rawQuery = Prisma.sql`+ SELECT object_id+ FROM comments+ WHERE project_id = ${projectId} AND object_type = ${objectType}::"CommentObjectType"+ GROUP BY object_id+ HAVING COUNT(*) ${Prisma.raw(operator)} ${value}+ `;++ const results = await prisma.$queryRaw<{ object_id: string }[]>(rawQuery);+ return results.map((r) => r.object_id);+}++/**+ * Query PostgreSQL for object IDs where comments match a text search query.+ * Uses PostgreSQL's full-text search with GIN index for "contains" operator.+ * Falls back to ILIKE for other operators.+ *+ * @example+ * // Get traces with comments containing "bug"+ * await getObjectIdsByCommentContent({+ * prisma,+ * projectId: "abc123",+ * objectType: "TRACE",+ * searchQuery: "bug",+ * operator: "contains"+ * });+ */+export async function getObjectIdsByCommentContent({+ prisma,+ projectId,+ objectType,+ searchQuery,+ operator = "contains",+}: {+ prisma: PrismaClient;+ projectId: string;+ objectType: CommentObjectType;+ searchQuery: string;+ operator?: CommentContentOperator;+}): Promise<string[]> {+ if (operator === "contains") {+ // Use full-text search with GIN index for best performance+ // plainto_tsquery() automatically sanitizes special characters and handles tokenization+ const trimmedQuery = searchQuery.trim();++ if (!trimmedQuery) {+ return [];+ }++ const rawResults = await prisma.$queryRaw<{ object_id: string }[]>`+ SELECT DISTINCT object_id+ FROM comments+ WHERE project_id = ${projectId}+ AND object_type = ${objectType}::"CommentObjectType"+ AND to_tsvector('english', content) @@ plainto_tsquery('english', ${trimmedQuery})+ `;++ return rawResults.map((r) => r.object_id);+ }++ // For other operators, use Prisma's query builder with ILIKE+ let whereCondition: Prisma.CommentWhereInput;++ if (operator === "does not contain") {+ whereCondition = {+ projectId,+ objectType,+ NOT: {+ content: {+ contains: searchQuery,+ mode: "insensitive",+ },+ },+ };+ } else if (operator === "starts with") {+ whereCondition = {+ projectId,+ objectType,+ content: {+ startsWith: searchQuery,+ mode: "insensitive",+ },+ };+ } else if (operator === "ends with") {+ whereCondition = {+ projectId,+ objectType,+ content: {+ endsWith: searchQuery,+ mode: "insensitive",+ },+ };+ } else {+ // Default to contains (for "=" operator which maps to exact match in string filters)+ whereCondition = {+ projectId,+ objectType,+ content: {+ contains: searchQuery,+ mode: "insensitive",+ },+ };+ }++ const comments = await prisma.comment.findMany({+ where: whereCondition,+ select: { objectId: true },+ distinct: ["objectId"],+ });++ return comments.map((c) => c.objectId);+}diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.tsindex 0012e4bbe2..996d64fcef 100644--- a/packages/shared/src/server/repositories/index.ts+++ b/packages/shared/src/server/repositories/index.ts@@ -16,3 +16,4 @@ export * from "./environments";export * from "./automation-repository";export * from "./dataset-run-items-converters";export * from "./dataset-run-items";+export * from "./comments";diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex ffa1d277db..adb4771a36 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -246,4 +246,16 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [clickhouseTableName: "scores",clickhouseSelect: "s.score_categories",},+ {+ uiTableName: "Comment Count",+ uiTableId: "commentCount",+ clickhouseTableName: "comments",+ clickhouseSelect: "", // handled by comment filter helpers+ },+ {+ uiTableName: "Comment Content",+ uiTableId: "commentContent",+ clickhouseTableName: "comments",+ clickhouseSelect: "", // handled by comment filter helpers+ },];diff --git a/packages/shared/src/tableDefinitions/promptsTable.ts b/packages/shared/src/tableDefinitions/promptsTable.tsindex 7c56fdd373..6f20ca3805 100644--- a/packages/shared/src/tableDefinitions/promptsTable.ts+++ b/packages/shared/src/tableDefinitions/promptsTable.ts@@ -3,6 +3,12 @@ import { formatColumnOptions } from "./typeHelpers";import { ColumnDefinition, SingleValueOption } from "./types";export const promptsTableCols: ColumnDefinition[] = [+ {+ name: "ID",+ id: "id",+ type: "string",+ internal: 'p."id"',+ },{name: "Name",id: "name",diff --git a/packages/shared/src/tableDefinitions/sessionsView.ts b/packages/shared/src/tableDefinitions/sessionsView.tsindex 3af22864da..26ab0a913f 100644--- a/packages/shared/src/tableDefinitions/sessionsView.ts+++ b/packages/shared/src/tableDefinitions/sessionsView.ts@@ -110,6 +110,18 @@ export const sessionsViewCols: ColumnDefinition[] = [options: [], // to be added at runtimenullable: true,},+ {+ name: "Comment Count",+ id: "commentCount",+ type: "number",+ internal: "", // handled by comment filter helpers+ },+ {+ name: "Comment Content",+ id: "commentContent",+ type: "string",+ internal: "", // handled by comment filter helpers+ },];export type SessionOptions = {diff --git a/packages/shared/src/tableDefinitions/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.tsindex 17f41aa780..d81cb15d9d 100644--- a/packages/shared/src/tableDefinitions/tracesTable.ts+++ b/packages/shared/src/tableDefinitions/tracesTable.ts@@ -184,6 +184,18 @@ export const tracesTableCols: ColumnDefinition[] = [internal: '"calculatedTotalCost"',nullable: true,},+ {+ name: "Comment Count",+ id: "commentCount",+ type: "number",+ internal: "", // handled by comment filter helpers+ },+ {+ name: "Comment Content",+ id: "commentContent",+ type: "string",+ internal: "", // handled by comment filter helpers+ },];export const datasetCol: ColumnDefinition = {diff --git a/web/src/__tests__/async/observations-comment-filter.servertest.ts b/web/src/__tests__/async/observations-comment-filter.servertest.tsnew file mode 100644index 0000000000..a797d7354a--- /dev/null+++ b/web/src/__tests__/async/observations-comment-filter.servertest.ts@@ -0,0 +1,497 @@+/** @jest-environment node */++import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ createTrace,+ createTracesCh,+ createObservation,+ createObservationsCh,+ createEvent,+ createEventsCh,+} from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";+import { env } from "@/src/env.mjs";++describe("Observations Comment Filtering", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+ const useEventsTable =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Helper to create observation data in the appropriate format+ const createObservationData = (data: {+ id: string;+ project_id: string;+ trace_id: string;+ type: string;+ }) => {+ if (useEventsTable) {+ return createEvent({+ ...data,+ span_id: data.id,+ });+ } else {+ return createObservation(data);+ }+ };++ // Helper to insert observations into the correct table+ const insertObservations = async (observations: any[]) => {+ if (useEventsTable) {+ await createEventsCh(observations);+ } else {+ await createObservationsCh(observations);+ }+ };++ // Helper to create standard query params+ const createQueryParams = (filter: any[]) => ({+ projectId,+ filter,+ searchQuery: null,+ searchType: [] as any[],+ orderBy: null as any,+ page: 0,+ limit: 10,+ });++ describe("Comment Count Filter", () => {+ it("should filter observations with >= 2 comments", async () => {+ // Create traces and observations+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1, trace2]);++ const observation1Id = randomUUID();+ const observation2Id = randomUUID();++ const observation1 = createObservationData({+ id: observation1Id,+ project_id: projectId,+ trace_id: trace1.id,+ type: "GENERATION",+ });+ const observation2 = createObservationData({+ id: observation2Id,+ project_id: projectId,+ trace_id: trace2.id,+ type: "GENERATION",+ });+ await insertObservations([observation1, observation2]);++ // Add 2 comments to observation1+ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "OBSERVATION",+ objectId: observation1Id,+ content: "First comment",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "OBSERVATION",+ objectId: observation1Id,+ content: "Second comment",+ authorUserId: "user-1",+ },+ ],+ });++ // Add 1 comment to observation2+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observation2Id,+ content: "Only one comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ ]),+ );++ // Should get observation1 (has >= 2 comments)+ const observationIds = result.generations.map((o) => o.id);+ expect(observationIds).toContain(observation1Id);+ // observation2 has only 1 comment, should not be included+ expect(observationIds).not.toContain(observation2Id);+ });+ });++ describe("Comment Content Filter", () => {+ it("should filter observations by comment content (contains)", async () => {+ // Create traces and observations+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1, trace2]);++ const observation1Id = randomUUID();+ const observation2Id = randomUUID();++ const observation1 = createObservationData({+ id: observation1Id,+ project_id: projectId,+ trace_id: trace1.id,+ type: "GENERATION",+ });+ const observation2 = createObservationData({+ id: observation2Id,+ project_id: projectId,+ trace_id: trace2.id,+ type: "GENERATION",+ });+ await insertObservations([observation1, observation2]);++ // Add comments with different content+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observation1Id,+ content: "This observation has a bug in the output",+ authorUserId: "user-1",+ },+ });++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observation2Id,+ content: "Observation works perfectly",+ authorUserId: "user-1",+ },+ });++ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ]),+ );++ const observationIds = result.generations.map((o) => o.id);+ expect(observationIds).toContain(observation1Id);+ expect(observationIds).not.toContain(observation2Id);+ });+ });++ describe("Combined Filters (AND Logic)", () => {+ it("should combine comment count + content filters", async () => {+ // Create trace and observation+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ const observationId = randomUUID();+ const observation = createObservationData({+ id: observationId,+ project_id: projectId,+ trace_id: trace.id,+ type: "GENERATION",+ });+ await insertObservations([observation]);++ // Add 2 comments with "bug" in content+ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Found a bug here",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Confirmed the bug",+ authorUserId: "user-1",+ },+ ],+ });++ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ]),+ );++ const observationIds = result.generations.map((o) => o.id);+ expect(observationIds).toContain(observationId);+ });+ });++ describe("Count Query", () => {+ it("should return correct count with comment filter", async () => {+ // Create trace and observation+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ const observationId = randomUUID();+ const observation = createObservationData({+ id: observationId,+ project_id: projectId,+ trace_id: trace.id,+ type: "GENERATION",+ });+ await insertObservations([observation]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Test comment for counting",+ authorUserId: "user-1",+ },+ });++ const countResult = await caller.generations.countAll({+ projectId,+ filter: [+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ ],+ searchQuery: null,+ searchType: [] as any[],+ orderBy: null as any,+ page: 0,+ limit: 10,+ });++ expect(typeof countResult.totalCount).toBe("number");+ expect(countResult.totalCount).toBeGreaterThan(0);+ });+ });++ describe("Edge Cases", () => {+ it("should handle range filters correctly (>=1 AND <=100)", async () => {+ // Create trace and observation+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ const observationId = randomUUID();+ const observation = createObservationData({+ id: observationId,+ project_id: projectId,+ trace_id: trace.id,+ type: "GENERATION",+ });+ await insertObservations([observation]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Test comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "datetime",+ column: "startTime",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ {+ type: "number",+ column: "commentCount",+ operator: "<=",+ value: 100,+ },+ ]),+ );++ const observationIds = result.generations.map((o) => o.id);+ expect(observationIds).toContain(observationId);+ });++ it("should return empty results when no observations match range", async () => {+ // Create trace and observation+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ const observationId = randomUUID();+ const observation = createObservationData({+ id: observationId,+ project_id: projectId,+ trace_id: trace.id,+ type: "GENERATION",+ });+ await insertObservations([observation]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Test comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 5, // No observation has 5+ comments+ },+ ]),+ );++ expect(result.generations).toEqual([]);+ });++ it("should handle special characters in search query", async () => {+ // Create trace and observation+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ const observationId = randomUUID();+ const observation = createObservationData({+ id: observationId,+ project_id: projectId,+ trace_id: trace.id,+ type: "GENERATION",+ });+ await insertObservations([observation]);++ // Add comment with special characters+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "OBSERVATION",+ objectId: observationId,+ content: "Error: (test & validation) failed!",+ authorUserId: "user-1",+ },+ });++ // Should not throw SQL syntax error with special characters+ const result = await caller.generations.all(+ createQueryParams([+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "test & validation",+ },+ ]),+ );++ const observationIds = result.generations.map((o) => o.id);+ expect(observationIds).toContain(observationId);+ });+ });+});diff --git a/web/src/__tests__/async/sessions-comment-filter.servertest.ts b/web/src/__tests__/async/sessions-comment-filter.servertest.tsnew file mode 100644index 0000000000..ae9aa5a649--- /dev/null+++ b/web/src/__tests__/async/sessions-comment-filter.servertest.ts@@ -0,0 +1,483 @@+/** @jest-environment node */++import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { createTrace, createTracesCh } from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";++describe("Sessions Comment Filtering", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Helper to create standard query params+ const createQueryParams = (filter: any[]) => ({+ projectId,+ filter,+ orderBy: null as any,+ page: 0,+ limit: 10,+ });++ describe("Comment Count Filter", () => {+ it("should filter sessions with >= 2 comments", async () => {+ const sessionId1 = randomUUID();+ const sessionId2 = randomUUID();++ // Create sessions in PostgreSQL+ await prisma.traceSession.createMany({+ data: [+ { id: sessionId1, projectId },+ { id: sessionId2, projectId },+ ],+ });++ // Create traces with session IDs in ClickHouse+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId1,+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId2,+ });+ await createTracesCh([trace1, trace2]);++ // Add 2 comments to session1+ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "SESSION",+ objectId: sessionId1,+ content: "First comment",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "SESSION",+ objectId: sessionId1,+ content: "Second comment",+ authorUserId: "user-1",+ },+ ],+ });++ // Add 1 comment to session2+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId2,+ content: "Only one comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "datetime",+ column: "createdAt",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ ]),+ );++ // Should get session1 (has >= 2 comments)+ const sessionIds = result.sessions.map((s) => s.id);+ expect(sessionIds).toContain(sessionId1);+ // session2 has only 1 comment, should not be included+ expect(sessionIds).not.toContain(sessionId2);+ });+ });++ describe("Comment Content Filter", () => {+ it("should filter sessions by comment content (contains)", async () => {+ const sessionId1 = randomUUID();+ const sessionId2 = randomUUID();++ // Create sessions in PostgreSQL+ await prisma.traceSession.createMany({+ data: [+ { id: sessionId1, projectId },+ { id: sessionId2, projectId },+ ],+ });++ // Create traces with session IDs in ClickHouse+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId1,+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId2,+ });+ await createTracesCh([trace1, trace2]);++ // Add comments with different content+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId1,+ content: "This session has a bug in the authentication flow",+ authorUserId: "user-1",+ },+ });++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId2,+ content: "Session works perfectly",+ authorUserId: "user-1",+ },+ });++ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "datetime",+ column: "createdAt",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ]),+ );++ const sessionIds = result.sessions.map((s) => s.id);+ expect(sessionIds).toContain(sessionId1);+ expect(sessionIds).not.toContain(sessionId2);+ });+ });++ describe("Combined Filters (AND Logic)", () => {+ it("should combine comment count + content filters", async () => {+ const sessionId = randomUUID();++ // Create session in PostgreSQL+ await prisma.traceSession.create({+ data: {+ id: sessionId,+ projectId,+ },+ });++ // Create trace with session ID in ClickHouse+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId,+ });+ await createTracesCh([trace]);++ // Add 2 comments with "bug" in content+ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Found a bug here",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Confirmed the bug",+ authorUserId: "user-1",+ },+ ],+ });++ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "datetime",+ column: "createdAt",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ]),+ );++ const sessionIds = result.sessions.map((s) => s.id);+ expect(sessionIds).toContain(sessionId);+ });+ });++ describe("Count Query", () => {+ it("should return correct count with comment filter", async () => {+ const sessionId = randomUUID();++ // Create session in PostgreSQL+ await prisma.traceSession.create({+ data: {+ id: sessionId,+ projectId,+ },+ });++ // Create trace with session ID in ClickHouse+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId,+ });+ await createTracesCh([trace]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Test comment for counting",+ authorUserId: "user-1",+ },+ });++ const countResult = await caller.sessions.countAll({+ projectId,+ filter: [+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ ],+ orderBy: null as any,+ page: 0,+ limit: 10,+ });++ expect(typeof countResult.totalCount).toBe("number");+ expect(countResult.totalCount).toBeGreaterThan(0);+ });+ });++ describe("Edge Cases", () => {+ it("should handle range filters correctly (>=1 AND <=100)", async () => {+ const sessionId = randomUUID();++ // Create session in PostgreSQL+ await prisma.traceSession.create({+ data: {+ id: sessionId,+ projectId,+ },+ });++ // Create trace with session ID in ClickHouse+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId,+ });+ await createTracesCh([trace]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Test comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "datetime",+ column: "createdAt",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ {+ type: "number",+ column: "commentCount",+ operator: "<=",+ value: 100,+ },+ ]),+ );++ const sessionIds = result.sessions.map((s) => s.id);+ expect(sessionIds).toContain(sessionId);+ });++ it("should return empty results when no sessions match range", async () => {+ const sessionId = randomUUID();++ // Create session in PostgreSQL+ await prisma.traceSession.create({+ data: {+ id: sessionId,+ projectId,+ },+ });++ // Create trace with session ID in ClickHouse+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId,+ });+ await createTracesCh([trace]);++ // Add comment+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Test comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 5, // No session has 5+ comments+ },+ ]),+ );++ expect(result.sessions).toEqual([]);+ });++ it("should handle special characters in search query", async () => {+ const sessionId = randomUUID();++ // Create session in PostgreSQL+ await prisma.traceSession.create({+ data: {+ id: sessionId,+ projectId,+ },+ });++ // Create trace with session ID in ClickHouse+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ session_id: sessionId,+ });+ await createTracesCh([trace]);++ // Add comment with special characters+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "SESSION",+ objectId: sessionId,+ content: "Error: (test & validation) failed!",+ authorUserId: "user-1",+ },+ });++ // Should not throw SQL syntax error with special characters+ const result = await caller.sessions.all(+ createQueryParams([+ {+ type: "datetime",+ column: "createdAt",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "test & validation",+ },+ ]),+ );++ const sessionIds = result.sessions.map((s) => s.id);+ expect(sessionIds).toContain(sessionId);+ });+ });+});diff --git a/web/src/__tests__/async/traces-comment-filter.servertest.ts b/web/src/__tests__/async/traces-comment-filter.servertest.tsnew file mode 100644index 0000000000..63a3554bfe--- /dev/null+++ b/web/src/__tests__/async/traces-comment-filter.servertest.ts@@ -0,0 +1,507 @@+/** @jest-environment node */++import type { Session } from "next-auth";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { createTrace, createTracesCh } from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";++describe("Traces Comment Filtering", () => {+ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";++ const session: Session = {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: "seed-org-id",+ name: "Test Organization",+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: "Test Project",+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ admin: true,+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ // Helper to create standard query params+ const createQueryParams = (filter: any[]) => ({+ projectId,+ filter,+ searchQuery: null,+ searchType: [] as any[],+ orderBy: null as any,+ page: 0,+ limit: 10,+ });++ describe("Comment Count Filter", () => {+ it("should filter traces with >= 2 comments", async () => {+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1]);++ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "First comment",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "Second comment",+ authorUserId: "user-1",+ },+ ],+ });++ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace2]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace2.id,+ content: "Only one comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(), // Last 5 seconds+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ ]),+ );++ // Should get trace1 (has >= 2 comments)+ const traceIds = result.traces.map((t) => t.id);+ expect(traceIds).toContain(trace1.id);+ // trace2 has only 1 comment, should not be included+ expect(traceIds).not.toContain(trace2.id);+ });+ });++ describe("Comment Content Filter", () => {+ it("should filter traces by comment content (contains)", async () => {+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "This is a bug in the authentication flow",+ authorUserId: "user-1",+ },+ });++ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace2]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace2.id,+ content: "Feature works perfectly",+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(),+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ]),+ );++ const traceIds = result.traces.map((t) => t.id);+ expect(traceIds).toContain(trace1.id);+ expect(traceIds).not.toContain(trace2.id);+ });+ });++ describe("Combined Filters (AND Logic)", () => {+ it("should combine comment count + content filters", async () => {+ const uniqueId = randomUUID();+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1]);++ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: `Found a bug here ${uniqueId}`,+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: `Confirmed the bug ${uniqueId}`,+ authorUserId: "user-1",+ },+ ],+ });++ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: uniqueId,+ },+ ]),+ );++ const traceIds = result.traces.map((t) => t.id);+ expect(traceIds).toContain(trace1.id);+ });+ });++ describe("Count Query", () => {+ it("should return correct count with comment filter", async () => {+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace.id,+ content: "Test comment for counting",+ authorUserId: "user-1",+ },+ });++ const countResult = await caller.traces.countAll({+ projectId,+ filter: [+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ ],+ searchQuery: null,+ searchType: [] as any[],+ orderBy: null as any,+ });++ expect(typeof countResult.totalCount).toBe("number");+ expect(countResult.totalCount).toBeGreaterThan(0);+ });+ });++ describe("Metrics Query", () => {+ it("should filter metrics by comment count", async () => {+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1, trace2]);++ // Add 2 comments to trace1+ await prisma.comment.createMany({+ data: [+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "First comment",+ authorUserId: "user-1",+ },+ {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "Second comment",+ authorUserId: "user-1",+ },+ ],+ });++ // Add 1 comment to trace2+ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace2.id,+ content: "Only one comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.metrics({+ projectId,+ traceIds: [trace1.id, trace2.id],+ filter: [+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 2,+ },+ ],+ });++ // Should only return metrics for trace1 (has >= 2 comments)+ expect(result.length).toBe(1);+ expect(result[0]?.id).toBe(trace1.id);+ });++ it("should filter metrics by comment content", async () => {+ const trace1 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ const trace2 = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace1, trace2]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace1.id,+ content: "Found a bug in authentication",+ authorUserId: "user-1",+ },+ });++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace2.id,+ content: "Everything works fine",+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.metrics({+ projectId,+ traceIds: [trace1.id, trace2.id],+ filter: [+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "bug",+ },+ ],+ });++ // Should only return metrics for trace1 (has comment with "bug")+ expect(result.length).toBe(1);+ expect(result[0]?.id).toBe(trace1.id);+ });+ });++ describe("Edge Cases", () => {+ it("should handle range filters correctly (>=1 AND <=100)", async () => {+ const uniqueId = randomUUID();+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace.id,+ content: `Test comment ${uniqueId}`,+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(),+ },+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: uniqueId,+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 1,+ },+ {+ type: "number",+ column: "commentCount",+ operator: "<=",+ value: 100,+ },+ ]),+ );++ const traceIds = result.traces.map((t) => t.id);+ expect(traceIds).toContain(trace.id);+ });++ it("should return empty results when no traces match range", async () => {+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace.id,+ content: "Test comment",+ authorUserId: "user-1",+ },+ });++ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "datetime",+ column: "timestamp",+ operator: ">=",+ value: new Date(Date.now() - 5000).toISOString(),+ },+ {+ type: "number",+ column: "commentCount",+ operator: ">=",+ value: 5, // No trace has 5+ comments+ },+ ]),+ );++ expect(result.traces).toEqual([]);+ });++ it("should handle special characters in search query", async () => {+ const uniqueId = randomUUID();+ const trace = createTrace({+ project_id: projectId,+ id: randomUUID(),+ });+ await createTracesCh([trace]);++ await prisma.comment.create({+ data: {+ projectId,+ objectType: "TRACE",+ objectId: trace.id,+ content: `Error: (test & validation) failed! ${uniqueId}`,+ authorUserId: "user-1",+ },+ });++ // Should not throw SQL syntax error with special characters+ const result = await caller.traces.all(+ createQueryParams([+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: `test & validation) failed! ${uniqueId}`,+ },+ ]),+ );++ const traceIds = result.traces.map((t) => t.id);+ expect(traceIds).toContain(trace.id);+ });+ });+});diff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsxindex e9737e8221..f38112ef85 100644--- a/web/src/components/BatchExportTableButton.tsx+++ b/web/src/components/BatchExportTableButton.tsx@@ -76,13 +76,15 @@ export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (const getWarningMessage = () => {switch (props.tableName) {case BatchTableNames.Traces:- return "Note: Filters on observation-level columns (Level, Tokens, Cost, Latency) are not included in trace exports. You may receive more data than expected.";+ return "Note: Filters on observation-level columns (Level, Tokens, Cost, Latency) and Comments are not included in trace exports. You may receive more data than expected.";case BatchTableNames.Observations:- return "Note: Filters on trace-level columns (Trace Name, Trace Tags, User ID, Trace Environment) are not included in observation exports. You may receive more data than expected.";+ return "Note: Filters on trace-level columns (Trace Name, Trace Tags, User ID, Trace Environment) and Comments are not included in observation exports. You may receive more data than expected.";+ case BatchTableNames.Sessions:+ return "Note: Filters on Comments are not included in session exports. You may receive more data than expected.";case BatchTableNames.AuditLogs:return "Note: Filters are not applied to audit log exports. All audit logs for this project will be exported.";default:- // Note: for Scores, Sessions, DatasetRunItems, DatasetItems, filters should work as expected+ // Note: for Scores, DatasetRunItems, DatasetItems, filters should work as expectedreturn null;}};diff --git a/web/src/features/comments/server/commentFilterHelpers.ts b/web/src/features/comments/server/commentFilterHelpers.tsnew file mode 100644index 0000000000..80f7680f13--- /dev/null+++ b/web/src/features/comments/server/commentFilterHelpers.ts@@ -0,0 +1,328 @@+import type { PrismaClient } from "@langfuse/shared/src/db";+import { type singleFilter } from "@langfuse/shared";+import {+ type CommentObjectType,+ type CommentCountOperator,+ type CommentContentOperator,+ getObjectIdsByCommentCount,+ getObjectIdsByCommentContent,+} from "@langfuse/shared/src/server";+import { TRPCError } from "@trpc/server";+import type { z } from "zod/v4";++/**+ * Maximum number of object IDs that can be returned from comment filters.+ * This protects ClickHouse from processing excessively large IN clauses.+ * Typical scenarios: 10K comments → 1K-5K distinct object IDs (well under limit)+ */+export const COMMENT_FILTER_THRESHOLD = 50000;++/**+ * Validates that the number of object IDs is within acceptable limits.+ * Throws a user-friendly error if threshold is exceeded.+ */+export function validateObjectIdCount(+ objectIds: string[],+ objectType: CommentObjectType,+): void {+ if (objectIds.length > COMMENT_FILTER_THRESHOLD) {+ const objectTypePlural = objectType.toLowerCase() + "s";+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Comment filter matches ${objectIds.length.toLocaleString()} ${objectTypePlural} (limit: ${COMMENT_FILTER_THRESHOLD.toLocaleString()}). Please add additional filters to narrow your search.`,+ });+ }+}++/**+ * Checks if the comment count filters include items with zero comments.+ * This is true when:+ * - There's no lower bound filter (defaults to >= 0)+ * - The lower bound allows 0 (>= 0, >= negative, or > negative)+ *+ * When true, we need to use exclusion logic instead of inclusion logic,+ * since items with 0 comments don't exist in the comments table.+ */+function filterRangeIncludesZero(+ filters: Array<{ type: string; operator: string; value: number }>,+): boolean {+ const lowerBoundFilters = filters.filter(+ (f) => f.type === "number" && (f.operator === ">=" || f.operator === ">"),+ );++ // No lower bound = includes 0+ if (lowerBoundFilters.length === 0) {+ return true;+ }++ // Check if any lower bound allows 0+ return lowerBoundFilters.some(+ (f) =>+ (f.operator === ">=" && f.value <= 0) ||+ (f.operator === ">" && f.value < 0),+ );+}++/**+ * Processes comment filters from filter state and returns the updated filter state+ * with matching object IDs injected. This abstracts the duplicated logic across+ * all endpoints (traces, sessions, observations).+ *+ * @returns Object with:+ * - filterState: Updated filter state with comment filters replaced by object ID filter+ * - hasNoMatches: true if comment filters were present but matched nothing (caller should return empty result)+ * - matchingIds: The object IDs matching comment filters (null if no comment filters). Useful for+ * cases that need to intersect with another ID list (e.g., metrics endpoint).+ *+ * @example+ * const { filterState, hasNoMatches } = await applyCommentFilters({+ * filterState: input.filter ?? [],+ * prisma: ctx.prisma,+ * projectId: ctx.session.projectId,+ * objectType: "TRACE",+ * });+ *+ * if (hasNoMatches) {+ * return { traces: [] };+ * }+ *+ * // Use filterState directly in query+ */+export async function applyCommentFilters({+ filterState,+ prisma,+ projectId,+ objectType,+ idColumn = "id",+}: {+ filterState: z.infer<typeof singleFilter>[];+ prisma: PrismaClient;+ projectId: string;+ objectType: CommentObjectType;+ idColumn?: string;+}): Promise<{+ filterState: z.infer<typeof singleFilter>[];+ hasNoMatches: boolean;+ matchingIds: string[] | null;+}> {+ // Extract comment filters from filterState+ const commentCountFilters = filterState.filter(+ (f) =>+ (f.type === "number" || f.type === "datetime") &&+ f.column === "commentCount",+ );+ const commentContentFilter = filterState.find(+ (f) => f.type === "string" && f.column === "commentContent",+ );++ // If no comment filters, return original filter state+ if (commentCountFilters.length === 0 && !commentContentFilter) {+ return {+ filterState,+ hasNoMatches: false,+ matchingIds: null,+ };+ }++ let objectIdsFromComments: string[] = [];+ const hasCommentCountFilters = commentCountFilters.length > 0;++ // Remove comment filters from filterState+ const updatedFilterState = filterState.filter(+ (f) =>+ !(+ ((f.type === "number" || f.type === "datetime") &&+ f.column === "commentCount") ||+ (f.type === "string" && f.column === "commentContent")+ ),+ );++ // Handle comment count filters (may be multiple for ranges like >= 1 AND <= 100)+ if (commentCountFilters.length > 0) {+ // Check if the filter range includes zero-comment items+ // e.g., >= 0, <= 100, or >= 0 AND <= 100 all include items with 0 comments+ const numberFilters = commentCountFilters+ .filter((f) => f.type === "number")+ .map((f) => ({+ type: f.type,+ operator: f.operator,+ value: (f as { value: number }).value,+ }));++ if (filterRangeIncludesZero(numberFilters)) {+ // When range includes zero, use EXCLUSION logic instead of inclusion+ // Find the upper bound filter (if any)+ const upperBoundFilter = numberFilters.find(+ (f) => f.operator === "<=" || f.operator === "<",+ );++ if (!upperBoundFilter) {+ // No upper bound + includes zero = match everything, skip comment count filter+ // But still process content filter if present+ if (!commentContentFilter) {+ return {+ filterState: updatedFilterState,+ hasNoMatches: false,+ matchingIds: null,+ };+ }+ // Continue to content filter handling below+ } else {+ // Get IDs that EXCEED the upper bound (to exclude them)+ const excludeOperator = upperBoundFilter.operator === "<=" ? ">" : ">=";+ const idsToExclude = await getObjectIdsByCommentCount({+ prisma,+ projectId,+ objectType,+ operator: excludeOperator as CommentCountOperator,+ value: upperBoundFilter.value,+ });++ validateObjectIdCount(idsToExclude, objectType);++ // Handle content filter intersection if present+ if (commentContentFilter && commentContentFilter.type === "string") {+ const contentObjectIds = await getObjectIdsByCommentContent({+ prisma,+ projectId,+ objectType,+ searchQuery: commentContentFilter.value,+ operator: commentContentFilter.operator as CommentContentOperator,+ });++ validateObjectIdCount(contentObjectIds, objectType);++ // For content filter with zero-inclusive count filter:+ // Include items matching content AND not exceeding upper bound+ // This is complex - items with matching content that have 0 comments+ // won't be in contentObjectIds (they have no comments to search)+ // So we can only return items that HAVE comments matching content+ // and also don't exceed the upper bound+ const matchingIds = contentObjectIds.filter(+ (id) => !idsToExclude.includes(id),+ );++ if (matchingIds.length === 0) {+ return {+ filterState: updatedFilterState,+ hasNoMatches: true,+ matchingIds: [],+ };+ }++ return {+ filterState: [+ ...updatedFilterState,+ {+ type: "stringOptions" as const,+ operator: "any of" as const,+ column: idColumn,+ value: matchingIds,+ },+ ],+ hasNoMatches: false,+ matchingIds,+ };+ }++ // No content filter - just exclude items exceeding upper bound+ if (idsToExclude.length > 0) {+ return {+ filterState: [+ ...updatedFilterState,+ {+ type: "stringOptions" as const,+ operator: "none of" as const,+ column: idColumn,+ value: idsToExclude,+ },+ ],+ hasNoMatches: false,+ matchingIds: null,+ };+ }++ // No items exceed limit, return all (no filter needed)+ return {+ filterState: updatedFilterState,+ hasNoMatches: false,+ matchingIds: null,+ };+ }+ } else {+ // Standard inclusion logic for filters that don't include zero+ // (e.g., >= 1, > 0, = 5, etc.)+ let isFirstCommentCountFilter = true;+ for (const commentCountFilter of commentCountFilters) {+ if (commentCountFilter.type === "number") {+ const filterObjectIds = await getObjectIdsByCommentCount({+ prisma,+ projectId,+ objectType,+ operator: commentCountFilter.operator as CommentCountOperator,+ value: commentCountFilter.value,+ });++ validateObjectIdCount(filterObjectIds, objectType);++ // Intersect with previous results (AND logic for multiple filters)+ if (isFirstCommentCountFilter) {+ objectIdsFromComments = filterObjectIds;+ isFirstCommentCountFilter = false;+ } else {+ objectIdsFromComments = objectIdsFromComments.filter((id) =>+ filterObjectIds.includes(id),+ );+ }+ }+ }+ }+ }++ // Handle comment content filter+ if (commentContentFilter && commentContentFilter.type === "string") {+ const contentObjectIds = await getObjectIdsByCommentContent({+ prisma,+ projectId,+ objectType,+ searchQuery: commentContentFilter.value,+ operator: commentContentFilter.operator as CommentContentOperator,+ });++ validateObjectIdCount(contentObjectIds, objectType);++ // Intersect with comment count results if present+ if (hasCommentCountFilters) {+ // Always intersect if comment count filters were processed+ objectIdsFromComments = objectIdsFromComments.filter((id) =>+ contentObjectIds.includes(id),+ );+ } else {+ objectIdsFromComments = contentObjectIds;+ }+ }++ // If no objects match, signal caller to return empty result+ if (objectIdsFromComments.length === 0) {+ return {+ filterState: updatedFilterState,+ hasNoMatches: true,+ matchingIds: [],+ };+ }++ // Inject matching object IDs as filter+ return {+ filterState: [+ ...updatedFilterState,+ {+ type: "stringOptions" as const,+ operator: "any of" as const,+ column: idColumn,+ value: objectIdsFromComments,+ },+ ],+ hasNoMatches: false,+ matchingIds: objectIdsFromComments,+ };+}diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.tsindex 954c18ac31..c9f8c0aba9 100644--- a/web/src/features/filters/config/observations-config.ts+++ b/web/src/features/filters/config/observations-config.ts@@ -144,5 +144,17 @@ export const observationFilterConfig: FilterConfig = {column: "scores_avg",label: "Numeric Scores",},+ {+ type: "numeric" as const,+ column: "commentCount",+ label: "Comment Count",+ min: 0,+ max: 100,+ },+ {+ type: "string" as const,+ column: "commentContent",+ label: "Comment Content",+ },],};diff --git a/web/src/features/filters/config/sessions-config.ts b/web/src/features/filters/config/sessions-config.tsindex 268c14a905..06f0d38c80 100644--- a/web/src/features/filters/config/sessions-config.ts+++ b/web/src/features/filters/config/sessions-config.ts@@ -115,5 +115,17 @@ export const sessionFilterConfig: FilterConfig = {column: "scores_avg",label: "Numeric Scores",},+ {+ type: "numeric" as const,+ column: "commentCount",+ label: "Comment Count",+ min: 0,+ max: 100,+ },+ {+ type: "string" as const,+ column: "commentContent",+ label: "Comment Content",+ },],};diff --git a/web/src/features/filters/config/traces-config.ts b/web/src/features/filters/config/traces-config.tsindex 8e647b4c7a..8d0789c7e5 100644--- a/web/src/features/filters/config/traces-config.ts+++ b/web/src/features/filters/config/traces-config.ts@@ -56,6 +56,18 @@ export const traceFilterConfig: FilterConfig = {trueLabel: "Bookmarked",falseLabel: "Not bookmarked",},+ {+ type: "numeric" as const,+ column: "commentCount",+ label: "Comment Count",+ min: 0,+ max: 100,+ },+ {+ type: "string" as const,+ column: "commentContent",+ label: "Comment Content",+ },{type: "categorical" as const,column: "tags",diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex 188ee84f8f..d25d229437 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -113,7 +113,7 @@ export const promptRouter = createTRPCRouter({);const filterCondition = tableColumnsToSqlFilterAndPrefix(- input.filter,+ input.filter ?? [],promptsTableCols,"prompts",);@@ -201,13 +201,14 @@ export const promptRouter = createTRPCRouter({scope: "prompts:read",});- const filterCondition = input.filter- ? tableColumnsToSqlFilterAndPrefix(- input.filter,- promptsTableCols,- "prompts",- )- : Prisma.empty;+ const filterCondition =+ input.filter && input.filter.length > 0+ ? tableColumnsToSqlFilterAndPrefix(+ input.filter,+ promptsTableCols,+ "prompts",+ )+ : Prisma.empty;const pathFilter = input.pathPrefix? (() => {diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.tsindex 768e28153d..5712559f9e 100644--- a/web/src/server/api/routers/generations/getAllQueries.ts+++ b/web/src/server/api/routers/generations/getAllQueries.ts@@ -8,6 +8,7 @@ import {getObservationsTableCount,} from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";+import { applyCommentFilters } from "@/src/features/comments/server/commentFilterHelpers";const GetAllGenerationsInput = GenerationTableOptions.extend({...paginationZod,@@ -18,9 +19,23 @@ export type GetAllGenerationsInput = z.infer<typeof GetAllGenerationsInput>;export const getAllQueries = {all: protectedProjectProcedure.input(GetAllGenerationsInput)- .query(async ({ input }) => {+ .query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: input.projectId,+ objectType: "OBSERVATION",+ });++ if (hasNoMatches) {+ return { generations: [] };+ }+const { generations } = await getAllGenerations({- input,+ input: {+ ...input,+ filter: filterState,+ },selectIOAndMetadata: false,});return { generations };@@ -28,9 +43,20 @@ export const getAllQueries = {countAll: protectedProjectProcedure.input(GetAllGenerationsInput).query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: input.projectId,+ objectType: "OBSERVATION",+ });++ if (hasNoMatches) {+ return { totalCount: 0 };+ }+const queryOpts = {projectId: ctx.session.projectId,- filter: input.filter ?? [],+ filter: filterState,limit: 1,offset: 0,};diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 733887748c..01d71bdfed 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -1,6 +1,7 @@import { z } from "zod/v4";import { auditLog } from "@/src/features/audit-logs/auditLog";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { applyCommentFilters } from "@/src/features/comments/server/commentFilterHelpers";import {createTRPCRouter,protectedGetSessionProcedure,@@ -140,9 +141,20 @@ export const sessionRouter = createTRPCRouter({all: protectedProjectProcedure.input(SessionFilterOptions).query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: input.projectId,+ objectType: "SESSION",+ });++ if (hasNoMatches) {+ return { sessions: [] };+ }+const finalFilter = await getPublicSessionsFilter(input.projectId,- input.filter ?? [],+ filterState,);const sessions = await getSessionsTable({projectId: input.projectId,@@ -187,10 +199,21 @@ export const sessionRouter = createTRPCRouter({}),countAll: protectedProjectProcedure.input(SessionFilterOptions)- .query(async ({ input }) => {+ .query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: input.projectId,+ objectType: "SESSION",+ });++ if (hasNoMatches) {+ return { totalCount: 0 };+ }+const finalFilter = await getPublicSessionsFilter(input.projectId,- input.filter ?? [],+ filterState,);const count = await getSessionsTableCount({projectId: input.projectId,diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 199628a607..e0845ec29c 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -2,6 +2,7 @@ import { z } from "zod/v4";import { auditLog } from "@/src/features/audit-logs/auditLog";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";+import { applyCommentFilters } from "@/src/features/comments/server/commentFilterHelpers";import {createTRPCRouter,protectedGetTraceProcedure,@@ -110,9 +111,20 @@ export const traceRouter = createTRPCRouter({all: protectedProjectProcedure.input(TraceFilterOptions).query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: ctx.session.projectId,+ objectType: "TRACE",+ });++ if (hasNoMatches) {+ return { traces: [] };+ }+const traces = await getTracesTable({projectId: ctx.session.projectId,- filter: input.filter ?? [],+ filter: filterState,searchQuery: input.searchQuery ?? undefined,searchType: input.searchType ?? ["id"],orderBy: input.orderBy,@@ -124,9 +136,20 @@ export const traceRouter = createTRPCRouter({countAll: protectedProjectProcedure.input(TraceFilterOptions).query(async ({ input, ctx }) => {+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: ctx.session.projectId,+ objectType: "TRACE",+ });++ if (hasNoMatches) {+ return { totalCount: 0 };+ }+const count = await getTracesTableCount({projectId: ctx.session.projectId,- filter: input.filter ?? [],+ filter: filterState,searchType: input.searchType,searchQuery: input.searchQuery ?? undefined,limit: 1,@@ -147,15 +170,50 @@ export const traceRouter = createTRPCRouter({).query(async ({ input, ctx }) => {if (input.traceIds.length === 0) return [];++ const { filterState, hasNoMatches, matchingIds } =+ await applyCommentFilters({+ filterState: input.filter ?? [],+ prisma: ctx.prisma,+ projectId: ctx.session.projectId,+ objectType: "TRACE",+ });++ if (hasNoMatches) {+ return [];+ }++ // If comment filters returned matching IDs, intersect with input.traceIds+ let filteredTraceIds = input.traceIds;+ if (matchingIds !== null) {+ filteredTraceIds = input.traceIds.filter((id) =>+ matchingIds.includes(id),+ );++ if (filteredTraceIds.length === 0) {+ return [];+ }+ }++ // Remove the comment filter's ID injection and use filteredTraceIds instead+ const filterWithoutCommentIds = filterState.filter(+ (f) =>+ !(+ f.type === "stringOptions" &&+ f.column === "id" &&+ f.operator === "any of"+ ),+ );+const res = await getTracesTableMetrics({projectId: ctx.session.projectId,filter: [- ...(input.filter ?? []),+ ...filterWithoutCommentIds,{type: "stringOptions",operator: "any of",column: "ID",- value: input.traceIds,+ value: filteredTraceIds,},],});