🪢 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(events): enable select-all batch delete on v4 events table (#14937)
Valery Meleshkin2804fb8f1f41
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.tsindex a2e323c2bf..1e96e7dbc6 100644--- a/packages/shared/src/features/batchAction/types.ts+++ b/packages/shared/src/features/batchAction/types.ts@@ -37,8 +37,9 @@ export const BatchActionQuerySchema = z.object({searchQuery: z.string().optional(),searchType: z.array(TracingSearchType).optional(),pathPrefix: z.string().optional(),- // Dispatch-time snapshot of the user's v4 beta flag; routes the sessions- // read stream to the events table instead of the legacy traces path.+ // Routes worker reads to the events table instead of the legacy tables.+ // The v4 events view declares it and the server validates the declaration;+ // otherwise createBatchActionJob snapshots the user's v4 beta flag.useEventsTable: z.boolean().optional(),});diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex a60ab83652..4d25fc8cc2 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -105,6 +105,10 @@ const buildOrderByClause = (const EVENTS_FIELDS = {// Aggregatescount: "count(*) as count",+ // uniq() is the approximate distinct aggregate (HLL-based, bounded memory);+ // uniqExact would build an unbounded hash set when the filtered set spans+ // millions of traces.+ uniqueTraceCount: 'uniq(e.trace_id) as "unique_trace_count"',// Identity & basic fieldsid: "e.span_id as id",@@ -203,6 +207,7 @@ const EVENTS_FIELDS = {const FIELD_SETS = {// Aggregatescount: ["count"],+ countWithUniqueTraces: ["count", "uniqueTraceCount"],// List query field sets (for getObservationsWithModelDataFromEventsTable)base: [diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 447f29cbcc..bcb2d3c72b 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -480,6 +480,28 @@ export const getObservationsCountFromEventsTable = async (return Number(count[0].count);};+/**+ * Row count plus approximate distinct trace count over the same filtered set,+ * computed in a single ClickHouse pass. Powers the events-table select-all+ * batch-delete confirmation ("N items spanning M unique traces").+ */+export const getObservationsCountsFromEventsTable = async (+ opts: ObservationTableQuery,+): Promise<{ totalCount: number; uniqueTraceCount: number }> => {+ const counts = await getObservationsFromEventsTableInternal<{+ count: string;+ unique_trace_count: string;+ }>({+ ...opts,+ select: "count-with-unique-traces",+ });++ return {+ totalCount: Number(counts[0].count),+ uniqueTraceCount: Number(counts[0].unique_trace_count),+ };+};+export const getObservationsWithModelDataFromEventsTable = async (opts: ObservationTableQuery,): Promise<FullEventsObservations> => {@@ -560,7 +582,11 @@ export const getTraceDeleteCursorPageFromEvents = async (props: {async function getObservationsFromEventsTableInternal<T>(opts: ObservationTableQuery & {- select: "count" | "rows" | "trace-delete-cursor";+ select:+ | "count"+ | "count-with-unique-traces"+ | "rows"+ | "trace-delete-cursor";selectToolData?: boolean;cursor?: PublicApiObservationsQuery["cursor"];preferredClickhouseService?: PreferredClickhouseService;@@ -624,6 +650,8 @@ async function getObservationsFromEventsTableInternal<T>(if (opts.select === "count") {queryBuilder.selectFieldSet("count");+ } else if (opts.select === "count-with-unique-traces") {+ queryBuilder.selectFieldSet("countWithUniqueTraces");} else if (opts.select === "trace-delete-cursor") {queryBuilder.selectRaw("e.span_id AS id",diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.tsindex bda16105d0..1282408eae 100644--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts@@ -4,6 +4,7 @@ import {getObservationsForTraceFromEventsTable,getObservationsWithModelDataFromEventsTable,getObservationsCountFromEventsTable,+ getObservationsCountsFromEventsTable,getObservationByIdFromEventsTable,getObservationsFromEventsTableForPublicApi,getObservationsCountFromEventsTableForPublicApi,@@ -466,6 +467,95 @@ describe("Clickhouse Events Repository Test", () => {});});+ maybe("getObservationsCountsFromEventsTable", () => {+ it("should return zero counts for non-existent project", async () => {+ const nonExistentProjectId = randomUUID();++ const counts = await getObservationsCountsFromEventsTable({+ projectId: nonExistentProjectId,+ filter: [],+ });++ expect(counts).toEqual({ totalCount: 0, uniqueTraceCount: 0 });+ });++ it("should return total event count and unique trace count in one query", async () => {+ const uniqueProjectId = randomUUID();+ const traceIds = [randomUUID(), randomUUID(), randomUUID()];+ // 6 events across 3 distinct traces (2 events per trace)+ const events = traceIds.flatMap((traceId, traceIndex) =>+ Array.from({ length: 2 }, (_, i) =>+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: traceId,+ type: "SPAN",+ name: `counts-test-${traceIndex}-${i}`,+ }),+ ),+ );++ await createEventsCh(events);++ const counts = await getObservationsCountsFromEventsTable({+ projectId: uniqueProjectId,+ filter: [],+ });++ expect(counts.totalCount).toBe(6);+ expect(counts.uniqueTraceCount).toBe(3);+ });++ it("should apply filters to both counts", async () => {+ const uniqueProjectId = randomUUID();+ const matchingTraceId = randomUUID();+ const otherTraceId = randomUUID();++ await createEventsCh([+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: matchingTraceId,+ type: "SPAN",+ name: "counts-filter-match",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: matchingTraceId,+ type: "SPAN",+ name: "counts-filter-match",+ }),+ createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ project_id: uniqueProjectId,+ trace_id: otherTraceId,+ type: "SPAN",+ name: "counts-filter-other",+ }),+ ]);++ const counts = await getObservationsCountsFromEventsTable({+ projectId: uniqueProjectId,+ filter: [+ {+ type: "string",+ column: "name",+ operator: "=",+ value: "counts-filter-match",+ },+ ],+ });++ expect(counts.totalCount).toBe(2);+ expect(counts.uniqueTraceCount).toBe(1);+ });+ });+maybe("Search Query Tests", () => {it("should not throw when searchQuery is combined with score filter", async () => {const uniqueProjectId = randomUUID();diff --git a/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.tsindex b091273c07..251725f508 100644--- a/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts+++ b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts@@ -16,12 +16,14 @@ vi.mock("@langfuse/shared/src/server", async () => {import type { Session } from "next-auth";import { randomUUID } from "crypto";-import { beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import {ActionId,+ AnnotationQueueObjectType,BatchExportTableName,BatchActionStatus,createTraceDeleteBatchActionConfig,@@ -132,29 +134,6 @@ describe("traces.deleteMany batch action", () => {expect(mockAddBatchAction).not.toHaveBeenCalled();});- it("snapshots v4 beta state into an events-backed config", async () => {- const { projectId, caller } = await createCaller({ v4BetaEnabled: true });- const batchActionId = `${projectId}-traces-trace-delete`;-- await caller.traces.deleteMany({- projectId,- traceIds: [randomUUID()],- isBatchAction: true,- query: traceDeleteQuery(`delete-user-${randomUUID()}`),- });-- const batchAction = await prisma.batchAction.findUniqueOrThrow({- where: { id: batchActionId },- });- expect(batchAction.query).toMatchObject({ useEventsTable: true });- expect(- TraceDeleteBatchActionConfigSchema.parse(batchAction.config),- ).toMatchObject({- source: "events",- inFlightBatch: null,- });- });-it("does not overwrite an active trace-delete BatchAction row", async () => {const { projectId, session, caller } = await createCaller();const batchActionId = `${projectId}-traces-trace-delete`;@@ -311,4 +290,306 @@ describe("traces.deleteMany batch action", () => {).resolves.toBe(true);expect(mockGetBatchActionJobState).not.toHaveBeenCalled();});++ it("rejects batch deletes with comment filters without creating a batch action", async () => {+ const { projectId, caller } = await createCaller();+ const batchActionId = `${projectId}-traces-trace-delete`;++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: {+ filter: [+ {+ column: "commentCount",+ operator: ">=" as const,+ value: 1,+ type: "number" as const,+ },+ ],+ orderBy: { column: "timestamp", order: "DESC" as const },+ },+ }),+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message:+ "Batch deletion does not support comment filters. Remove the comment filter and try again.",+ });++ await expect(+ prisma.batchAction.findUnique({ where: { id: batchActionId } }),+ ).resolves.toBeNull();+ });++ it("rejects deletes with an empty traceIds array even for batch actions", async () => {+ // An empty selection while select-all is armed signals a client-side+ // consistency issue; the server contract requires at least one traceId+ // for every delete and must fail loudly rather than absorb it.+ const { projectId, caller } = await createCaller();+ const batchActionId = `${projectId}-traces-trace-delete`;++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [],+ isBatchAction: true,+ query: traceDeleteQuery(`delete-user-${randomUUID()}`),+ }),+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: expect.stringContaining("Minimum 1 traceId is required."),+ });++ await expect(+ prisma.batchAction.findUnique({ where: { id: batchActionId } }),+ ).resolves.toBeNull();+ });++ describe("events-surface declarations (query.useEventsTable)", () => {+ 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;++ afterEach(() => {+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN =+ originalPreviewOptIn;+ });++ it("creates an events-backed config for non-beta users when the events preview surface is enabled", async () => {+ // The events view is reachable without the per-user v4 beta flag when+ // the instance-wide preview opt-in is set; a dispatch from it must keep+ // reading from the events table so the persisted events-view filters+ // stay valid for the worker.+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: false,+ });+ const batchActionId = `${projectId}-traces-trace-delete`;++ await caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: {+ ...traceDeleteQuery(`delete-user-${randomUUID()}`),+ useEventsTable: true,+ },+ });++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction.query).toMatchObject({ useEventsTable: true });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(batchAction.config),+ ).toMatchObject({+ source: "events",+ inFlightBatch: null,+ });+ expect(mockAddBatchAction).not.toHaveBeenCalled();+ });++ it("rejects the declaration when neither the beta flag nor the preview surface is enabled", async () => {+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "false";+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: false,+ });+ const batchActionId = `${projectId}-traces-trace-delete`;++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: {+ ...traceDeleteQuery(`delete-user-${randomUUID()}`),+ useEventsTable: true,+ },+ }),+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message:+ "Events-backed batch deletion is not available for this user on this instance.",+ });++ await expect(+ prisma.batchAction.findUnique({ where: { id: batchActionId } }),+ ).resolves.toBeNull();+ });++ it("ignores a client-sent useEventsTable: false and routes on the session snapshot", async () => {+ // Only validated useEventsTable: true declarations are honored —+ // legacy and stale clients can't be trusted to set the flag correctly,+ // so a client-sent false is ignored and the session's v4 beta flag+ // snapshot decides the source: a beta user stays events-backed.+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: true,+ });+ const batchActionId = `${projectId}-traces-trace-delete`;++ await caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: {+ ...traceDeleteQuery(`delete-user-${randomUUID()}`),+ useEventsTable: false,+ },+ });++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction.query).toMatchObject({ useEventsTable: true });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(batchAction.config),+ ).toMatchObject({ source: "events", inFlightBatch: null });+ });++ it("falls back to the session flag when the client declares no surface", async () => {+ // Dispatches without query.useEventsTable (stale clients mid-deploy,+ // out-of-tree callers) route on the session's v4 beta flag alone; the+ // instance-wide preview opt-in is irrelevant without a declaration.+ mutableEnv.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN = "true";++ const beta = await createCaller({ v4BetaEnabled: true });+ await beta.caller.traces.deleteMany({+ projectId: beta.projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: traceDeleteQuery(`delete-user-${randomUUID()}`),+ });++ const betaBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: `${beta.projectId}-traces-trace-delete` },+ });+ expect(betaBatchAction.query).toMatchObject({ useEventsTable: true });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(betaBatchAction.config),+ ).toMatchObject({ source: "events", inFlightBatch: null });++ const nonBeta = await createCaller({ v4BetaEnabled: false });+ await nonBeta.caller.traces.deleteMany({+ projectId: nonBeta.projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: traceDeleteQuery(`delete-user-${randomUUID()}`),+ });++ const nonBetaBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: `${nonBeta.projectId}-traces-trace-delete` },+ });+ expect(nonBetaBatchAction.query).toMatchObject({ useEventsTable: false });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(nonBetaBatchAction.config),+ ).toMatchObject({ source: "traces" });+ });+ });++ describe("with legacy IO search disabled", () => {+ const mutableEnv = env as unknown as {+ LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH: "true" | "false";+ };+ const originalLegacyIoSearchDisabled =+ mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH;++ afterEach(() => {+ mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH =+ originalLegacyIoSearchDisabled;+ });++ const ioSearchQuery = (userId: string) => ({+ ...traceDeleteQuery(userId),+ searchQuery: "some full-text query",+ searchType: ["id" as const, "content" as const],+ });++ // Literal owned by the module-private LEGACY_IO_SEARCH_BATCH_JOB_ERROR_MESSAGE+ // in web/src/features/traces/server/legacyIoSearch.ts.+ const legacyIoSearchErrorMessage =+ "Input/output search is disabled for legacy tracing tables on this instance. Switch to ID, name, or user ID search before creating a batch job.";++ it("allows v4 (events-backed) batch deletes with full-text search", async () => {+ mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH = "true";+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: true,+ });+ const batchActionId = `${projectId}-traces-trace-delete`;++ await caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: ioSearchQuery(`delete-user-${randomUUID()}`),+ });++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction.status).toBe(BatchActionStatus.Queued);+ expect(batchAction.query).toMatchObject({+ useEventsTable: true,+ searchQuery: "some full-text query",+ searchType: ["id", "content"],+ });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(batchAction.config),+ ).toMatchObject({ source: "events" });+ });++ it("still rejects non-TraceDelete batch actions with full-text search for v4 users", async () => {+ // Only TraceDelete's worker path honors useEventsTable; other batch+ // actions (here: trace add-to-annotation-queue) read from the legacy+ // traces table and must keep the strict legacy IO-search guard even+ // when the dispatching user is v4-flagged.+ mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH = "true";+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: true,+ });++ await expect(+ caller.annotationQueueItems.createMany({+ projectId,+ queueId: randomUUID(),+ objectIds: [randomUUID()],+ objectType: AnnotationQueueObjectType.TRACE,+ isBatchAction: true,+ query: ioSearchQuery(`queue-user-${randomUUID()}`),+ }),+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: legacyIoSearchErrorMessage,+ });++ expect(mockAddBatchAction).not.toHaveBeenCalled();+ });++ it("still rejects legacy (traces-backed) batch deletes with full-text search", async () => {+ mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH = "true";+ const { projectId, caller } = await createCaller({+ v4BetaEnabled: false,+ });+ const batchActionId = `${projectId}-traces-trace-delete`;++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: ioSearchQuery(`delete-user-${randomUUID()}`),+ }),+ ).rejects.toMatchObject({+ code: "BAD_REQUEST",+ message: legacyIoSearchErrorMessage,+ });++ await expect(+ prisma.batchAction.findUnique({ where: { id: batchActionId } }),+ ).resolves.toBeNull();+ });+ });});diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex 49be7fda0c..fd97813214 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -591,6 +591,15 @@ export default function TracesTable({compactNumberFormatter(Object.keys(selectedRows).length));+ // Select-all deletes persist the raw filterState into the batch action, but+ // comment filters resolve via Postgres at read time and the server rejects+ // such dispatches, so disable the action up front with a clear reason.+ // Column ids mirror the traces.deleteMany guard in+ // web/src/server/api/routers/traces.ts.+ const hasCommentFilter = filterState.some(+ (f) => f.column === "commentCount" || f.column === "commentContent",+ );+const tableActions: TableAction[] = [...(hasTraceDeletionEntitlement? [@@ -599,6 +608,9 @@ export default function TracesTable({type: BatchActionType.Delete,label: "Delete Traces",description: `This action permanently deletes ${displayCount} traces and cannot be undone. Trace deletion happens asynchronously and may take up to 24 hours.`,+ disabled: selectAll && hasCommentFilter,+ disabledReason:+ "Batch deletion does not support comment filters. Remove the comment filter to delete.",accessCheck: {scope: "traces:delete",entitlement: "trace-deletion",diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex cbd474ea89..3b10c16b3a 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -39,7 +39,11 @@ import {import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";import { cn } from "@/src/utils/tailwind";import { LevelColors } from "@/src/components/level-colors";-import { numberFormatter, usdFormatter } from "@/src/utils/numbers";+import {+ compactNumberFormatter,+ numberFormatter,+ usdFormatter,+} from "@/src/utils/numbers";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";import { useTableDateRange } from "@/src/hooks/useTableDateRange";@@ -612,6 +616,7 @@ export default function ObservationsEventsTable({const {observations,totalCount,+ uniqueTraceCount,isTotalCountLoading,isTotalCountError,hasMore,@@ -745,16 +750,59 @@ export default function ObservationsEventsTable({}, [observations.rows, selectedRows]);const handleDeleteTraces = async ({ projectId }: { projectId: string }) => {- if (selectedTraceIds.length === 0) return;+ // Select-all deletes are dispatched even if a background refetch drained+ // the visible-page selection to [] while the dialog was open: the server+ // requires at least one traceId regardless, so such a dispatch fails+ // loudly (as in the v3 traces table) — an empty selection while+ // select-all is armed signals a consistency issue, not a no-op.+ if (!selectAll && selectedTraceIds.length === 0) return;await traceDeleteMutation.mutateAsync({projectId,traceIds: selectedTraceIds,- isBatchAction: false,+ query: {+ filter: filterState,+ orderBy: orderByState,+ searchQuery: searchQuery || undefined,+ searchType,+ // Declare the dispatching surface: these are events-view filters, so+ // the worker must read them from the events table. The server+ // validates the declaration (beta flag or instance preview opt-in).+ useEventsTable: true,+ },+ isBatchAction: selectAll,});setSelectedRows({});};+ // Confirmation counts for "Delete Traces": page selection counts directly;+ // select-all counts resolve lazily ("..." while loading) and the distinct+ // trace count is a ClickHouse `uniq` approximation, hence the "~".+ const selectedVisibleRowCount = (observations.rows ?? []).filter(+ (observation) => selectedRows[observation.id],+ ).length;+ const selectedItemCount = selectAll ? totalCount : selectedVisibleRowCount;+ const itemCountDisplay =+ selectedItemCount !== null+ ? compactNumberFormatter(selectedItemCount)+ : "...";+ const selectedUniqueTraceCount = selectAll+ ? uniqueTraceCount+ : selectedTraceIds.length;+ const traceCountDisplay =+ selectedUniqueTraceCount !== null+ ? `${selectAll ? "~" : ""}${compactNumberFormatter(selectedUniqueTraceCount)}`+ : "...";++ // Select-all deletes persist the raw filterState into the batch action, but+ // comment filters (commentCount/commentContent) resolve via Postgres at read+ // time and the worker cannot translate them into a ClickHouse query — the+ // server blocks such dispatches, so disable the action up front with a+ // clear reason.+ const hasCommentFilter = filterState.some(+ (f) => f.column === "commentCount" || f.column === "commentContent",+ );+const isSelectAllCountUnavailable = isTotalCountLoading || isTotalCountError;const selectAllCountUnavailableReason = isTotalCountLoading? "Counting selected observations."@@ -768,12 +816,27 @@ export default function ObservationsEventsTable({id: ActionId.TraceDelete,type: BatchActionType.Delete,label: "Delete Traces",- description:- "This permanently deletes all observations within this trace(s), as well as the trace(s), even if you only have single observations selected. This action cannot be undone. Trace deletion happens asynchronously and may take up to 24 hours.",- disabled: selectAll || selectedTraceIds.length === 0,- disabledReason: selectAll- ? "Delete traces is only available for observations selected on the current page."- : "Selected observations are missing trace IDs.",+ description: `${itemCountDisplay} ${selectedItemCount === 1 ? "item is" : "items are"} selected, spanning ${traceCountDisplay} unique ${selectedUniqueTraceCount === 1 ? "trace" : "traces"}. A trace is always deleted as a whole — if at least one of its observations is selected, all of its observations are deleted with it. This action cannot be undone. Trace deletion happens asynchronously and may take up to 24 hours.`,+ // Select-all is not gated on the visible-page selection; if that+ // selection drained to empty, dispatch fails loudly with the+ // server's min-1 traceIds rejection (as in the v3 traces table).+ // Page selection needs concrete trace IDs.+ disabled: selectAll+ ? hasCommentFilter+ : selectedTraceIds.length === 0,+ disabledReason:+ selectAll && hasCommentFilter+ ? "Batch deletion does not support comment filters. Remove the comment filter to delete."+ : "Selected observations are missing trace IDs.",+ // The server keys every trace-delete batch row under the traces+ // table (row id `${projectId}-traces-trace-delete`), whichever+ // view dispatched it — the events-vs-traces read routing travels+ // in the job's config.source, not in the table name. The shared+ // key allows only one active trace deletion per project across+ // the v3 and v4 views, and pointing the in-progress poll at it+ // lets this dialog see a deletion started from either view. This+ // must stay Traces at least as long as the v3 view exists.+ tableName: BatchExportTableName.Traces,accessCheck: {scope: "traces:delete",entitlement: "trace-deletion",diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.tsindex bc5d71d798..bb942b2d8b 100644--- a/web/src/features/events/hooks/useEventsTableData.ts+++ b/web/src/features/events/hooks/useEventsTableData.ts@@ -174,6 +174,11 @@ export function useEventsTableData({const totalCount = selectAll? (totalCountQuery.data?.totalCount ?? null): null;+ // Approximate distinct trace_id count over the same filtered set, computed+ // alongside totalCount; shares its loading/error state below.+ const uniqueTraceCount = selectAll+ ? (totalCountQuery.data?.uniqueTraceCount ?? null)+ : null;const isTotalCountLoading =selectAll && totalCount === null && totalCountQuery.isFetching;const isTotalCountError =@@ -233,6 +238,7 @@ export function useEventsTableData({observations: joinedData,dataUpdatedAt: observations.dataUpdatedAt,totalCount,+ uniqueTraceCount,isTotalCountLoading,isTotalCountError,hasMore,diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex 6a3545fc3b..9d4d836cd1 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -134,7 +134,7 @@ export const eventsRouter = createTRPCRouter({});if (hasNoMatches) {- return { totalCount: 0 };+ return { totalCount: 0, uniqueTraceCount: 0 };}return instrumentAsync(diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 402a574c5e..9d7255755f 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -6,7 +6,7 @@ import {filterAndValidateDbScoreList,} from "@langfuse/shared";import {- getObservationsCountFromEventsTable,+ getObservationsCountsFromEventsTable,getObservationsWithModelDataFromEventsTable,getCategoricalScoresGroupedByName,getEventsFilterOptionsForColumns,@@ -324,7 +324,8 @@ export async function getEventList(params: GetObservationsListParams) {}/**- * Get total count of events matching filters+ * Get total count of events matching filters, plus the approximate number of+ * unique traces they span (single ClickHouse pass).*/export async function getEventCount(params: GetObservationsCountParams) {const queryOpts = {@@ -337,9 +338,10 @@ export async function getEventCount(params: GetObservationsCountParams) {offset: 0,};- const totalCount = await getObservationsCountFromEventsTable(queryOpts);+ const { totalCount, uniqueTraceCount } =+ await getObservationsCountsFromEventsTable(queryOpts);- return { totalCount };+ return { totalCount, uniqueTraceCount };}type EventFilterOptionRow = Awaited<diff --git a/web/src/features/table/components/TableActionDialog.tsx b/web/src/features/table/components/TableActionDialog.tsxindex b84293d8a9..6c20ffef07 100644--- a/web/src/features/table/components/TableActionDialog.tsx+++ b/web/src/features/table/components/TableActionDialog.tsx@@ -59,7 +59,10 @@ export function TableActionDialog({const isInProgress = api.table.getIsBatchActionInProgress.useQuery({projectId,- tableName,+ // Batch action rows are keyed by (projectId, actionId, tableName); an+ // action that registers under a different table than the hosting view+ // overrides the poll target via action.tableName.+ tableName: action.tableName ?? tableName,actionId: action.id,},{diff --git a/web/src/features/table/components/TableActionMenu.tsx b/web/src/features/table/components/TableActionMenu.tsxindex 192f0381e0..23c15162e4 100644--- a/web/src/features/table/components/TableActionMenu.tsx+++ b/web/src/features/table/components/TableActionMenu.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useEffect, useState } from "react";import { Button } from "@/src/components/ui/button";import { X, Trash } from "lucide-react";import { Plus } from "lucide-react";@@ -45,25 +45,44 @@ export function TableActionMenu({onClearSelection,onCustomAction,}: TableActionMenuProps) {- const [selectedAction, setSelectedAction] = useState<TableAction | null>(- null,- );+ const [selectedActionId, setSelectedActionId] = useState<+ TableAction["id"] | null+ >(null);const [isDialogOpen, setDialogOpen] = useState(false);+ // Derive the action from props on every render (ids are unique within one+ // menu) so the dialog shows live data — e.g. descriptions embedding lazily+ // resolved select-all counts — instead of a snapshot frozen at click time.+ // If the action disappears from `actions` while open, the dialog unmounts.+ const selectedAction =+ selectedActionId !== null+ ? actions.find((action) => action.id === selectedActionId)+ : undefined;+const handleActionSelect = (action: TableAction) => {if ("customDialog" in action && action.customDialog) {onCustomAction?.(action.id);return;}- setSelectedAction(action);+ setSelectedActionId(action.id);setDialogOpen(true);};const handleClose = () => {- setSelectedAction(null);+ setSelectedActionId(null);setDialogOpen(false);};+ // If the selected action leaves `actions` while its dialog is open, the+ // dialog unmounts without firing onClose; reset the open/selected state so+ // the dialog cannot reappear without a click if the action returns.+ useEffect(() => {+ if (selectedActionId !== null && selectedAction === undefined) {+ setSelectedActionId(null);+ setDialogOpen(false);+ }+ }, [selectedActionId, selectedAction]);+return (<><div className="pointer-events-none fixed inset-x-0 bottom-16 z-50 flex justify-center">diff --git a/web/src/features/table/server/createBatchActionJob.ts b/web/src/features/table/server/createBatchActionJob.tsindex 20b8bb47c4..1ac1b9ec3a 100644--- a/web/src/features/table/server/createBatchActionJob.ts+++ b/web/src/features/table/server/createBatchActionJob.ts@@ -40,6 +40,10 @@ type CreateBatchActionJob = {};query: BatchActionQuery;targetId?: string;+ // Call-site decision on whether this action reads from the events table+ // (see traces.deleteMany). When unset, it is inferred from the user's v4+ // beta flag below.+ useEventsTableOverride?: boolean;};const ACTIVE_BATCH_ACTION_STATUSES = [@@ -58,20 +62,31 @@ export const createBatchActionJob = async ({session,query,targetId,+ useEventsTableOverride,}: CreateBatchActionJob) => {- assertLegacyTracingIoSearchCanCreateBatchJob({- searchQuery: query.searchQuery,- searchType: query.searchType,- tableName,- });-- // Snapshot the user's v4 beta flag so the worker reads from the same data- // source as the UI table; overrides any client-sent value.+ // Whether the action reads from the events table is determined at the+ // call site (useEventsTableOverride) or inferred from the user's v4 beta+ // flag; the decision is snapshotted into the query at dispatch time.const queryWithSnapshot: BatchActionQuery = {...query,- useEventsTable: session.user.v4BetaEnabled ?? false,+ useEventsTable:+ useEventsTableOverride ?? session.user.v4BetaEnabled ?? false,};+ assertLegacyTracingIoSearchCanCreateBatchJob({+ searchQuery: queryWithSnapshot.searchQuery,+ searchType: queryWithSnapshot.searchType,+ tableName,+ // Only TraceDelete's worker path honors useEventsTable (config.source+ // "events" -> getTraceDeleteCursorPageFromEvents). Every other action+ // reads from the legacy tables regardless of the flag, so it must keep+ // the strict legacy IO-search guard.+ useEventsTable:+ actionId === ActionId.TraceDelete+ ? queryWithSnapshot.useEventsTable+ : undefined,+ });+const batchActionId = generateBatchActionId(projectId, actionId, tableName);if (actionId === ActionId.TraceDelete) {diff --git a/web/src/features/table/types.ts b/web/src/features/table/types.tsindex c3618ea6c7..556859ab63 100644--- a/web/src/features/table/types.ts+++ b/web/src/features/table/types.ts@@ -1,6 +1,10 @@import { type Entitlement } from "@/src/features/entitlements/constants/entitlements";import { type ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";-import { type BatchActionType, type ActionId } from "@langfuse/shared";+import {+ type BatchActionType,+ type ActionId,+ type BatchExportTableName,+} from "@langfuse/shared";import { type ReactElement } from "react";type BaseTableAction = {@@ -10,6 +14,11 @@ type BaseTableAction = {icon?: ReactElement<any>;disabled?: boolean;disabledReason?: string;+ // Batch action rows are registered per (projectId, actionId, tableName).+ // When an action dispatches under a different table than the hosting view+ // (e.g. TraceDelete from the events view registers under "traces"), set+ // this so the in-progress poll targets the table the job is stored under.+ tableName?: BatchExportTableName;accessCheck: {scope: ProjectScope;entitlement?: Entitlement;diff --git a/web/src/features/traces/server/legacyIoSearch.ts b/web/src/features/traces/server/legacyIoSearch.tsindex 00af0c8579..de38c33aaa 100644--- a/web/src/features/traces/server/legacyIoSearch.ts+++ b/web/src/features/traces/server/legacyIoSearch.ts@@ -62,9 +62,18 @@ export const assertLegacyTracingIoSearchCanCreateBatchJob = ({searchQuery,searchType,tableName,+ useEventsTable,}: LegacyTracingSearch & {tableName: BatchTableNames;+ // Dispatch-time snapshot of the user's v4 beta flag. Callers must only set+ // this for jobs whose worker path actually runs the stored query against+ // the events table (currently only TraceDelete via config.source "events");+ // such jobs are exempt from the legacy IO-search restriction just like+ // tableName "events". Leave it unset for every other action — their worker+ // paths ignore the flag and still run the legacy full-text IO scan.+ useEventsTable?: boolean;}) => {+ if (useEventsTable) return;if (!isLegacyTracingIoSearchDisabled()) return;if (!hasSearchQuery(searchQuery)) return;if (!hasLegacyTracingIoSearch(searchType)) return;diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 5f30394152..5fee0304bb 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -471,6 +471,43 @@ export const traceRouter = createTRPCRouter({});if (input.isBatchAction && input.query) {+ // Comment filters (commentCount/commentContent in both the v3 traces+ // and v4 events views) resolve via Postgres lookups at read time+ // (applyCommentFilters); when the worker translates the stored+ // filters into ClickHouse SQL, these columns map to a nonexistent+ // "comments" table and would deterministically fail every batch, so+ // reject them at dispatch.+ const hasCommentFilter = (input.query.filter ?? []).some(+ (f) => f.column === "commentCount" || f.column === "commentContent",+ );+ if (hasCommentFilter) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Batch deletion does not support comment filters. Remove the comment filter and try again.",+ });+ }++ // Decide here whether this delete reads from the events table: the+ // v4 events view sets query.useEventsTable: true, which we honor+ // after checking the events view is actually available to this user+ // (v4 beta flag, or the instance-wide preview opt-in). In every+ // other case createBatchActionJob infers the choice from the user's+ // v4 beta flag.+ const declaresEventsTable = input.query.useEventsTable === true;+ if (declaresEventsTable) {+ const eventsSurfaceAvailable =+ ctx.session.user.v4BetaEnabled === true ||+ env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true";+ if (!eventsSurfaceAvailable) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ "Events-backed batch deletion is not available for this user on this instance.",+ });+ }+ }+await createBatchActionJob({projectId: input.projectId,actionId: ActionId.TraceDelete,@@ -478,6 +515,7 @@ export const traceRouter = createTRPCRouter({tableName: BatchExportTableName.Traces,session: ctx.session,query: input.query,+ useEventsTableOverride: declaresEventsTable ? true : undefined,});} else {await Promise.all(