🪢 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(events): resolve comment filters for every event stream (#14976)
Valery Meleshkin86b29b2501e2
diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts b/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.tsindex 9abb8f79db..c63ad6380d 100644--- a/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/events-observation-row-selection.ts@@ -1,4 +1,5 @@import { eventsTableCols } from "../../../eventsTable";+import { InvalidRequestError } from "../../../errors";import type { TracingSearchType } from "../../../interfaces/search";import { findUiColumnMapping } from "../../../tableDefinitions";import type { FilterCondition } from "../../../types";@@ -149,6 +150,12 @@ const buildEventsObservationRowSelectionInternal = (} => {const filterGroups = groupEventsObservationFilters(filter);+ if (filterGroups.comments.length > 0) {+ throw new InvalidRequestError(+ "Event comment filters must be resolved before building the ClickHouse row selection.",+ );+ }+const eventsFilter = new FilterList(createFilterFromFilterState(filter ?? [],diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.tsindex 8b37c20e4f..678730a217 100644--- a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts@@ -1,4 +1,5 @@import type { FilterCondition } from "../../../types";+import { InvalidRequestError } from "../../../errors";import { describe, expect, it } from "vitest";import {buildEventsObservationRowSelection,@@ -167,25 +168,6 @@ describe("buildEventsStreamQuery", () => {expect(Object.values(params)).toContain("quality");});-- it("keeps comment filters out of the legacy stream selection", () => {- const { queryBuilder } = buildEventsStreamQuery({- projectId,- filter: [- nativeFilter,- {- column: "commentContent",- operator: "contains",- value: "comment-needle",- type: "string",- },- ],- rowLimit: 7,- });- const { params } = queryBuilder.selectFieldSet("eval").buildWithParams();-- expect(Object.values(params)).not.toContain("comment-needle");- });});describe("buildEventsObservationRowSelection", () => {@@ -275,7 +257,7 @@ describe("buildEventsObservationRowSelection", () => {},);- it("does not silently discard unresolved comment filters", () => {+ it("rejects unresolved comment filters", () => {expect(() =>buildSelection({filter: [@@ -287,6 +269,6 @@ describe("buildEventsObservationRowSelection", () => {},],}),- ).toThrow();+ ).toThrow(InvalidRequestError);});});diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.tsindex 89ec148787..0c2ef65628 100644--- a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts@@ -4,7 +4,6 @@ import type { EventsQueryBuilder } from "./event-query-builder";import {buildEventsObservationRowSelection,buildEventsObservationRowSelectionForBlobExport,- groupEventsObservationFilters,} from "./events-observation-row-selection";export type EventsStreamQueryInput = {@@ -31,8 +30,8 @@ export type EventsBlobExportStreamQuery = EventsStreamQuery & {* select its own row shape. Callers must add a field set or raw selection* before building the query.*- * Score filters are applied by the shared row-selection planner. Unresolved- * comment filters remain excluded until the stream caller resolves them.+ * Score filters are applied by the shared row-selection planner. Comment+ * filters must be resolved to event IDs before reaching this builder.*/const buildEventsStreamQueryInternal = ({@@ -45,12 +44,7 @@ const buildEventsStreamQueryInternal = (}: EventsStreamQueryInput,buildRowSelection: typeof buildEventsObservationRowSelection,): EventsBlobExportStreamQuery => {- const originalFilterGroups = groupEventsObservationFilters(filter);- const filterConditions: FilterCondition[] = [- ...originalFilterGroups.events,- ...originalFilterGroups.observationScores,- ...originalFilterGroups.traceScores,- ];+ const filterConditions: FilterCondition[] = [...(filter ?? [])];if (cutoffCreatedAt) {filterConditions.push({column: "startTime",diff --git a/packages/shared/src/server/services/commentFilterService.test.ts b/packages/shared/src/server/services/commentFilterService.test.tsnew file mode 100644index 0000000000..6b0d1aeea5--- /dev/null+++ b/packages/shared/src/server/services/commentFilterService.test.ts@@ -0,0 +1,194 @@+import type { PrismaClient } from "../../db";+import { InvalidRequestError } from "../../errors";+import { afterEach, describe, expect, it, vi } from "vitest";+import * as commentsRepository from "../repositories/comments";+import {+ applyCommentFilters,+ COMMENT_FILTER_THRESHOLD,+ validateObjectIdCount,+} from "./commentFilterService";++const prisma = {} as PrismaClient;+const commonArgs = {+ projectId: "comment-filter-project",+ objectType: "OBSERVATION" as const,+ prisma,+};++const count = (operator: "=" | ">=" | "<=", value: number) => ({+ type: "number" as const,+ column: "commentCount",+ operator,+ value,+});++const content = (value: string) => ({+ type: "string" as const,+ column: "commentContent",+ operator: "contains" as const,+ value,+});++const idFilter = (operator: "any of" | "none of", value: string[]) => ({+ type: "stringOptions" as const,+ column: "id",+ operator,+ value,+});++const selection = (matchingIds: string[]) => ({+ filterState: [idFilter("any of", matchingIds)],+ hasNoMatches: false,+ matchingIds,+});++const resolve = (+ filterState: Parameters<typeof applyCommentFilters>[0]["filterState"],+) => applyCommentFilters({ filterState, ...commonArgs });++const mockResults = (+ method: "getObjectIdsByCommentCount" | "getObjectIdsByCommentContent",+ ...results: string[][]+) => {+ const mock = vi.spyOn(commentsRepository, method);+ results.forEach((result) => mock.mockResolvedValueOnce(result));+ return mock;+};++afterEach(() => vi.restoreAllMocks());++describe("applyCommentFilters", () => {+ it("treats an unbounded zero-inclusive count filter as a no-op", async () => {+ const countLookup = mockResults("getObjectIdsByCommentCount");++ await expect(resolve([count(">=", 0)])).resolves.toEqual({+ filterState: [],+ hasNoMatches: false,+ matchingIds: null,+ });+ expect(countLookup).not.toHaveBeenCalled();+ });++ it("still applies content when the count predicate is a no-op", async () => {+ const matchingIds = ["matching-observation"];+ mockResults("getObjectIdsByCommentContent", matchingIds);++ await expect(+ resolve([count(">=", 0), content("needs-review")]),+ ).resolves.toEqual(selection(matchingIds));+ });++ it("expresses an exact zero count as an exclusion", async () => {+ const excludedIds = ["commented-observation"];+ const countLookup = mockResults("getObjectIdsByCommentCount", excludedIds);++ await expect(resolve([count("=", 0)])).resolves.toEqual({+ filterState: [idFilter("none of", excludedIds)],+ hasNoMatches: false,+ matchingIds: null,+ });+ expect(countLookup).toHaveBeenCalledExactlyOnceWith({+ ...commonArgs,+ operator: ">",+ value: 0,+ });+ });++ it("uses the tightest zero-inclusive upper bound", async () => {+ const excludedIds = ["observation-above-tightest-bound"];+ const countLookup = mockResults("getObjectIdsByCommentCount", excludedIds);++ await resolve([count("<=", 10), count("<=", 3)]);++ expect(countLookup).toHaveBeenCalledExactlyOnceWith({+ ...commonArgs,+ operator: ">",+ value: 3,+ });+ });++ it.each([+ {+ name: "treats non-zero equality as inclusion",+ filters: [count("=", 1)],+ countResults: [["matching-observation"]],+ contentResults: [],+ },+ {+ name: "intersects equality with content",+ filters: [count("=", 1), content("needs-review")],+ countResults: [["matching-observation", "count-only"]],+ contentResults: [["matching-observation", "content-only"]],+ },+ {+ name: "intersects every content predicate",+ filters: [content("urgent"), content("customer")],+ countResults: [],+ contentResults: [+ ["matching-observation", "first-only"],+ ["matching-observation", "second-only"],+ ],+ },+ {+ name: "intersects every content predicate with a bounded count",+ filters: [count("<=", 1), content("urgent"), content("customer")],+ countResults: [["outside-count-range"]],+ contentResults: [+ ["matching-observation", "first-only", "outside-count-range"],+ ["matching-observation", "second-only"],+ ],+ },+ {+ name: "applies every lower bound even if one includes zero",+ filters: [count(">=", 0), count(">=", 1)],+ countResults: [+ ["matching-observation", "first-only"],+ ["matching-observation"],+ ],+ contentResults: [],+ },+ ])("$name", async ({ filters, countResults, contentResults }) => {+ const countLookup = mockResults(+ "getObjectIdsByCommentCount",+ ...countResults,+ );+ const contentLookup = mockResults(+ "getObjectIdsByCommentContent",+ ...contentResults,+ );++ await expect(resolve(filters)).resolves.toEqual(+ selection(["matching-observation"]),+ );+ expect(countLookup).toHaveBeenCalledTimes(countResults.length);+ expect(contentLookup).toHaveBeenCalledTimes(contentResults.length);+ });++ it("validates the final content-filter intersection", async () => {+ const broadIds = Array.from(+ { length: COMMENT_FILTER_THRESHOLD + 1 },+ (_, index) => `observation-${index}`,+ );+ const matchingIds = [broadIds[0]!];+ mockResults("getObjectIdsByCommentContent", broadIds, matchingIds);++ await expect(+ resolve([content("broad"), content("narrow")]),+ ).resolves.toEqual(selection(matchingIds));+ });+});++describe("validateObjectIdCount", () => {+ it("throws a user-facing InvalidRequestError above the 50,000-ID guard", () => {+ const validate = () =>+ validateObjectIdCount(+ Array<string>(COMMENT_FILTER_THRESHOLD + 1).fill("observation-id"),+ "OBSERVATION",+ );++ expect(validate).toThrow(InvalidRequestError);+ expect(validate).toThrow(+ "Comment filter matches 50,001 observations (limit: 50,000). Please add additional filters to narrow your search.",+ );+ });+});diff --git a/packages/shared/src/server/services/commentFilterService.ts b/packages/shared/src/server/services/commentFilterService.tsindex a84cb4ef98..4770570ae3 100644--- a/packages/shared/src/server/services/commentFilterService.ts+++ b/packages/shared/src/server/services/commentFilterService.ts@@ -1,4 +1,5 @@import type { PrismaClient } from "../../db";+import { InvalidRequestError } from "../../errors";import { type singleFilter } from "../../interfaces/filters";import {type CommentObjectType,@@ -9,6 +10,11 @@ import {} from "../repositories/comments";import type { z } from "zod";+type CommentContentFilter = Extract<+ z.infer<typeof singleFilter>,+ { type: "string" }+>;+/*** Maximum number of object IDs that can be returned from comment filters.* This protects ClickHouse from processing excessively large IN clauses.@@ -26,8 +32,8 @@ export function validateObjectIdCount(): void {if (objectIds.length > COMMENT_FILTER_THRESHOLD) {const objectTypePlural = objectType.toLowerCase() + "s";- throw new Error(- `Comment filter matches ${objectIds.length.toLocaleString()} ${objectTypePlural} (limit: ${COMMENT_FILTER_THRESHOLD.toLocaleString()}). Please add additional filters to narrow your search.`,+ throw new InvalidRequestError(+ `Comment filter matches ${objectIds.length.toLocaleString("en-US")} ${objectTypePlural} (limit: ${COMMENT_FILTER_THRESHOLD.toLocaleString("en-US")}). Please add additional filters to narrow your search.`,);}}@@ -44,6 +50,10 @@ export function validateObjectIdCount(function filterRangeIncludesZero(filters: Array<{ type: string; operator: string; value: number }>,): boolean {+ if (filters.some((f) => f.operator === "=" && f.value !== 0)) {+ return false;+ }+const lowerBoundFilters = filters.filter((f) => f.type === "number" && (f.operator === ">=" || f.operator === ">"),);@@ -53,8 +63,8 @@ function filterRangeIncludesZero(return true;}- // Check if any lower bound allows 0- return lowerBoundFilters.some(+ // Every lower bound must allow 0 because filters are combined with AND.+ return lowerBoundFilters.every((f) =>(f.operator === ">=" && f.value <= 0) ||(f.operator === ">" && f.value < 0),@@ -109,12 +119,13 @@ export async function applyCommentFilters({(f.type === "number" || f.type === "datetime") &&f.column === "commentCount",);- const commentContentFilter = filterState.find(- (f) => f.type === "string" && f.column === "commentContent",+ const commentContentFilters = filterState.filter(+ (f): f is CommentContentFilter =>+ f.type === "string" && f.column === "commentContent",);// If no comment filters, return original filter state- if (commentCountFilters.length === 0 && !commentContentFilter) {+ if (commentCountFilters.length === 0 && commentContentFilters.length === 0) {return {filterState,hasNoMatches: false,@@ -123,7 +134,7 @@ export async function applyCommentFilters({}let objectIdsFromComments: string[] = [];- const hasCommentCountFilters = commentCountFilters.length > 0;+ let shouldIntersectWithCommentCountIds = commentCountFilters.length > 0;// Remove comment filters from filterStateconst updatedFilterState = filterState.filter(@@ -135,6 +146,31 @@ export async function applyCommentFilters({),);+ const resolveCommentContentFilterIds = async (): Promise<string[]> => {+ let matchingIds: string[] | null = null;++ for (const commentContentFilter of commentContentFilters) {+ const filterObjectIds = await getObjectIdsByCommentContent({+ prisma,+ projectId,+ objectType,+ searchQuery: commentContentFilter.value,+ operator: commentContentFilter.operator as CommentContentOperator,+ });++ if (matchingIds === null) {+ matchingIds = filterObjectIds;+ } else {+ const filterObjectIdSet = new Set(filterObjectIds);+ matchingIds = matchingIds.filter((id) => filterObjectIdSet.has(id));+ }+ }++ const resolvedIds = matchingIds ?? [];+ validateObjectIdCount(resolvedIds, objectType);+ return resolvedIds;+ };+// 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@@ -150,24 +186,52 @@ export async function applyCommentFilters({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 === "<",- );+ // Exact zero is equivalent to the tightest possible upper bound because+ // comment counts cannot be negative.+ const upperBoundFilter = numberFilters.reduce<+ (typeof numberFilters)[number] | undefined+ >((tightest, filter) => {+ const isUpperBound =+ (filter.operator === "=" && filter.value === 0) ||+ filter.operator === "<=" ||+ filter.operator === "<";++ if (!isUpperBound) return tightest;+ if (!tightest) return filter;++ const isTighter =+ filter.value < tightest.value ||+ (filter.value === tightest.value &&+ filter.operator === "<" &&+ tightest.operator !== "<");++ return isTighter ? filter : tightest;+ }, undefined);if (!upperBoundFilter) {// No upper bound + includes zero = match everything, skip comment count filter// But still process content filter if present- if (!commentContentFilter) {+ if (commentContentFilters.length === 0) {return {filterState: updatedFilterState,hasNoMatches: false,matchingIds: null,};}+ // Only the lower-bound predicates that are no-ops for non-negative+ // counts can safely be discarded before applying the content filter.+ const commentCountFilterIsNoop =+ numberFilters.length === commentCountFilters.length &&+ numberFilters.every(+ (filter) =>+ (filter.operator === ">=" && filter.value <= 0) ||+ (filter.operator === ">" && filter.value < 0),+ );+ shouldIntersectWithCommentCountIds = !commentCountFilterIsNoop;// Continue to content filter handling below} else {// Get IDs that EXCEED the upper bound (to exclude them)- const excludeOperator = upperBoundFilter.operator === "<=" ? ">" : ">=";+ const excludeOperator = upperBoundFilter.operator === "<" ? ">=" : ">";const idsToExclude = await getObjectIdsByCommentCount({prisma,projectId,@@ -179,16 +243,8 @@ export async function applyCommentFilters({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);+ if (commentContentFilters.length > 0) {+ const contentObjectIds = await resolveCommentContentFilterIds();// For content filter with zero-inclusive count filter:// Include items matching content AND not exceeding upper bound@@ -278,20 +334,11 @@ export async function applyCommentFilters({}// 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);+ if (commentContentFilters.length > 0) {+ const contentObjectIds = await resolveCommentContentFilterIds();// Intersect with comment count results if present- if (hasCommentCountFilters) {- // Always intersect if comment count filters were processed+ if (shouldIntersectWithCommentCountIds) {objectIdsFromComments = objectIdsFromComments.filter((id) =>contentObjectIds.includes(id),);diff --git a/web/src/__tests__/server/unit/batch-actions-comment-filter.servertest.ts b/web/src/__tests__/server/unit/batch-actions-comment-filter.servertest.tsnew file mode 100644index 0000000000..7903bfc3b0--- /dev/null+++ b/web/src/__tests__/server/unit/batch-actions-comment-filter.servertest.ts@@ -0,0 +1,228 @@+const mocks = vi.hoisted(() => ({+ applyCommentFilters: vi.fn(),+ getObservationsCountFromEventsTable: vi.fn(),+ getObservationsTableCount: vi.fn(),+ queueAdd: vi.fn(),+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual = await importOriginal<typeof SharedServerModule>();++ return {+ ...actual,+ applyCommentFilters: mocks.applyCommentFilters,+ getObservationsCountFromEventsTable:+ mocks.getObservationsCountFromEventsTable,+ getObservationsTableCount: mocks.getObservationsTableCount,+ BatchActionQueue: {+ getInstance: vi.fn(() => ({ add: mocks.queueAdd })),+ },+ };+});++vi.mock("@/src/features/audit-logs/auditLog", () => ({+ auditLog: vi.fn(),+}));++import type { Session } from "next-auth";+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { PrismaClient } from "@langfuse/shared/src/db";+import type * as SharedServerModule from "@langfuse/shared/src/server";+import {+ BatchEvalSourceTable,+ InvalidRequestError,+ type BatchActionQuery,+} from "@langfuse/shared";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { addToDatasetRouter } from "@/src/features/batch-actions/server/addToDatasetRouter";+import { runEvaluationRouter } from "@/src/features/batch-actions/server/runEvaluationRouter";+import { env } from "@/src/env.mjs";++const mutableEnv = env as unknown as {+ LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN: "true" | "false";+};+const originalPreviewOptIn =+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN;++const projectId = "project-id";+const evaluatorId = "evaluator-id";+const rawCommentFilter = {+ type: "string" as const,+ column: "commentContent",+ operator: "contains" as const,+ value: "needs-review",+};+const resolvedIdFilter = {+ type: "stringOptions" as const,+ column: "id",+ operator: "any of" as const,+ value: ["matching-observation"],+};+const query: BatchActionQuery = {+ filter: [rawCommentFilter],+ orderBy: null,+};+const datasetConfig = {+ datasetId: "dataset-id",+ datasetName: "Dataset",+ mapping: {+ input: { mode: "none" as const },+ expectedOutput: { mode: "none" as const },+ metadata: { mode: "none" as const },+ },+};++const session = {+ expires: "1",+ user: {+ id: "user-id",+ organizations: [+ {+ id: "org-id",+ role: "OWNER",+ projects: [+ {+ id: projectId,+ role: "ADMIN",+ },+ ],+ },+ ],+ },+} as Session;++function prepare() {+ const batchActionCreate = vi+ .fn()+ .mockResolvedValue({ id: "batch-action-id" });+ const prisma = {+ batchAction: { create: batchActionCreate },+ jobConfiguration: {+ findMany: vi.fn(async () => [{ id: evaluatorId }]),+ },+ } as unknown as PrismaClient;+ const ctx = {+ ...createInnerTRPCContext({ session, headers: {} }),+ prisma,+ };++ return {+ prisma,+ batchActionCreate,+ addToDataset: addToDatasetRouter.createCaller(ctx),+ runEvaluation: runEvaluationRouter.createCaller(ctx),+ };+}++type TestContext = ReturnType<typeof prepare>;+type Action = "add-to-dataset" | "run-evaluation";+const actions = [+ { label: "add-to-dataset", action: "add-to-dataset" },+ { label: "evaluation", action: "run-evaluation" },+] as const;++function runAction(action: Action, context: TestContext) {+ return action === "add-to-dataset"+ ? context.addToDataset.create({ projectId, query, config: datasetConfig })+ : context.runEvaluation.create({+ projectId,+ query,+ evaluatorIds: [evaluatorId],+ sourceTable: BatchEvalSourceTable.EVENTS,+ });+}++function resolveComments(hasNoMatches = false) {+ mocks.applyCommentFilters.mockResolvedValue({+ filterState: hasNoMatches ? [] : [resolvedIdFilter],+ hasNoMatches,+ matchingIds: hasNoMatches ? [] : resolvedIdFilter.value,+ });+}++describe("event batch-action comment filter preflight", () => {+ beforeEach(() => {+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ Object.values(mocks).forEach((mock) => mock.mockReset());+ mocks.getObservationsCountFromEventsTable.mockResolvedValue(1);+ mocks.getObservationsTableCount.mockResolvedValue(1);+ mocks.queueAdd.mockResolvedValue(undefined);+ });++ afterAll(() => {+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN =+ originalPreviewOptIn;+ });++ it.each(actions)(+ "uses resolved comment filters for the $label count",+ async ({ action }) => {+ const context = prepare();+ resolveComments();++ await runAction(action, context);++ expect(mocks.applyCommentFilters).toHaveBeenCalledWith({+ filterState: query.filter,+ prisma: context.prisma,+ projectId,+ objectType: "OBSERVATION",+ });+ expect(mocks.getObservationsCountFromEventsTable).toHaveBeenCalledWith(+ expect.objectContaining({ filter: [resolvedIdFilter] }),+ );+ expect(context.batchActionCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({ query }),+ }),+ );+ expect(mocks.queueAdd).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ payload: expect.objectContaining({ query }),+ }),+ expect.anything(),+ );+ },+ );++ it.each(actions)(+ "skips the $label count when comment filters have no matches",+ async ({ action }) => {+ const context = prepare();+ resolveComments(true);++ await runAction(action, context);++ expect(mocks.getObservationsCountFromEventsTable).not.toHaveBeenCalled();+ },+ );++ it("uses resolved comment filters for the legacy Observation count", async () => {+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "false";+ const context = prepare();+ resolveComments();++ await runAction("add-to-dataset", context);++ expect(mocks.getObservationsTableCount).toHaveBeenCalledWith(+ expect.objectContaining({ filter: [resolvedIdFilter] }),+ );+ expect(mocks.getObservationsCountFromEventsTable).not.toHaveBeenCalled();+ });++ it.each(actions)(+ "returns a comment-filter threshold as a $label bad request",+ async ({ action }) => {+ const context = prepare();+ mocks.applyCommentFilters.mockRejectedValue(+ new InvalidRequestError("comment-filter threshold"),+ );++ await expect(runAction(action, context)).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: "comment-filter threshold",+ });+ },+ );+});diff --git a/web/src/__tests__/server/unit/code-eval-test-run-comment-filter.servertest.ts b/web/src/__tests__/server/unit/code-eval-test-run-comment-filter.servertest.tsnew file mode 100644index 0000000000..6f08b5625d--- /dev/null+++ b/web/src/__tests__/server/unit/code-eval-test-run-comment-filter.servertest.ts@@ -0,0 +1,88 @@+const mocks = vi.hoisted(() => ({+ applyCommentFilters: vi.fn(),+ getEventsStreamForEval: vi.fn(),+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => {+ const actual = await importOriginal<typeof SharedServerModule>();++ return {+ ...actual,+ applyCommentFilters: mocks.applyCommentFilters,+ getEventsStreamForEval: mocks.getEventsStreamForEval,+ };+});++import { beforeEach, describe, expect, it, vi } from "vitest";+import { EvalTargetObject } from "@langfuse/shared";+import type { PrismaClient } from "@langfuse/shared/src/db";+import type * as SharedServerModule from "@langfuse/shared/src/server";+import { runCodeEvalTestForJobConfig } from "@/src/features/evals/server/codeEvalTestRun";++const commentFilter = {+ type: "string" as const,+ column: "commentContent",+ operator: "contains" as const,+ value: "missing comment",+};+const filter = [commentFilter];+const prisma = {} as PrismaClient;+const previewParams = {+ prisma,+ orgId: "org-id",+ projectId: "project-id",+ evalTemplateId: "template-id",+ target: EvalTargetObject.EVENT,+ mapping: [],+ scoreName: "score-name",+ filter,+};++function resolveComments(filterState: unknown[], hasNoMatches = false) {+ mocks.applyCommentFilters.mockResolvedValue({+ filterState,+ hasNoMatches,+ matchingIds: [],+ });+}++describe("code-eval filter preview comment handling", () => {+ beforeEach(() => {+ Object.values(mocks).forEach((mock) => mock.mockReset());+ mocks.getEventsStreamForEval.mockResolvedValue(+ (async function* emptyStream() {})(),+ );+ });++ it("returns null without querying events when observation comment filters have no matches", async () => {+ resolveComments([], true);++ await expect(+ runCodeEvalTestForJobConfig(previewParams),+ ).resolves.toBeNull();+ expect(mocks.applyCommentFilters).toHaveBeenCalledWith({+ filterState: filter,+ prisma,+ projectId: "project-id",+ objectType: "OBSERVATION",+ });+ expect(mocks.getEventsStreamForEval).not.toHaveBeenCalled();+ });++ it("queries one event with the resolved comment filter", async () => {+ const resolvedFilter = {+ type: "stringOptions" as const,+ column: "id",+ operator: "any of" as const,+ value: ["matching-observation"],+ };+ resolveComments([resolvedFilter]);++ await runCodeEvalTestForJobConfig(previewParams);+ expect(mocks.getEventsStreamForEval).toHaveBeenCalledWith({+ projectId: "project-id",+ filter: [resolvedFilter],+ rowLimit: 1,+ });+ });+});diff --git a/web/src/features/batch-actions/server/addToDatasetRouter.ts b/web/src/features/batch-actions/server/addToDatasetRouter.tsindex c6d141e29e..997f850130 100644--- a/web/src/features/batch-actions/server/addToDatasetRouter.ts+++ b/web/src/features/batch-actions/server/addToDatasetRouter.ts@@ -8,6 +8,7 @@ import {BatchActionQueue,logger,QueueJobs,+ applyCommentFilters,getObservationsCountFromEventsTable,getObservationsTableCount,} from "@langfuse/shared/src/server";@@ -17,6 +18,7 @@ import {BatchActionType,BatchActionStatus,ActionId,+ InvalidRequestError,} from "@langfuse/shared";import { env } from "@/src/env.mjs";import { CreateObservationAddToDatasetActionSchema } from "../validation";@@ -50,18 +52,30 @@ export const addToDatasetRouter = createTRPCRouter({tableName,});+ // Resolve comment predicates for the count only. The original query is+ // persisted and queued so the worker can resolve comments against its+ // own cutoff-time selection.+ const commentFilterResult = await applyCommentFilters({+ filterState: query.filter ?? [],+ prisma: ctx.prisma,+ projectId,+ objectType: "OBSERVATION",+ });+// Check observation count doesn't exceed maximumconst queryOpts = {projectId,- filter: query.filter ?? [],+ filter: commentFilterResult.filterState,searchQuery: query.searchQuery,searchType: query.searchType,limit: 1,offset: 0,};- const observationCount = useEventsTable- ? await getObservationsCountFromEventsTable(queryOpts)- : await getObservationsTableCount(queryOpts);+ const observationCount = commentFilterResult.hasNoMatches+ ? 0+ : useEventsTable+ ? await getObservationsCountFromEventsTable(queryOpts)+ : await getObservationsTableCount(queryOpts);if (observationCount > MAX_BATCH_ADD_TO_DATASET_ITEMS) {throw new TRPCError({@@ -127,6 +141,13 @@ export const addToDatasetRouter = createTRPCRouter({if (e instanceof TRPCError) {throw e;}+ if (e instanceof InvalidRequestError) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: e.message,+ cause: e,+ });+ }throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "Creating add-to-dataset action failed.",diff --git a/web/src/features/batch-actions/server/runEvaluationRouter.ts b/web/src/features/batch-actions/server/runEvaluationRouter.tsindex 6bae32ef03..2b10e83000 100644--- a/web/src/features/batch-actions/server/runEvaluationRouter.ts+++ b/web/src/features/batch-actions/server/runEvaluationRouter.ts@@ -8,6 +8,7 @@ import {BatchActionQueue,logger,QueueJobs,+ applyCommentFilters,getObservationsCountFromEventsTable,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";@@ -17,6 +18,7 @@ import {ActionId,BatchEvalSourceTable,getEvalTargetObjectFromSourceTable,+ InvalidRequestError,} from "@langfuse/shared";import { env } from "@/src/env.mjs";import { CreateObservationBatchEvaluationActionSchema } from "../validation";@@ -85,15 +87,28 @@ export const runEvaluationRouter = createTRPCRouter({});}+ // Event comments live in Postgres, so resolve them for the preflight+ // count while retaining the original query for the queued worker.+ const commentFilterResult =+ sourceTable === BatchEvalSourceTable.EVENTS+ ? await applyCommentFilters({+ filterState: query.filter ?? [],+ prisma: ctx.prisma,+ projectId,+ objectType: "OBSERVATION",+ })+ : null;+const countQueryOpts = {projectId,- filter: query.filter ?? [],+ filter: commentFilterResult?.filterState ?? query.filter ?? [],searchQuery: query.searchQuery,searchType: query.searchType,};- const observationCount =- await getObservationsCountFromEventsTable(countQueryOpts);+ const observationCount = commentFilterResult?.hasNoMatches+ ? 0+ : await getObservationsCountFromEventsTable(countQueryOpts);if (observationCount > env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT) {throw new TRPCError({@@ -161,6 +176,13 @@ export const runEvaluationRouter = createTRPCRouter({if (e instanceof TRPCError) {throw e;}+ if (e instanceof InvalidRequestError) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: e.message,+ cause: e,+ });+ }throw new TRPCError({code: "INTERNAL_SERVER_ERROR",message: "Creating run-evaluation action failed.",diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.tsindex 45c83c0fbc..c5b80a89e0 100644--- a/web/src/features/evals/server/codeEvalTestRun.ts+++ b/web/src/features/evals/server/codeEvalTestRun.ts@@ -3,6 +3,7 @@ import {DEFAULT_TRACE_ENVIRONMENT,createUnknownSdkIngestionAttribution,eventTypes,+ applyCommentFilters,createW3CTraceId,extractObservationVariables,getEventsStreamForEval,@@ -106,6 +107,7 @@ export async function runCodeEvalTestForJobConfig(params: {filter: FilterCondition[] | null;}): Promise<CodeEvalTestRunResult | null> {const observation = await getObservationForEvalByFilter({+ prisma: params.prisma,projectId: params.projectId,target: params.target,filter: params.filter,@@ -220,6 +222,7 @@ function toCodeEvalTestRunError({}async function getObservationForEvalByFilter(params: {+ prisma: PrismaClient;projectId: string;target: EvalTargetObject;filter: FilterCondition[] | null;@@ -235,9 +238,20 @@ async function getObservationForEvalByFilter(params: {? getExperimentEvalPreviewFilters(params.filter): params.filter;+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: filter ?? [],+ prisma: params.prisma,+ projectId: params.projectId,+ objectType: "OBSERVATION",+ });++ if (hasNoMatches) {+ return null;+ }+const stream = await getEventsStreamForEval({projectId: params.projectId,- filter,+ filter: filterState,rowLimit: 1,});diff --git a/worker/src/__tests__/handleBatchActionJob-comment-filters.unit.test.ts b/worker/src/__tests__/handleBatchActionJob-comment-filters.unit.test.tsnew file mode 100644index 0000000000..3017faecaa--- /dev/null+++ b/worker/src/__tests__/handleBatchActionJob-comment-filters.unit.test.ts@@ -0,0 +1,183 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ BatchActionType,+ BatchTableNames,+ type FilterCondition,+} from "@langfuse/shared";++const mocks = vi.hoisted(() => {+ const emptyStream = () =>+ (async function* (): AsyncGenerator<Record<string, unknown>> {+ // Intentionally empty.+ })();++ return {+ applyCommentFilters: vi.fn(),+ getEventsStreamForAnnotationQueue: vi.fn(emptyStream),+ getEventsStreamForDataset: vi.fn(emptyStream),+ getEventsStreamForEval: vi.fn(emptyStream),+ getObservationStream: vi.fn(emptyStream),+ findEvaluators: vi.fn(),+ };+});++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ jobConfiguration: { findMany: mocks.findEvaluators },+ batchAction: { update: vi.fn().mockResolvedValue(undefined) },+ },+}));++vi.mock("@langfuse/shared/src/server", () => ({+ applyCommentFilters: mocks.applyCommentFilters,+ getEventsStreamForEval: mocks.getEventsStreamForEval,+ getCurrentSpan: vi.fn(() => undefined),+ logger: { info: vi.fn(), error: vi.fn() },+ CreateEvalQueue: { getInstance: vi.fn() },+ findDatasetIdsForBatchDeletion: vi.fn(),+ traceDeletionProcessor: vi.fn(),+}));++vi.mock("../features/database-read-stream/event-stream", () => ({+ getEventsStreamForAnnotationQueue: mocks.getEventsStreamForAnnotationQueue,+ getEventsStreamForDataset: mocks.getEventsStreamForDataset,+}));++vi.mock("../features/database-read-stream/observation-stream", () => ({+ getObservationStream: mocks.getObservationStream,+}));++vi.mock("../features/batchAction/processAddObservationsToDataset", () => ({+ processAddObservationsToDataset: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("../features/batchAction/processBatchedObservationEval", () => ({+ processBatchedObservationEval: vi.fn().mockResolvedValue(undefined),+}));++import { prisma } from "@langfuse/shared/src/db";+import type { BatchActionProcessingEventType } from "@langfuse/shared/src/server";+import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJob";++const rawCommentFilter: FilterCondition[] = [+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "review me",+ },+];+const idFilter = (value: string[]): FilterCondition[] => [+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value,+ },+];+const resolvedCommentFilter = idFilter(["observation-1"]);+const emptySelectionFilter = idFilter([]);+const datasetConfig = {+ datasetId: "dataset-1",+ datasetName: "Dataset",+ mapping: {+ input: { mode: "full" },+ expectedOutput: { mode: "full" },+ metadata: { mode: "none" },+ },+} as const;++const runBatchAction = (payload: BatchActionProcessingEventType) =>+ handleBatchActionJob({ payload } as never);+const createPayload = (+ actionId: BatchActionProcessingEventType["actionId"],+ tableName = BatchTableNames.Events,+) =>+ ({+ projectId: "project-1",+ actionId,+ tableName,+ cutoffCreatedAt: new Date(),+ query: { filter: rawCommentFilter, orderBy: null },+ targetId: "queue-1",+ batchActionId: "batch-action-1",+ config: datasetConfig,+ evaluatorIds: ["evaluator-1"],+ type: BatchActionType.Create,+ }) as BatchActionProcessingEventType;++describe("event batch-action comment filter wiring", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.applyCommentFilters.mockResolvedValue({+ filterState: resolvedCommentFilter,+ hasNoMatches: false,+ matchingIds: ["observation-1"],+ });+ mocks.findEvaluators.mockResolvedValue([+ {+ evalTemplate: { type: "LLM_AS_JUDGE" },+ },+ ]);+ });++ it.each([+ {+ name: "Events annotation queue",+ payload: createPayload("observation-add-to-annotation-queue"),+ getStream: mocks.getEventsStreamForAnnotationQueue,+ },+ {+ name: "legacy Observations annotation queue",+ payload: createPayload(+ "observation-add-to-annotation-queue",+ BatchTableNames.Observations,+ ),+ getStream: mocks.getObservationStream,+ },+ {+ name: "legacy Observations dataset",+ payload: createPayload(+ "observation-add-to-dataset",+ BatchTableNames.Observations,+ ),+ getStream: mocks.getObservationStream,+ },+ {+ name: "Events evaluation",+ payload: createPayload("observation-run-batched-evaluation"),+ getStream: mocks.getEventsStreamForEval,+ },+ {+ name: "Events dataset with no matches",+ payload: createPayload("observation-add-to-dataset"),+ getStream: mocks.getEventsStreamForDataset,+ noMatches: true,+ },+ ])(+ "resolves observation comments for $name",+ async ({ payload, getStream, noMatches }) => {+ if (noMatches) {+ mocks.applyCommentFilters.mockResolvedValue({+ filterState: [],+ hasNoMatches: true,+ matchingIds: [],+ });+ }++ await runBatchAction(payload);++ expect(mocks.applyCommentFilters).toHaveBeenCalledWith({+ filterState: rawCommentFilter,+ prisma,+ projectId: "project-1",+ objectType: "OBSERVATION",+ });+ expect(getStream).toHaveBeenCalledWith(+ expect.objectContaining({+ filter: noMatches ? emptySelectionFilter : resolvedCommentFilter,+ }),+ );+ },+ );+});diff --git a/worker/src/__tests__/handleBatchExportJob-comment-filters.unit.test.ts b/worker/src/__tests__/handleBatchExportJob-comment-filters.unit.test.tsnew file mode 100644index 0000000000..cb1945f288--- /dev/null+++ b/worker/src/__tests__/handleBatchExportJob-comment-filters.unit.test.ts@@ -0,0 +1,97 @@+import { expect, it, vi } from "vitest";+import {+ BatchExportFileFormat,+ BatchExportStatus,+ BatchExportTableName,+ type FilterCondition,+} from "@langfuse/shared";++const mocks = vi.hoisted(() => ({+ applyCommentFilters: vi.fn(),+ findBatchExport: vi.fn(),+ getEventsStream: vi.fn(),+ updateBatchExport: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ batchExport: {+ findFirst: mocks.findBatchExport,+ update: mocks.updateBatchExport,+ },+ },+}));++vi.mock("@langfuse/shared/src/server", () => ({+ applyCommentFilters: mocks.applyCommentFilters,+ getCurrentSpan: vi.fn(() => undefined),+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+ sendBatchExportSuccessEmail: vi.fn(),+ StorageServiceFactory: {},+ streamTransformations: {},+}));++vi.mock("../env", () => ({+ env: { LANGFUSE_S3_BATCH_EXPORT_ENABLED: "true" },+}));++vi.mock("../features/database-read-stream/event-stream", () => ({+ getEventsStream: mocks.getEventsStream,+}));++import { prisma } from "@langfuse/shared/src/db";+import { handleBatchExportJob } from "../features/batchExport/handleBatchExportJob";++const rawCommentFilter: FilterCondition[] = [+ {+ type: "string",+ column: "commentContent",+ operator: "contains",+ value: "review me",+ },+];+const resolvedCommentFilter: FilterCondition[] = [+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value: ["observation-1"],+ },+];++it("resolves Events comments as observation comments before exporting", async () => {+ const stopAfterStreamSelection = new Error("stop after stream selection");+ mocks.getEventsStream.mockRejectedValue(stopAfterStreamSelection);+ mocks.applyCommentFilters.mockResolvedValue({+ filterState: resolvedCommentFilter,+ hasNoMatches: false,+ matchingIds: ["observation-1"],+ });+ mocks.findBatchExport.mockResolvedValue({+ createdAt: new Date(),+ status: BatchExportStatus.QUEUED,+ format: BatchExportFileFormat.JSONL,+ query: {+ tableName: BatchExportTableName.Events,+ filter: rawCommentFilter,+ orderBy: null,+ },+ });++ await expect(+ handleBatchExportJob({+ projectId: "project-1",+ batchExportId: "export-1",+ }),+ ).rejects.toBe(stopAfterStreamSelection);++ expect(mocks.applyCommentFilters).toHaveBeenCalledWith({+ filterState: rawCommentFilter,+ prisma,+ projectId: "project-1",+ objectType: "OBSERVATION",+ });+ expect(mocks.getEventsStream).toHaveBeenCalledWith(+ expect.objectContaining({ filter: resolvedCommentFilter }),+ );+});diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex 91809e1754..7c75c9f9c2 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -9,6 +9,7 @@ import {TQueueJobTypes,findDatasetIdsForBatchDeletion,traceDeletionProcessor,+ applyCommentFilters,} from "@langfuse/shared/src/server";import {BatchActionType,@@ -50,6 +51,38 @@ const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {);};+const resolveObservationCommentFilters = async ({+ projectId,+ filter,+}: {+ projectId: string;+ filter: FilterCondition[];+}): Promise<FilterCondition[]> => {+ // Observation comments live in Postgres, while the event and legacy+ // observation streams query ClickHouse. Resolve comment predicates to an+ // observation ID predicate before constructing either stream.+ const { filterState, hasNoMatches } = await applyCommentFilters({+ filterState: filter,+ prisma,+ projectId,+ objectType: "OBSERVATION",+ });++ // applyCommentFilters removes the resolved comment predicates. If none+ // matched, passing filterState alone could leave the stream unconstrained,+ // so encode an explicitly empty selection and let the batch action complete.+ return hasNoMatches+ ? [+ {+ type: "stringOptions",+ operator: "any of",+ column: "id",+ value: [],+ },+ ]+ : filterState;+};+type HandleBatchActionJobDeps = {evalCreatorQueue?: Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>;};@@ -184,10 +217,21 @@ export const handleBatchActionJob = async (throw new Error(`Target ID is required for create action`);}+ const convertedFilter = convertDatesInFiltersFromStrings(+ query.filter ?? [],+ );+ const filter =+ actionId === "observation-add-to-annotation-queue"+ ? await resolveObservationCommentFilters({+ projectId,+ filter: convertedFilter,+ })+ : convertedFilter;+const streamParams = {projectId: projectId,cutoffCreatedAt: new Date(cutoffCreatedAt),- filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ filter,searchQuery: query.searchQuery ?? undefined,searchType: query.searchType ?? ["id" as const],};@@ -369,10 +413,18 @@ export const handleBatchActionJob = async (const parsedConfig = ObservationAddToDatasetConfigSchema.parse(config);// Get observation stream — use events table when tableName indicates it+ const convertedFilter = convertDatesInFiltersFromStrings(+ query.filter ?? [],+ );+ const filter = await resolveObservationCommentFilters({+ projectId,+ filter: convertedFilter,+ });+const streamParams = {projectId,cutoffCreatedAt: new Date(cutoffCreatedAt),- filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ filter,searchQuery: query.searchQuery ?? undefined,searchType: query.searchType ?? ["id" as const],};@@ -476,10 +528,15 @@ export const handleBatchActionJob = async (return;}+ const filter = await resolveObservationCommentFilters({+ projectId,+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ });+const dbReadStream = await getEventsStreamForEval({projectId,cutoffCreatedAt: new Date(cutoffCreatedAt),- filter: convertDatesInFiltersFromStrings(query.filter ?? []),+ filter,searchQuery: query.searchQuery ?? undefined,searchType: query.searchType ?? ["id", "content"],rowLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.tsindex 7434965c7a..78d89e4b82 100644--- a/worker/src/features/batchExport/handleBatchExportJob.ts+++ b/worker/src/features/batchExport/handleBatchExportJob.ts@@ -28,6 +28,7 @@ import { getEventsStream } from "../database-read-stream/event-stream";const tableToCommentType: Record<string, CommentObjectType | undefined> = {traces: "TRACE",observations: "OBSERVATION",+ events: "OBSERVATION",sessions: "SESSION",};