🪢 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: make batch action trace delete capable of handling 1mil+ actions (#14776)
Valery Meleshkin03bf0393cd05
diff --git a/.env.prod.example b/.env.prod.exampleindex ff8ef0d5c7..04a816f96c 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -242,6 +242,10 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_INTERVAL_MS=3600000# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_SUBMIT_TIMEOUT_MS=60000# LANGFUSE_CLICKHOUSE_DELETED_MASK_CLEANER_CLUSTER_MODE_ENABLED=false+# LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_ENABLED=true+# LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_INTERVAL_MS=10000+# LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_LOCK_TTL_SECONDS=1800+# LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_MAX_BATCHES_PER_RUN=5# Ingestion configuration# LANGFUSE_INGESTION_QUEUE_DELAY_MS=diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.tsindex b80848be09..a2e323c2bf 100644--- a/packages/shared/src/features/batchAction/types.ts+++ b/packages/shared/src/features/batchAction/types.ts@@ -44,6 +44,48 @@ export const BatchActionQuerySchema = z.object({export type BatchActionQuery = z.infer<typeof BatchActionQuerySchema>;+const TraceDeleteUtcTimestampSchema = z.iso.datetime();++export const TraceDeleteCursorSchema = z.object({+ timestamp: TraceDeleteUtcTimestampSchema,+ traceId: z.string(),+ id: z.string().optional(),+});++const TraceDeleteInFlightBatchSchema = z.object({+ traceIds: z.array(z.string()),+ cursorAfter: TraceDeleteCursorSchema,+ minTimestamp: TraceDeleteUtcTimestampSchema,+ maxTimestamp: TraceDeleteUtcTimestampSchema,+});++export const TraceDeleteBatchActionConfigSchema = z.object({+ version: z.literal(1),+ source: z.enum(["traces", "events"]),+ cutoffCreatedAt: TraceDeleteUtcTimestampSchema,+ failureCount: z.number().int().nonnegative().default(0),+ inFlightBatch: TraceDeleteInFlightBatchSchema.nullable(),+});++export type TraceDeleteBatchActionConfig = z.infer<+ typeof TraceDeleteBatchActionConfigSchema+>;++export type TraceDeleteBatchActionCursor = z.infer<+ typeof TraceDeleteCursorSchema+>;++export const createTraceDeleteBatchActionConfig = (opts: {+ useEventsTable: boolean;+ cutoffCreatedAt: Date;+}): TraceDeleteBatchActionConfig => ({+ version: 1,+ source: opts.useEventsTable ? "events" : "traces",+ cutoffCreatedAt: opts.cutoffCreatedAt.toISOString(),+ failureCount: 0,+ inFlightBatch: null,+});+export const CreateBatchActionSchema = z.object({projectId: z.string(),actionId: ActionIdSchema,diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 220d5efa7e..08015c4857 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -117,6 +117,7 @@ import {eventsTableCols,type NumericEventsTableColumnId,} from "../../eventsTable";+import type { TraceDeleteBatchActionCursor } from "../../features/batchAction/types";import {findUiColumnMapping,type UiColumnMappings,@@ -497,10 +498,68 @@ export const getObservationsWithModelDataFromEventsTable = async (return enrichObservationsWithTraceFields(withModelData);};+export const getTraceDeleteCursorPageFromEvents = async (props: {+ projectId: string;+ filter: FilterState;+ cutoffCreatedAt: Date;+ cursor?: TraceDeleteBatchActionCursor | null;+ searchQuery?: string;+ searchType?: TracingSearchType[];+ limit: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;+}): Promise<TraceDeleteBatchActionCursor[]> => {+ // Trace-delete cursoring intentionally reuses observation pagination where+ // span_id is the final tuple element, while this scanner deduplicates by+ // trace_id. If a deleted multi-span trace is still visible on a lagging+ // replica, a later span for the same trace can be emitted again. That is+ // acceptable because trace deletion is idempotent and only retries the same+ // trace id; the processor keeps its durable in-flight traceIds boundary.+ const rows = await getObservationsFromEventsTableInternal<{+ id: string;+ trace_id: string;+ start_time: string;+ }>({+ projectId: props.projectId,+ filter: [+ ...props.filter,+ {+ column: "startTime",+ operator: "<" as const,+ value: props.cutoffCreatedAt,+ type: "datetime" as const,+ },+ ],+ searchQuery: props.searchQuery,+ searchType: props.searchType,+ limit: props.limit,+ cursor: props.cursor?.id+ ? {+ lastStartTimeTo: new Date(props.cursor.timestamp),+ lastTraceId: props.cursor.traceId,+ lastId: props.cursor.id,+ }+ : undefined,+ clickhouseConfigs: props.clickhouseConfigs,+ // This scanner runs interleaved with DELETE mutations. Use the writable+ // pool so the next page is read from the same side as the mutation path+ // instead of a potentially lagging EventsReadOnly replica.+ preferredClickhouseService: "ReadWrite",+ select: "trace-delete-cursor",+ });++ return rows.map((row) => ({+ id: row.id,+ traceId: row.trace_id,+ timestamp: parseClickhouseUTCDateTimeFormat(row.start_time).toISOString(),+ }));+};+async function getObservationsFromEventsTableInternal<T>(opts: ObservationTableQuery & {- select: "count" | "rows";+ select: "count" | "rows" | "trace-delete-cursor";selectToolData?: boolean;+ cursor?: PublicApiObservationsQuery["cursor"];+ preferredClickhouseService?: PreferredClickhouseService;},): Promise<Array<T>> {const {@@ -513,6 +572,7 @@ async function getObservationsFromEventsTableInternal<T>(offset,orderBy,clickhouseConfigs,+ preferredClickhouseService,} = opts;// Extract positionInTrace filter and build baseFilter without it@@ -560,6 +620,12 @@ async function getObservationsFromEventsTableInternal<T>(if (opts.select === "count") {queryBuilder.selectFieldSet("count");+ } else if (opts.select === "trace-delete-cursor") {+ queryBuilder.selectRaw(+ "e.span_id AS id",+ "e.trace_id AS trace_id",+ "e.start_time AS start_time",+ );} else {queryBuilder.selectFieldSet(selectToolData ? "base" : "baseWithoutTools",@@ -579,6 +645,7 @@ async function getObservationsFromEventsTableInternal<T>(query: opts.searchQuery,searchType: opts.searchType,});+ const isTraceDeleteCursorSelect = opts.select === "trace-delete-cursor";// Handle positionInTrace via CTE with ROW_NUMBER()// All modes use the same pattern: rank observations per trace, pick rn = N.@@ -653,8 +720,16 @@ async function getObservationsFromEventsTableInternal<T>(.when(search.requiresEventsFull, (b) => b.forceFullTable()).applyFilters(observationsFilter).where(search)- .when(orderByEntries.length > 0, (b) => b.orderByColumns(orderByEntries))- .limit(limit, offset);+ .when(isTraceDeleteCursorSelect, (b) =>+ applyObservationsCursorFilter(opts.cursor, b),+ )+ .when(isTraceDeleteCursorSelect, (b) =>+ applyOrderByForObservationsQuery(b).limitBy("e.trace_id", "e.project_id"),+ )+ .when(!isTraceDeleteCursorSelect && orderByEntries.length > 0, (b) =>+ b.orderByColumns(orderByEntries),+ )+ .limit(limit, isTraceDeleteCursorSelect ? undefined : offset);const { query, params } = queryBuilder.buildWithParams();@@ -671,7 +746,8 @@ async function getObservationsFromEventsTableInternal<T>(params: input.params,tags: input.tags,clickhouseConfigs,- preferredClickhouseService: "EventsReadOnly",+ preferredClickhouseService:+ preferredClickhouseService ?? "EventsReadOnly",});},});@@ -1315,22 +1391,34 @@ function applyOffsetPagination(return queryBuilder.limit(opts.limit, offset);}-function applyCursorPagination(- opts: PublicApiObservationsQuery,+function applyObservationsCursorFilter(+ cursor: PublicApiObservationsQuery["cursor"] | undefined,queryBuilder: EventsQueryBuilder,): EventsQueryBuilder {- // Apply cursor filter if provided- queryBuilder = queryBuilder.when(Boolean(opts.cursor), (b) => {- const cursor = opts.cursor!;+ return queryBuilder.when(Boolean(cursor), (b) => {+ const currentCursor = cursor;+ if (!currentCursor) {+ return b;+ }+return b.whereRaw("e.start_time <= {lastStartTime: DateTime64(6)} AND (e.start_time, xxHash32(e.trace_id), e.span_id) < ({lastStartTime: DateTime64(6)}, xxHash32({lastTraceId: String}), {lastId: String})",{- lastStartTime: convertDateToClickhouseDateTime(cursor.lastStartTimeTo),- lastTraceId: cursor.lastTraceId,- lastId: cursor.lastId,+ lastStartTime: convertDateToClickhouseDateTime(+ currentCursor.lastStartTimeTo,+ ),+ lastTraceId: currentCursor.lastTraceId,+ lastId: currentCursor.lastId,},);});+}++function applyCursorPagination(+ opts: PublicApiObservationsQuery,+ queryBuilder: EventsQueryBuilder,+): EventsQueryBuilder {+ queryBuilder = applyObservationsCursorFilter(opts.cursor, queryBuilder);// Always apply limit (fetch limit+1 to detect if there are more results)return queryBuilder.limit(opts.limit + 1, undefined);diff --git a/packages/shared/src/server/services/traces-ui-table-service.test.ts b/packages/shared/src/server/services/traces-ui-table-service.test.tsnew file mode 100644index 0000000000..d88a8ae742--- /dev/null+++ b/packages/shared/src/server/services/traces-ui-table-service.test.ts@@ -0,0 +1,55 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockQueryClickhouse = vi.hoisted(() => vi.fn());+const mockShouldSkipObservationsFinal = vi.hoisted(() => vi.fn());+const mockClickhouseCompliantRandomCharacters = vi.hoisted(() => vi.fn());++vi.mock("../repositories", () => ({+ OBSERVATIONS_TO_TRACE_INTERVAL: "INTERVAL 2 DAY",+ SCORE_TO_TRACE_OBSERVATIONS_INTERVAL: "INTERVAL 1 HOUR",+ clickhouseCompliantRandomCharacters: mockClickhouseCompliantRandomCharacters,+ parseClickhouseUTCDateTimeFormat: (date: string) => new Date(date),+ queryClickhouse: mockQueryClickhouse,+ reduceUsageOrCostDetails: (details: Record<string, number>) => details,+}));++vi.mock("../queries/clickhouse-sql/query-options", () => ({+ shouldSkipObservationsFinal: mockShouldSkipObservationsFinal,+}));++import { getTraceDeleteCursorPageFromTraces } from "./traces-ui-table-service";++describe("getTraceDeleteCursorPageFromTraces", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ let counter = 0;+ mockClickhouseCompliantRandomCharacters.mockImplementation(+ () => `x${++counter}`,+ );+ mockQueryClickhouse.mockResolvedValue([]);+ mockShouldSkipObservationsFinal.mockResolvedValue(false);+ });++ it("uses canonical cursor ordering without FINAL", async () => {+ await getTraceDeleteCursorPageFromTraces({+ projectId: "project-1",+ filter: [],+ cutoffCreatedAt: new Date("2026-01-01T00:00:00.000Z"),+ limit: 100,+ });++ expect(mockQueryClickhouse).toHaveBeenCalledOnce();+ const { query } = mockQueryClickhouse.mock.calls[0]![0] as {+ query: string;+ };+ const normalizedQuery = query.replace(/\s+/g, " ");++ expect(normalizedQuery).toMatch(/\bFROM traces t\b/);+ expect(normalizedQuery).not.toMatch(/\bFROM traces t FINAL\b/);+ expect(normalizedQuery).toContain(+ "ORDER BY t.timestamp DESC, t.id DESC, t.event_ts DESC",+ );+ expect(normalizedQuery).toContain("LIMIT 1 BY id, project_id");+ expect(normalizedQuery).toContain("LIMIT {limit: Int32}");+ });+});diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex bb7670a7a2..b862ca8ecb 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -29,6 +29,8 @@ import { TracingSearchType } from "../../interfaces/search";import { ObservationLevelType, TraceDomain } from "../../domain";import { ClickHouseClientConfigOptions } from "@clickhouse/client";import { shouldSkipObservationsFinal } from "../queries/clickhouse-sql/query-options";+import { convertDateToClickhouseDateTime } from "../clickhouse/client";+import type { TraceDeleteBatchActionCursor } from "../../features/batchAction/types";export type TracesTableReturnType = Pick<TraceRecordReadType,@@ -171,6 +173,8 @@ export type FetchTracesTableProps = {page?: number;clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;tags?: Record<string, string>;+ traceDeleteCursor?: TraceDeleteBatchActionCursor | null;+ traceDeleteCursorOrder?: boolean;};// Define return type mapping for better type safety@@ -214,6 +218,8 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {searchQuery,searchType,clickhouseConfigs,+ traceDeleteCursor,+ traceDeleteCursorOrder,} = props;// OTel projects use immutable spans - no need for deduplication@@ -439,6 +445,37 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {].flat(),orderByCols,);+ const canonicalTraceDeleteOrder =+ select === "identifiers" && traceDeleteCursorOrder;+ const usesNonFinalTraceReadPath =+ defaultOrder || canonicalTraceDeleteOrder;+ const effectiveOrderBy = canonicalTraceDeleteOrder+ ? "ORDER BY t.timestamp DESC, t.id DESC, t.event_ts DESC"+ : chOrderBy;+ const cursorClause =+ canonicalTraceDeleteOrder && traceDeleteCursor+ ? `+ -- Cursor follows ORDER BY (timestamp DESC, id DESC). Older timestamps+ -- must pass regardless of how their ids compare to the cursor id.+ AND (+ t.timestamp < {cursorTimestamp: DateTime64(3)}+ OR (+ t.timestamp = {cursorTimestamp: DateTime64(3)}+ AND t.id < {cursorTraceId: String}+ )+ )`+ : "";+ const limitByClause =+ ["metrics", "rows", "identifiers"].includes(select) &&+ usesNonFinalTraceReadPath+ ? "LIMIT 1 BY id, project_id"+ : "";+ const limitClause =+ limit !== undefined && traceDeleteCursorOrder+ ? "LIMIT {limit: Int32}"+ : limit !== undefined && page !== undefined+ ? "LIMIT {limit: Int32} OFFSET {offset: Int32}"+ : "";// complex query ahead:// - we only join scores and observations if we really need them to speed up default views@@ -452,17 +489,18 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {SELECT ${sqlSelect}-- FINAL is used for non default ordering.- FROM traces t ${defaultOrder || select === "count" ? "" : "FINAL"}+ FROM traces t ${usesNonFinalTraceReadPath || select === "count" ? "" : "FINAL"}${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}WHERE t.project_id = {projectId: String}${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}+ ${cursorClause}${search.query}- ${chOrderBy}+ ${effectiveOrderBy}-- This is used for metrics and row queries. Count has only one result.-- This is only used for default ordering. Otherwise, we use final.- ${["metrics", "rows", "identifiers"].includes(select) && defaultOrder ? "LIMIT 1 BY id, project_id" : ""}- ${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ ${limitByClause}+ ${limitClause}`;const res = await queryClickhouse<@@ -473,6 +511,14 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {limit: limit,offset: limit && page ? limit * page : 0,traceTimestamp: timeStampFilter?.value.getTime(),+ ...(traceDeleteCursor+ ? {+ cursorTimestamp: convertDateToClickhouseDateTime(+ new Date(traceDeleteCursor.timestamp),+ ),+ cursorTraceId: traceDeleteCursor.traceId,+ }+ : {}),projectId: projectId,...tracesFilterRes.params,...observationFilterRes.params,@@ -599,3 +645,39 @@ export const getTraceIdentifiers = async (props: {timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),}));};++export const getTraceDeleteCursorPageFromTraces = async (props: {+ projectId: string;+ filter: FilterState;+ cutoffCreatedAt: Date;+ cursor?: TraceDeleteBatchActionCursor | null;+ searchQuery?: string;+ searchType?: TracingSearchType[];+ limit: number;+ clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;+}) => {+ const identifiers = await getTracesTableGeneric({+ select: "identifiers",+ projectId: props.projectId,+ filter: [+ ...props.filter,+ {+ column: "timestamp",+ operator: "<" as const,+ value: props.cutoffCreatedAt,+ type: "datetime" as const,+ },+ ],+ searchQuery: props.searchQuery,+ searchType: props.searchType,+ limit: props.limit,+ clickhouseConfigs: props.clickhouseConfigs,+ traceDeleteCursor: props.cursor ?? null,+ traceDeleteCursorOrder: true,+ });++ return identifiers.map((row) => ({+ traceId: row.id,+ timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp).toISOString(),+ }));+};diff --git a/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.tsnew file mode 100644index 0000000000..b091273c07--- /dev/null+++ b/web/src/__tests__/server/traces-batch-delete-trpc.servertest.ts@@ -0,0 +1,314 @@+const mockAddBatchAction = vi.fn();+const mockGetBatchActionJobState = vi.fn();++vi.mock("@langfuse/shared/src/server", async () => {+ const originalModule = await vi.importActual("@langfuse/shared/src/server");+ return {+ ...originalModule,+ BatchActionQueue: {+ getInstance: vi.fn(() => ({+ add: mockAddBatchAction,+ getJobState: mockGetBatchActionJobState,+ })),+ },+ };+});++import type { Session } from "next-auth";+import { randomUUID } from "crypto";+import { beforeEach, describe, expect, it } from "vitest";+import { prisma } from "@langfuse/shared/src/db";+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import {+ ActionId,+ BatchExportTableName,+ BatchActionStatus,+ createTraceDeleteBatchActionConfig,+ TraceDeleteBatchActionConfigSchema,+} from "@langfuse/shared";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";++const traceDeleteQuery = (userId: string) => ({+ filter: [+ {+ column: "userId",+ operator: "=" as const,+ value: userId,+ type: "string" as const,+ },+ ],+ orderBy: { column: "timestamp", order: "DESC" as const },+});++const createCaller = async (opts: { v4BetaEnabled?: boolean } = {}) => {+ const { project, org } = await createOrgProjectAndApiKey({ plan: "Team" });+ const session: Session = {+ expires: "1",+ user: {+ id: `user-${randomUUID()}`,+ name: "Batch Delete Test User",+ admin: true,+ v4BetaEnabled: opts.v4BetaEnabled ?? false,+ organizations: [+ {+ id: org.id,+ name: org.name,+ role: "OWNER",+ plan: "cloud:team",+ cloudConfig: undefined,+ projects: [+ {+ id: project.id,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: project.name,+ },+ ],+ },+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ },+ },+ environment: {} as any,+ };++ const ctx = createInnerTRPCContext({ session });+ return {+ projectId: project.id,+ session,+ caller: appRouter.createCaller({ ...ctx, prisma }),+ };+};++describe("traces.deleteMany batch action", () => {+ beforeEach(() => {+ mockAddBatchAction.mockClear();+ mockGetBatchActionJobState.mockReset();+ mockGetBatchActionJobState.mockResolvedValue("unknown");+ });++ it("creates the trace-delete BatchAction row without a queue payload", async () => {+ const { projectId, session, caller } = await createCaller();+ const userId = `delete-user-${randomUUID()}`;+ const query = traceDeleteQuery(userId);+ const batchActionId = `${projectId}-traces-trace-delete`;++ await caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query,+ });++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction).toMatchObject({+ projectId,+ userId: session.user.id,+ actionType: "trace-delete",+ tableName: "traces",+ status: BatchActionStatus.Queued,+ totalCount: null,+ processedCount: 0,+ failedCount: 0,+ });+ expect(batchAction.query).toMatchObject({+ ...query,+ useEventsTable: false,+ });+ expect(+ TraceDeleteBatchActionConfigSchema.parse(batchAction.config),+ ).toMatchObject({+ version: 1,+ source: "traces",+ inFlightBatch: null,+ });++ 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`;+ const existingQuery = traceDeleteQuery(`existing-user-${randomUUID()}`);++ await prisma.batchAction.create({+ data: {+ id: batchActionId,+ projectId,+ userId: session.user.id,+ actionType: "trace-delete",+ tableName: "traces",+ status: BatchActionStatus.Processing,+ query: {+ ...existingQuery,+ useEventsTable: false,+ },+ config: createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ }),+ totalCount: null,+ processedCount: 1,+ failedCount: 0,+ },+ });++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: traceDeleteQuery(`new-user-${randomUUID()}`),+ }),+ ).rejects.toMatchObject({+ code: "CONFLICT",+ });++ expect(mockAddBatchAction).not.toHaveBeenCalled();++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction.status).toBe(BatchActionStatus.Processing);+ expect(batchAction.processedCount).toBe(1);+ expect(batchAction.query).toMatchObject({+ ...existingQuery,+ useEventsTable: false,+ });+ });++ it("resets a completed trace-delete BatchAction row exactly once", async () => {+ const { projectId, session, caller } = await createCaller();+ const batchActionId = `${projectId}-traces-trace-delete`;+ const completedQuery = traceDeleteQuery(`completed-user-${randomUUID()}`);+ const nextQuery = traceDeleteQuery(`next-user-${randomUUID()}`);++ await prisma.batchAction.create({+ data: {+ id: batchActionId,+ projectId,+ userId: session.user.id,+ actionType: "trace-delete",+ tableName: "traces",+ status: BatchActionStatus.Completed,+ query: {+ ...completedQuery,+ useEventsTable: false,+ },+ config: createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(Date.now() - 1_000),+ }),+ totalCount: 1,+ processedCount: 1,+ failedCount: 0,+ finishedAt: new Date(),+ log: "completed",+ },+ });++ await caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: nextQuery,+ });++ await expect(+ caller.traces.deleteMany({+ projectId,+ traceIds: [randomUUID()],+ isBatchAction: true,+ query: traceDeleteQuery(`conflicting-user-${randomUUID()}`),+ }),+ ).rejects.toMatchObject({+ code: "CONFLICT",+ });++ const batchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(batchAction).toMatchObject({+ status: BatchActionStatus.Queued,+ totalCount: null,+ processedCount: 0,+ failedCount: 0,+ finishedAt: null,+ log: null,+ });+ expect(batchAction.query).toMatchObject({+ ...nextQuery,+ useEventsTable: false,+ });+ expect(batchAction.query).not.toMatchObject({+ ...completedQuery,+ useEventsTable: false,+ });+ expect(mockAddBatchAction).not.toHaveBeenCalled();+ });++ it("reports durable active trace-delete BatchActions as in progress", async () => {+ const { projectId, session, caller } = await createCaller();+ const batchActionId = `${projectId}-traces-trace-delete`;++ await prisma.batchAction.create({+ data: {+ id: batchActionId,+ projectId,+ userId: session.user.id,+ actionType: "trace-delete",+ tableName: "traces",+ status: BatchActionStatus.Processing,+ query: {+ ...traceDeleteQuery(`existing-user-${randomUUID()}`),+ useEventsTable: false,+ },+ config: createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ }),+ totalCount: null,+ processedCount: 1,+ failedCount: 0,+ },+ });++ await expect(+ caller.table.getIsBatchActionInProgress({+ projectId,+ actionId: ActionId.TraceDelete,+ tableName: BatchExportTableName.Traces,+ }),+ ).resolves.toBe(true);+ expect(mockGetBatchActionJobState).not.toHaveBeenCalled();+ });+});diff --git a/web/src/features/table/server/createBatchActionJob.ts b/web/src/features/table/server/createBatchActionJob.tsindex 89b7b063f9..20b8bb47c4 100644--- a/web/src/features/table/server/createBatchActionJob.ts+++ b/web/src/features/table/server/createBatchActionJob.ts@@ -1,11 +1,13 @@import { auditLog } from "@/src/features/audit-logs/auditLog";import { generateBatchActionId } from "@/src/features/table/server/helpers";import {+ ActionId,+ BatchActionStatus,type Role,type BatchExportTableName,type BatchActionQuery,- type ActionId,type BatchActionType,+ createTraceDeleteBatchActionConfig,} from "@langfuse/shared";import {BatchActionQueue,@@ -14,6 +16,7 @@ import {} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { assertLegacyTracingIoSearchCanCreateBatchJob } from "@/src/features/traces/server/legacyIoSearch";+import { prisma } from "@langfuse/shared/src/db";type CreateBatchActionJob = {projectId: string;@@ -39,6 +42,11 @@ type CreateBatchActionJob = {targetId?: string;};+const ACTIVE_BATCH_ACTION_STATUSES = [+ BatchActionStatus.Queued,+ BatchActionStatus.Processing,+];+/*** ⚠️ Only use after verifying that the user has the necessary permissions to perform the action.*/@@ -66,6 +74,72 @@ export const createBatchActionJob = async ({const batchActionId = generateBatchActionId(projectId, actionId, tableName);+ if (actionId === ActionId.TraceDelete) {+ const cutoffCreatedAt = new Date();+ const config = createTraceDeleteBatchActionConfig({+ useEventsTable: queryWithSnapshot.useEventsTable ?? false,+ cutoffCreatedAt,+ });+ const batchActionData = {+ userId: session.user.id,+ actionType: actionId,+ tableName,+ status: BatchActionStatus.Queued,+ query: queryWithSnapshot,+ config,+ totalCount: null,+ processedCount: 0,+ failedCount: 0,+ };++ const activeTraceDeleteConflict = new TRPCError({+ code: "CONFLICT",+ message:+ "A trace deletion batch action is already in progress for this project.",+ });++ await prisma.$transaction(async (tx) => {+ const created = await tx.batchAction.createMany({+ data: {+ id: batchActionId,+ projectId,+ ...batchActionData,+ },+ skipDuplicates: true,+ });++ if (created.count > 0) {+ return;+ }++ const reset = await tx.batchAction.updateMany({+ where: {+ id: batchActionId,+ status: { notIn: ACTIVE_BATCH_ACTION_STATUSES },+ },+ data: {+ finishedAt: null,+ log: null,+ ...batchActionData,+ },+ });++ if (reset.count === 0) {+ throw activeTraceDeleteConflict;+ }+ });++ await auditLog({+ session,+ resourceType: "batchAction",+ resourceId: batchActionId,+ projectId: projectId,+ action: actionType as string,+ });++ return;+ }+const batchActionQueue = BatchActionQueue.getInstance();if (!batchActionQueue) {logger.warn(`BatchActionQueue not initialized`);diff --git a/web/src/features/table/server/tableRouter.ts b/web/src/features/table/server/tableRouter.tsindex 670d50a1cd..6eed6c6d4b 100644--- a/web/src/features/table/server/tableRouter.ts+++ b/web/src/features/table/server/tableRouter.ts@@ -3,11 +3,20 @@ import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { GetIsBatchActionInProgressSchema } from "@langfuse/shared";+import {+ ActionId,+ BatchActionStatus,+ GetIsBatchActionInProgressSchema,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";import { BatchActionQueue, logger } from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";const WAITING_JOBS = ["waiting", "delayed", "active"];+const ACTIVE_BATCH_ACTION_STATUSES = [+ BatchActionStatus.Queued,+ BatchActionStatus.Processing,+];export const tableRouter = createTRPCRouter({getIsBatchActionInProgress: protectedProjectProcedure@@ -19,10 +28,27 @@ export const tableRouter = createTRPCRouter({actionId,tableName,);+ const batchAction = await prisma.batchAction.findUnique({+ where: { id: batchActionId },+ select: { status: true },+ });++ if (+ batchAction &&+ ACTIVE_BATCH_ACTION_STATUSES.includes(+ batchAction.status as BatchActionStatus,+ )+ ) {+ return true;+ }const batchActionQueue = BatchActionQueue.getInstance();if (!batchActionQueue) {+ if (actionId === ActionId.TraceDelete) {+ return false;+ }+logger.warn(`BatchActionQueue not initialized`);throw new TRPCError({code: "INTERNAL_SERVER_ERROR",diff --git a/worker/src/__tests__/deletedMaskCleaner.test.ts b/worker/src/__tests__/deletedMaskCleaner.test.tsindex 27a4d427b9..f78b1dcdac 100644--- a/worker/src/__tests__/deletedMaskCleaner.test.ts+++ b/worker/src/__tests__/deletedMaskCleaner.test.ts@@ -30,45 +30,17 @@ import {type MutationCountRow,type WorkCandidateRow,} from "../features/deleted-mask-cleaner/helpers";+import { skipUnlessClickhouseTablesExist } from "./helpers/clickhouseTables";const TEST_TABLE = "events_full" as const;const PATCH_WAIT_TIMEOUT_MS = 30_000;-interface TableExistsRow {- count: number | string;-}--let eventsTableEnabled: boolean | undefined;--async function isEventsTableEnabled(): Promise<boolean> {- if (eventsTableEnabled !== undefined) {- return eventsTableEnabled;- }- try {- const rows = await queryClickhouse<TableExistsRow>({- query: `- SELECT count() AS count- FROM system.tables- WHERE database = {database: String}- AND name = {table: String}- `,- params: {- database: env.CLICKHOUSE_DB,- table: TEST_TABLE,- },- });- eventsTableEnabled = Number(rows[0]?.count ?? 0) > 0;- } catch {- eventsTableEnabled = false;- }-- return eventsTableEnabled;-}-async function skipUnlessEventsTableEnabled(ctx: TestContext): Promise<void> {- if (!(await isEventsTableEnabled())) {- ctx.skip("events table is not enabled in this ClickHouse");- }+ await skipUnlessClickhouseTablesExist(+ ctx,+ [TEST_TABLE],+ "events table is not enabled in this ClickHouse",+ );if (!redis) {ctx.skip(diff --git a/worker/src/__tests__/eventPropagationJob.test.ts b/worker/src/__tests__/eventPropagationJob.test.tsindex 6ef13ca1ff..45e848ad6b 100644--- a/worker/src/__tests__/eventPropagationJob.test.ts+++ b/worker/src/__tests__/eventPropagationJob.test.ts@@ -19,36 +19,21 @@ import {} from "@langfuse/shared/src/server";import { handleEventPropagationJob } from "../features/eventPropagation/handleEventPropagationJob";import { TableName } from "../services/ClickhouseWriter";+import { skipUnlessClickhouseTablesExist } from "./helpers/clickhouseTables";const LAST_PROCESSED_PARTITION_KEY ="langfuse:event-propagation:last-processed-partition";let previousLastProcessedPartition: string | null = null;-async function clickhouseTableExists(table: string): Promise<boolean> {- const rows = await queryClickhouse<{ count: number | string }>({- query: `- SELECT count() AS count- FROM system.tables- WHERE database = currentDatabase()- AND name = {table: String}- `,- params: { table },- });-- return Number(rows[0]?.count ?? 0) > 0;-}-async function skipUnlessEventPropagationTablesExist(ctx: TestContext,): Promise<void> {- const eventPropagationTablesExist =- (await clickhouseTableExists(TableName.ObservationsBatchStaging)) &&- (await clickhouseTableExists(TableName.EventsFull));-- if (!eventPropagationTablesExist) {- ctx.skip("event propagation ClickHouse tables are not enabled");- }+ await skipUnlessClickhouseTablesExist(+ ctx,+ [TableName.ObservationsBatchStaging, TableName.EventsFull],+ "event propagation ClickHouse tables are not enabled",+ );}function formatClickHouseDateTime(date: Date): string {diff --git a/worker/src/__tests__/helpers/clickhouseTables.ts b/worker/src/__tests__/helpers/clickhouseTables.tsnew file mode 100644index 0000000000..e7d6989caf--- /dev/null+++ b/worker/src/__tests__/helpers/clickhouseTables.ts@@ -0,0 +1,32 @@+import type { TestContext } from "vitest";+import { queryClickhouse } from "@langfuse/shared/src/server";++export async function clickhouseTableExists(table: string): Promise<boolean> {+ try {+ const rows = await queryClickhouse<{ count: number | string }>({+ query: `+ SELECT count() AS count+ FROM system.tables+ WHERE database = currentDatabase()+ AND name = {table: String}+ `,+ params: { table },+ });++ return Number(rows[0]?.count ?? 0) > 0;+ } catch {+ return false;+ }+}++export async function skipUnlessClickhouseTablesExist(+ ctx: TestContext,+ tables: string[],+ message = "required ClickHouse tables are not enabled",+): Promise<void> {+ for (const table of tables) {+ if (!(await clickhouseTableExists(table))) {+ ctx.skip(message);+ }+ }+}diff --git a/worker/src/__tests__/traceBatchDeleteBatchAction.test.ts b/worker/src/__tests__/traceBatchDeleteBatchAction.test.tsnew file mode 100644index 0000000000..a3429d34f5--- /dev/null+++ b/worker/src/__tests__/traceBatchDeleteBatchAction.test.ts@@ -0,0 +1,748 @@+import { randomUUID } from "crypto";+import waitForExpect from "wait-for-expect";+import { describe, expect, it } from "vitest";+import { prisma } from "@langfuse/shared/src/db";+import {+ ActionId,+ BatchActionStatus,+ BatchExportTableName,+ createTraceDeleteBatchActionConfig,+ TraceDeleteBatchActionConfigSchema,+ type FilterState,+} from "@langfuse/shared";+import {+ createEvent,+ createEventsCh,+ createObservation,+ createObservationsCh,+ createOrgProjectAndApiKey,+ createScoresCh,+ createTrace,+ createTraceScore,+ createTracesCh,+ deleteObservationsByTraceIds,+ deleteScoresByTraceIds,+ queryClickhouse,+} from "@langfuse/shared/src/server";+import { processTraceDeleteBatchAction } from "../features/batchAction/processTraceDeleteBatchAction";+import { TraceDeleteBatchActionRunner } from "../features/trace-delete-batch-action-runner";+import { skipUnlessClickhouseTablesExist } from "./helpers/clickhouseTables";++type ClickHouseTable =+ | "traces"+ | "observations"+ | "scores"+ | "events_full"+ | "events_core";++const countByTraceIds = async (+ table: ClickHouseTable,+ projectId: string,+ traceIds: string[],+) => {+ const idColumn = table === "traces" ? "id" : "trace_id";+ const rows = await queryClickhouse<{ count: string }>({+ query: `+ SELECT count(*) as count+ FROM ${table}+ WHERE project_id = {projectId: String}+ AND ${idColumn} IN ({traceIds: Array(String)})+ `,+ params: { projectId, traceIds },+ tags: { projectId },+ });++ return Number(rows[0]?.count ?? 0);+};++const expectCountsEventually = async (+ projectId: string,+ traceIds: string[],+ expected: Partial<Record<ClickHouseTable, number>>,+) => {+ await waitForExpect(async () => {+ await Promise.all(+ Object.entries(expected).map(async ([table, count]) => {+ await expect(+ countByTraceIds(table as ClickHouseTable, projectId, traceIds),+ ).resolves.toBe(count);+ }),+ );+ }, 20_000);+};++const traceDeleteQuery = (userId: string, extraFilters: FilterState = []) => ({+ filter: [+ {+ column: "userId",+ operator: "=" as const,+ value: userId,+ type: "string" as const,+ },+ ...extraFilters,+ ],+ orderBy: { column: "timestamp", order: "DESC" as const },+});++const createTraceDeleteBatchAction = async (opts: {+ projectId: string;+ userId: string;+ useEventsTable: boolean;+ cutoffCreatedAt: Date;+ query: ReturnType<typeof traceDeleteQuery>;+}) => {+ return prisma.batchAction.create({+ data: {+ id: randomUUID(),+ projectId: opts.projectId,+ userId: opts.userId,+ actionType: ActionId.TraceDelete,+ tableName: BatchExportTableName.Traces,+ status: BatchActionStatus.Queued,+ query: {+ ...opts.query,+ useEventsTable: opts.useEventsTable,+ },+ config: createTraceDeleteBatchActionConfig({+ useEventsTable: opts.useEventsTable,+ cutoffCreatedAt: opts.cutoffCreatedAt,+ }),+ totalCount: null,+ processedCount: 0,+ failedCount: 0,+ },+ });+};++const createLegacyArtifacts = async (opts: {+ projectId: string;+ traceIds: string[];+ userId: string;+ timestamp: Date;+}) => {+ await createTracesCh(+ opts.traceIds.map((traceId, index) =>+ createTrace({+ id: traceId,+ project_id: opts.projectId,+ user_id: opts.userId,+ timestamp: opts.timestamp.getTime() + index,+ created_at: opts.timestamp.getTime() + index,+ event_ts: opts.timestamp.getTime() + index,+ }),+ ),+ );+ await createObservationsCh(+ opts.traceIds.map((traceId, index) =>+ createObservation({+ id: randomUUID(),+ trace_id: traceId,+ project_id: opts.projectId,+ start_time: opts.timestamp.getTime() + index,+ created_at: opts.timestamp.getTime() + index,+ event_ts: opts.timestamp.getTime() + index,+ }),+ ),+ );+ await createScoresCh(+ opts.traceIds.map((traceId, index) =>+ createTraceScore({+ id: randomUUID(),+ trace_id: traceId,+ project_id: opts.projectId,+ timestamp: opts.timestamp.getTime() + index,+ created_at: opts.timestamp.getTime() + index,+ event_ts: opts.timestamp.getTime() + index,+ }),+ ),+ );+};++const createEventArtifacts = async (opts: {+ projectId: string;+ traceIds: string[];+ userId: string;+ timestamp: Date;+ parentSpanId?: string;+}) => {+ await createEventsCh(+ opts.traceIds.map((traceId, index) => {+ const eventTime = (opts.timestamp.getTime() + index) * 1000;+ return createEvent({+ id: randomUUID(),+ span_id: randomUUID(),+ parent_span_id: opts.parentSpanId ?? "",+ trace_id: traceId,+ project_id: opts.projectId,+ trace_name: `trace-${traceId}`,+ user_id: opts.userId,+ start_time: eventTime,+ created_at: eventTime,+ updated_at: eventTime,+ event_ts: eventTime,+ });+ }),+ );+ await createScoresCh(+ opts.traceIds.map((traceId, index) =>+ createTraceScore({+ id: randomUUID(),+ trace_id: traceId,+ project_id: opts.projectId,+ timestamp: opts.timestamp.getTime() + index,+ created_at: opts.timestamp.getTime() + index,+ event_ts: opts.timestamp.getTime() + index,+ }),+ ),+ );+};++describe("trace delete batch action worker processor", () => {+ it("deletes only selected legacy traces from a persisted batch action", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const otherProject = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const keepUserId = `keep-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const cutoffCreatedAt = new Date();+ const lateTimestamp = new Date(Date.now() + 3_600_000);+ // The oldest selected trace intentionally sorts after the page cursor id.+ // This catches cursor predicates that incorrectly require id < cursorId+ // across older timestamps.+ const selectedTraceIds = [+ `zzzz-${randomUUID()}`,+ `aaaa-${randomUUID()}`,+ `mmmm-${randomUUID()}`,+ ];+ const nonMatchingTraceId = randomUUID();+ const lateTraceId = randomUUID();+ const otherProjectTraceId = randomUUID();++ await createLegacyArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });+ await createLegacyArtifacts({+ projectId,+ traceIds: [nonMatchingTraceId],+ userId: keepUserId,+ timestamp: beforeCutoff,+ });+ await createLegacyArtifacts({+ projectId: otherProject.projectId,+ traceIds: [otherProjectTraceId],+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: false,+ cutoffCreatedAt,+ query: traceDeleteQuery(deleteUserId),+ });++ await createLegacyArtifacts({+ projectId,+ traceIds: [lateTraceId],+ userId: deleteUserId,+ timestamp: lateTimestamp,+ });++ let leaseExtensions = 0;+ await processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: 2,+ extendLease: async () => {+ leaseExtensions += 1;+ return true;+ },+ });+ expect(leaseExtensions).toBe(2);++ await expectCountsEventually(projectId, selectedTraceIds, {+ traces: 0,+ observations: 0,+ scores: 0,+ });+ await expectCountsEventually(projectId, [nonMatchingTraceId, lateTraceId], {+ traces: 2,+ observations: 2,+ scores: 2,+ });+ await expectCountsEventually(+ otherProject.projectId,+ [otherProjectTraceId],+ {+ traces: 1,+ observations: 1,+ scores: 1,+ },+ );++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Completed);+ expect(updatedBatchAction.processedCount).toBe(3);+ expect(updatedBatchAction.totalCount).toBe(3);+ expect(updatedBatchAction.config).toMatchObject({ inFlightBatch: null });+ });++ it("deletes only selected events-backed traces from a persisted batch action", async (ctx) => {+ await skipUnlessClickhouseTablesExist(+ ctx,+ ["events_full"],+ "events ClickHouse tables are not enabled",+ );++ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const otherProject = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const keepUserId = `keep-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const cutoffCreatedAt = new Date();+ const lateTimestamp = new Date(Date.now() + 3_600_000);+ // The oldest selected trace intentionally sorts after the page cursor id.+ // This catches cursor predicates that incorrectly require id < cursorId+ // across older timestamps.+ const selectedTraceIds = [+ `zzzz-${randomUUID()}`,+ `aaaa-${randomUUID()}`,+ `mmmm-${randomUUID()}`,+ ];+ const nonMatchingTraceId = randomUUID();+ const childOnlyTraceId = randomUUID();+ const lateTraceId = randomUUID();+ const otherProjectTraceId = randomUUID();++ await createEventArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });+ await createEventArtifacts({+ projectId,+ traceIds: [nonMatchingTraceId],+ userId: keepUserId,+ timestamp: beforeCutoff,+ });+ await createEventArtifacts({+ projectId,+ traceIds: [childOnlyTraceId],+ userId: deleteUserId,+ timestamp: beforeCutoff,+ parentSpanId: randomUUID(),+ });+ await createEventArtifacts({+ projectId: otherProject.projectId,+ traceIds: [otherProjectTraceId],+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });++ await expectCountsEventually(projectId, selectedTraceIds, {+ events_core: 3,+ events_full: 3,+ scores: 3,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: true,+ cutoffCreatedAt,+ query: traceDeleteQuery(deleteUserId, [+ {+ column: "isRootObservation",+ operator: "=" as const,+ value: true,+ type: "boolean" as const,+ },+ ]),+ });++ await createEventArtifacts({+ projectId,+ traceIds: [lateTraceId],+ userId: deleteUserId,+ timestamp: lateTimestamp,+ });+ await expectCountsEventually(projectId, [lateTraceId], {+ events_core: 1,+ events_full: 1,+ scores: 1,+ });++ await processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: 2,+ });++ await expectCountsEventually(projectId, selectedTraceIds, {+ events_core: 0,+ events_full: 0,+ scores: 0,+ });+ await expectCountsEventually(+ projectId,+ [nonMatchingTraceId, childOnlyTraceId, lateTraceId],+ {+ events_core: 3,+ events_full: 3,+ scores: 3,+ },+ );+ await expectCountsEventually(+ otherProject.projectId,+ [otherProjectTraceId],+ {+ events_core: 1,+ events_full: 1,+ scores: 1,+ },+ );++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Completed);+ expect(updatedBatchAction.processedCount).toBe(3);+ expect(updatedBatchAction.totalCount).toBe(3);+ expect(updatedBatchAction.config).toMatchObject({+ source: "events",+ inFlightBatch: null,+ });+ });++ it("retries a persisted in-flight batch idempotently", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const keepUserId = `keep-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const selectedTraceIds = [randomUUID(), randomUUID()];+ const nonMatchingTraceId = randomUUID();++ await createLegacyArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });+ await createLegacyArtifacts({+ projectId,+ traceIds: [nonMatchingTraceId],+ userId: keepUserId,+ timestamp: beforeCutoff,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ query: traceDeleteQuery(deleteUserId),+ });++ await deleteObservationsByTraceIds(projectId, [selectedTraceIds[0]]);+ await deleteScoresByTraceIds(projectId, [selectedTraceIds[0]]);++ await prisma.batchAction.update({+ where: { id: batchAction.id },+ data: {+ status: BatchActionStatus.Processing,+ config: {+ ...createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ }),+ failureCount: 3,+ inFlightBatch: {+ traceIds: selectedTraceIds,+ cursorAfter: {+ timestamp: beforeCutoff.toISOString(),+ traceId: selectedTraceIds[0],+ },+ minTimestamp: beforeCutoff.toISOString(),+ maxTimestamp: beforeCutoff.toISOString(),+ },+ },+ },+ });++ await processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: 2,+ });++ await expectCountsEventually(projectId, selectedTraceIds, {+ traces: 0,+ observations: 0,+ scores: 0,+ });+ await expectCountsEventually(projectId, [nonMatchingTraceId], {+ traces: 1,+ observations: 1,+ scores: 1,+ });++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Completed);+ expect(updatedBatchAction.processedCount).toBe(2);+ expect(+ TraceDeleteBatchActionConfigSchema.parse(updatedBatchAction.config),+ ).toMatchObject({+ failureCount: 0,+ inFlightBatch: null,+ });+ });++ it("marks guarded trace deletion skips as failed without throwing", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const selectedTraceIds = [randomUUID()];++ await createLegacyArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ query: traceDeleteQuery(deleteUserId),+ });++ let skippedDeletion:+ | { projectId: string; traceIds: string[]; entityType: string }+ | undefined;++ const result = await processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: 1,+ shouldSkipDeletion: async (seenProjectId, traceIds, entityType) => {+ skippedDeletion = {+ projectId: seenProjectId,+ traceIds,+ entityType,+ };+ return true;+ },+ });++ expect(result).toEqual({+ status: "failed",+ processedBatches: 0,+ });+ expect(skippedDeletion).toEqual({+ projectId,+ traceIds: selectedTraceIds,+ entityType: "trace",+ });+ await expectCountsEventually(projectId, selectedTraceIds, {+ traces: 1,+ observations: 1,+ scores: 1,+ });++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Failed);+ expect(updatedBatchAction.log).toContain("Trace deletion skipped");+ });++ it("does not commit progress after the runner lease is lost", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const selectedTraceIds = [randomUUID(), randomUUID()];++ await createLegacyArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ query: traceDeleteQuery(deleteUserId),+ });++ const inFlightBatch = {+ traceIds: selectedTraceIds,+ cursorAfter: {+ timestamp: beforeCutoff.toISOString(),+ traceId: selectedTraceIds[0],+ },+ minTimestamp: beforeCutoff.toISOString(),+ maxTimestamp: beforeCutoff.toISOString(),+ };++ await prisma.batchAction.update({+ where: { id: batchAction.id },+ data: {+ status: BatchActionStatus.Processing,+ config: {+ ...createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ }),+ inFlightBatch,+ },+ },+ });++ await expect(+ processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: 2,+ canCommitProgress: async () => false,+ }),+ ).rejects.toThrow("lost its worker lease");++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Processing);+ expect(updatedBatchAction.processedCount).toBe(0);+ expect(updatedBatchAction.log).toBeNull();+ expect(+ TraceDeleteBatchActionConfigSchema.parse(updatedBatchAction.config),+ ).toMatchObject({+ failureCount: 0,+ inFlightBatch,+ });+ });++ it("fails a persisted batch action after ten consecutive failures", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const batchActionId = randomUUID();++ await prisma.batchAction.create({+ data: {+ id: batchActionId,+ projectId,+ userId: `user-${randomUUID()}`,+ actionType: ActionId.TraceDelete,+ tableName: BatchExportTableName.Traces,+ status: BatchActionStatus.Queued,+ query: {+ filter: [],+ orderBy: { column: "timestamp", order: "NOPE" },+ useEventsTable: false,+ },+ config: createTraceDeleteBatchActionConfig({+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ }),+ totalCount: null,+ processedCount: 0,+ failedCount: 0,+ },+ });++ for (let i = 0; i < 10; i += 1) {+ await expect(+ processTraceDeleteBatchAction({+ batchActionId,+ batchSize: 1,+ }),+ ).rejects.toThrow();+ }++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchActionId },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Failed);+ expect(updatedBatchAction.log).toContain(+ "failed after 10 consecutive failures",+ );+ expect(+ TraceDeleteBatchActionConfigSchema.parse(updatedBatchAction.config),+ ).toMatchObject({+ failureCount: 10,+ inFlightBatch: null,+ });+ });++ it("runner advances a bounded batch action without queue continuation", async () => {+ const { projectId } = await createOrgProjectAndApiKey({ plan: "Team" });+ const deleteUserId = `delete-user-${randomUUID()}`;+ const beforeCutoff = new Date(Date.now() - 60_000);+ const selectedTraceIds = [randomUUID(), randomUUID()];+ const query = traceDeleteQuery(deleteUserId);++ await prisma.batchAction.updateMany({+ where: {+ actionType: ActionId.TraceDelete,+ tableName: BatchExportTableName.Traces,+ status: {+ in: [BatchActionStatus.Queued, BatchActionStatus.Processing],+ },+ },+ data: {+ status: BatchActionStatus.Failed,+ finishedAt: new Date(),+ log: "Closed by trace delete batch action runner test setup",+ },+ });++ await createLegacyArtifacts({+ projectId,+ traceIds: selectedTraceIds,+ userId: deleteUserId,+ timestamp: beforeCutoff,+ });++ const batchAction = await createTraceDeleteBatchAction({+ projectId,+ userId: `user-${randomUUID()}`,+ useEventsTable: false,+ cutoffCreatedAt: new Date(),+ query,+ });++ const runner = new TraceDeleteBatchActionRunner({+ batchSize: 1,+ maxBatchesPerRun: 1,+ intervalMs: 1_000,+ lockTtlSeconds: 60,+ });++ await runner.processBatch();++ await expectCountsEventually(projectId, selectedTraceIds, {+ traces: 1,+ observations: 1,+ scores: 1,+ });++ const updatedBatchAction = await prisma.batchAction.findUniqueOrThrow({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction.status).toBe(BatchActionStatus.Processing);+ expect(updatedBatchAction.processedCount).toBe(1);+ expect(updatedBatchAction.totalCount).toBeNull();+ expect(updatedBatchAction.config).toMatchObject({+ inFlightBatch: {+ traceIds: [expect.any(String)],+ },+ });+ }, 30_000);+});diff --git a/worker/src/app.ts b/worker/src/app.tsindex a859a6b831..791def7946 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -96,6 +96,7 @@ import { BatchProjectBlobCleaner } from "./features/batch-project-blob-cleaner";import { QueueMetricsRunner } from "./features/queue-metrics-runner";import { MonitorRunner } from "./features/monitor-runner";import { DeletedMaskCleaner } from "./features/deleted-mask-cleaner";+import { TraceDeleteBatchActionRunner } from "./features/trace-delete-batch-action-runner";const app = express();@@ -719,6 +720,15 @@ if (env.LANGFUSE_BATCH_TRACE_DELETION_CLEANER_ENABLED === "true") {batchTraceDeletionCleaner.start();}+// Durable trace-delete BatchAction runner+export let traceDeleteBatchActionRunner: TraceDeleteBatchActionRunner | null =+ null;++if (env.LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_ENABLED === "true") {+ traceDeleteBatchActionRunner = new TraceDeleteBatchActionRunner();+ traceDeleteBatchActionRunner.start();+}+// ClickHouse deleted-mask cleaner for physically applying lightweight delete masksexport let deletedMaskCleaner: DeletedMaskCleaner | null = null;diff --git a/worker/src/env.ts b/worker/src/env.tsindex 79b66edf81..e0be9d60a5 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -466,6 +466,21 @@ const EnvSchema = z.object({.number().positive().default(7200), // 2 hours to handle worst-case deletions+ LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_ENABLED: z+ .enum(["true", "false"])+ .default("true"),+ LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_INTERVAL_MS: z.coerce+ .number()+ .positive()+ .default(10_000),+ LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_LOCK_TTL_SECONDS: z.coerce+ .number()+ .positive()+ .default(1_800),+ LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_MAX_BATCHES_PER_RUN: z.coerce+ .number()+ .positive()+ .default(5),// V4 migration flags. See LFE-9778.LANGFUSE_MIGRATION_V4_WRITE_MODE: zdiff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex 1946de9489..91809e1754 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -67,6 +67,8 @@ async function processActionChunk(try {switch (actionId) {case "trace-delete":+ // Legacy queue path. Durable trace-delete BatchActions are processed+ // by TraceDeleteBatchActionRunner.await traceDeletionProcessor(projectId, chunkIds, { delayMs: 0 });break;diff --git a/worker/src/features/batchAction/processTraceDeleteBatchAction.ts b/worker/src/features/batchAction/processTraceDeleteBatchAction.tsnew file mode 100644index 0000000000..256384d166--- /dev/null+++ b/worker/src/features/batchAction/processTraceDeleteBatchAction.ts@@ -0,0 +1,491 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ ActionId,+ BatchActionQuerySchema,+ BatchActionStatus,+ TraceDeleteBatchActionConfigSchema,+ type FilterCondition,+ type FilterState,+ type TraceDeleteBatchActionConfig,+ type TraceDeleteBatchActionCursor,+} from "@langfuse/shared";+import {+ getTraceDeleteCursorPageFromEvents,+ getTraceDeleteCursorPageFromTraces,+ logger,+ shouldSkipDeletionFor,+} from "@langfuse/shared/src/server";+import { env } from "../../env";+import { processClickhouseTraceDelete } from "../traces/processClickhouseTraceDelete";+import { processPostgresTraceDelete } from "../traces/processPostgresTraceDelete";++type TraceDeleteCursorPageRow = TraceDeleteBatchActionCursor;+type CanCommitProgress = () => Promise<boolean>;+type ExtendLease = () => Promise<boolean>;+type ShouldSkipDeletion = typeof shouldSkipDeletionFor;+type TraceDeleteBatchActionState = {+ status: BatchActionStatus;+ processedCount: number;+ totalCount: number | null;+ finishedAt: Date | null;+ log: string | null;+ config: TraceDeleteBatchActionConfig;+};++export const TRACE_DELETE_BATCH_ACTION_MAX_BATCHES_PER_RUN = 5;+export const TRACE_DELETE_BATCH_ACTION_MAX_FAILURES = 10;++export type ProcessTraceDeleteBatchActionResult =+ | {+ status: "completed";+ processedBatches: number;+ }+ | {+ status: "failed";+ processedBatches: number;+ }+ | {+ status: "yielded";+ processedBatches: number;+ processedCount: number;+ };++class TraceDeleteBatchActionLeaseLostError extends Error {+ constructor(batchActionId: string) {+ super(`Trace delete batch action ${batchActionId} lost its worker lease`);+ this.name = "TraceDeleteBatchActionLeaseLostError";+ }+}++const assertCanCommitProgress = async (opts: {+ batchActionId: string;+ canCommitProgress?: CanCommitProgress;+}) => {+ if (opts.canCommitProgress && !(await opts.canCommitProgress())) {+ throw new TraceDeleteBatchActionLeaseLostError(opts.batchActionId);+ }+};++const extendProcessingLease = async (opts: {+ batchActionId: string;+ extendLease?: ExtendLease;+}) => {+ if (opts.extendLease && !(await opts.extendLease())) {+ throw new TraceDeleteBatchActionLeaseLostError(opts.batchActionId);+ }+};++const convertDatesInFiltersFromStrings = (+ filters: FilterCondition[],+): FilterState => {+ return filters.map((filter) => {+ if (filter.type !== "datetime") {+ return filter;+ }++ const value = (filter as { value: unknown }).value;+ return typeof value === "string"+ ? ({ ...filter, value: new Date(value) } as FilterCondition)+ : filter;+ });+};++const buildInFlightBatch = (rows: TraceDeleteCursorPageRow[]) => {+ const last = rows.at(-1);++ if (!last) {+ return null;+ }++ const timestamps = rows.map((row) => new Date(row.timestamp).getTime());+ const minTimestamp = new Date(Math.min(...timestamps));+ const maxTimestamp = new Date(Math.max(...timestamps));++ return {+ traceIds: rows.map((row) => row.traceId),+ cursorAfter: {+ timestamp: last.timestamp,+ traceId: last.traceId,+ ...(last.id ? { id: last.id } : {}),+ },+ minTimestamp: minTimestamp.toISOString(),+ maxTimestamp: maxTimestamp.toISOString(),+ };+};++const buildTraceDeleteBatchActionState = (+ batchAction: {+ status: string;+ processedCount: number | null;+ totalCount: number | null;+ finishedAt: Date | null;+ log: string | null;+ },+ config: TraceDeleteBatchActionConfig,+): TraceDeleteBatchActionState => ({+ status: batchAction.status as BatchActionStatus,+ processedCount: batchAction.processedCount ?? 0,+ totalCount: batchAction.totalCount,+ finishedAt: batchAction.finishedAt,+ log: batchAction.log,+ config,+});++const markTraceDeleteBatchActionProcessing = (+ state: TraceDeleteBatchActionState,+ config: TraceDeleteBatchActionConfig,+): TraceDeleteBatchActionState => ({+ ...state,+ status: BatchActionStatus.Processing,+ finishedAt: null,+ config,+});++const completeTraceDeleteBatchActionState = (+ state: TraceDeleteBatchActionState,+ processedCount: number,+): TraceDeleteBatchActionState => ({+ ...state,+ status: BatchActionStatus.Completed,+ finishedAt: new Date(),+ processedCount,+ totalCount: processedCount,+ config: {+ ...state.config,+ failureCount: 0,+ inFlightBatch: null,+ },+});++const advanceTraceDeleteBatchActionState = (+ state: TraceDeleteBatchActionState,+ processedCount: number,+ inFlightBatch: NonNullable<TraceDeleteBatchActionConfig["inFlightBatch"]>,+): TraceDeleteBatchActionState => ({+ ...state,+ status: BatchActionStatus.Processing,+ finishedAt: null,+ processedCount,+ config: {+ ...state.config,+ failureCount: 0,+ inFlightBatch,+ },+});++const failTraceDeleteBatchActionState = (+ state: TraceDeleteBatchActionState,+ opts: {+ failureCount?: number;+ log: string;+ finishedAt?: Date | null;+ },+): TraceDeleteBatchActionState => ({+ ...state,+ status: opts.finishedAt ? BatchActionStatus.Failed : state.status,+ finishedAt: opts.finishedAt ?? state.finishedAt,+ log: opts.log,+ config:+ opts.failureCount === undefined+ ? state.config+ : {+ ...state.config,+ failureCount: opts.failureCount,+ },+});++const commitTraceDeleteBatchActionState = async (opts: {+ batchActionId: string;+ state: TraceDeleteBatchActionState;+ canCommitProgress?: CanCommitProgress;+}) => {+ await assertCanCommitProgress(opts);++ await prisma.batchAction.update({+ where: { id: opts.batchActionId },+ data: {+ status: opts.state.status,+ processedCount: opts.state.processedCount,+ failedCount: 0,+ totalCount: opts.state.totalCount,+ finishedAt: opts.state.finishedAt,+ log: opts.state.log,+ config: opts.state.config,+ },+ });+};++const selectNextTraceDeleteBatch = async (opts: {+ projectId: string;+ query: unknown;+ config: TraceDeleteBatchActionConfig;+ cursor: TraceDeleteBatchActionCursor | null;+ batchSize: number;+}) => {+ const query = BatchActionQuerySchema.parse(opts.query);+ const filter = convertDatesInFiltersFromStrings(query.filter ?? []);+ const cutoffCreatedAt = new Date(opts.config.cutoffCreatedAt);++ const rows =+ opts.config.source === "events"+ ? await getTraceDeleteCursorPageFromEvents({+ projectId: opts.projectId,+ filter,+ cutoffCreatedAt,+ cursor: opts.cursor,+ searchQuery: query.searchQuery,+ searchType: query.searchType ?? ["id"],+ limit: opts.batchSize,+ })+ : await getTraceDeleteCursorPageFromTraces({+ projectId: opts.projectId,+ filter,+ cutoffCreatedAt,+ cursor: opts.cursor,+ searchQuery: query.searchQuery,+ searchType: query.searchType ?? ["id"],+ limit: opts.batchSize,+ });++ return buildInFlightBatch(rows);+};++const getErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : "Unknown trace delete error";++const recordTraceDeleteBatchActionFailure = async (opts: {+ batchActionId: string;+ error: unknown;+ canCommitProgress?: CanCommitProgress;+}) => {+ const batchAction = await prisma.batchAction.findUnique({+ where: { id: opts.batchActionId },+ });++ if (+ !batchAction ||+ batchAction.status === BatchActionStatus.Completed ||+ batchAction.status === BatchActionStatus.Failed+ ) {+ return;+ }++ const config = TraceDeleteBatchActionConfigSchema.parse(batchAction.config);+ const failureCount = config.failureCount + 1;+ const errorMessage = getErrorMessage(opts.error);+ const currentState = buildTraceDeleteBatchActionState(batchAction, config);++ if (failureCount >= TRACE_DELETE_BATCH_ACTION_MAX_FAILURES) {+ await commitTraceDeleteBatchActionState({+ batchActionId: opts.batchActionId,+ canCommitProgress: opts.canCommitProgress,+ state: failTraceDeleteBatchActionState(currentState, {+ failureCount,+ finishedAt: new Date(),+ log: `Trace delete batch action failed after ${failureCount} consecutive failures: ${errorMessage}`,+ }),+ });+ return;+ }++ await commitTraceDeleteBatchActionState({+ batchActionId: opts.batchActionId,+ canCommitProgress: opts.canCommitProgress,+ state: failTraceDeleteBatchActionState(currentState, {+ failureCount,+ log: `Trace delete batch action failure ${failureCount}/${TRACE_DELETE_BATCH_ACTION_MAX_FAILURES}: ${errorMessage}`,+ }),+ });+};++export const processTraceDeleteBatchAction = async ({+ batchActionId,+ batchSize = env.LANGFUSE_DELETE_BATCH_SIZE,+ maxBatchesPerRun = TRACE_DELETE_BATCH_ACTION_MAX_BATCHES_PER_RUN,+ canCommitProgress,+ extendLease,+ shouldSkipDeletion = shouldSkipDeletionFor,+}: {+ batchActionId: string;+ batchSize?: number;+ maxBatchesPerRun?: number;+ canCommitProgress?: CanCommitProgress;+ extendLease?: ExtendLease;+ shouldSkipDeletion?: ShouldSkipDeletion;+}): Promise<ProcessTraceDeleteBatchActionResult> => {+ const maxBatches = Math.max(1, Math.floor(maxBatchesPerRun));+ let processedBatches = 0;+ let lastProcessedCount = 0;++ try {+ while (processedBatches < maxBatches) {+ const batchAction = await prisma.batchAction.findUnique({+ where: { id: batchActionId },+ });++ if (!batchAction) {+ throw new Error(`Trace delete batch action ${batchActionId} not found`);+ }++ if (batchAction.actionType !== ActionId.TraceDelete) {+ throw new Error(+ `Batch action ${batchActionId} is not a trace-delete action`,+ );+ }++ if (+ batchAction.status === BatchActionStatus.Completed ||+ batchAction.status === BatchActionStatus.Failed+ ) {+ return { status: "completed", processedBatches };+ }++ const config = TraceDeleteBatchActionConfigSchema.parse(+ batchAction.config,+ );+ let state = buildTraceDeleteBatchActionState(batchAction, config);+ let inFlightBatch = config.inFlightBatch;++ if (!inFlightBatch) {+ // The durable cursor only exists as part of inFlightBatch. A missing+ // batch means this action is starting from the first page; every later+ // page is persisted before the loop can continue.+ inFlightBatch = await selectNextTraceDeleteBatch({+ projectId: batchAction.projectId,+ query: batchAction.query,+ config,+ cursor: null,+ batchSize,+ });++ if (!inFlightBatch) {+ state = completeTraceDeleteBatchActionState(+ state,+ batchAction.processedCount ?? 0,+ );+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ return { status: "completed", processedBatches };+ }++ state = markTraceDeleteBatchActionProcessing(state, {+ ...config,+ inFlightBatch,+ });+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ } else if (state.status === BatchActionStatus.Queued) {+ state = markTraceDeleteBatchActionProcessing(state, config);+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ }++ logger.info("Processing trace delete batch action page", {+ batchActionId,+ projectId: batchAction.projectId,+ source: state.config.source,+ traceCount: inFlightBatch.traceIds.length,+ });++ if (+ await shouldSkipDeletion(+ batchAction.projectId,+ inFlightBatch.traceIds,+ "trace",+ )+ ) {+ const message = `Trace deletion skipped for batch action ${batchActionId}`;+ state = failTraceDeleteBatchActionState(state, {+ finishedAt: new Date(),+ log: message,+ });+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ return { status: "failed", processedBatches };+ }++ await Promise.all([+ processPostgresTraceDelete(+ batchAction.projectId,+ inFlightBatch.traceIds,+ ),+ processClickhouseTraceDelete(+ batchAction.projectId,+ inFlightBatch.traceIds,+ ),+ ]);++ await extendProcessingLease({ batchActionId, extendLease });++ const nextInFlightBatch = await selectNextTraceDeleteBatch({+ projectId: batchAction.projectId,+ query: batchAction.query,+ config: state.config,+ cursor: inFlightBatch.cursorAfter,+ batchSize,+ });+ const processedCount =+ (batchAction.processedCount ?? 0) + inFlightBatch.traceIds.length;+ processedBatches += 1;+ lastProcessedCount = processedCount;++ if (!nextInFlightBatch) {+ state = completeTraceDeleteBatchActionState(state, processedCount);+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ return { status: "completed", processedBatches };+ }++ state = advanceTraceDeleteBatchActionState(+ state,+ processedCount,+ nextInFlightBatch,+ );+ await commitTraceDeleteBatchActionState({+ batchActionId,+ canCommitProgress,+ state,+ });+ }++ return {+ status: "yielded",+ processedBatches,+ processedCount: lastProcessedCount,+ };+ } catch (error) {+ if (error instanceof TraceDeleteBatchActionLeaseLostError) {+ throw error;+ }++ try {+ await recordTraceDeleteBatchActionFailure({+ batchActionId,+ error,+ canCommitProgress,+ });+ } catch (recordError) {+ logger.error("Failed to record trace delete batch action failure", {+ batchActionId,+ error: recordError,+ });+ }++ throw error;+ }+};diff --git a/worker/src/features/trace-delete-batch-action-runner/index.ts b/worker/src/features/trace-delete-batch-action-runner/index.tsnew file mode 100644index 0000000000..0f65cf871a--- /dev/null+++ b/worker/src/features/trace-delete-batch-action-runner/index.ts@@ -0,0 +1,213 @@+import {+ ActionId,+ BatchActionStatus,+ BatchExportTableName,+ TraceDeleteBatchActionConfigSchema,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import {+ logger,+ recordGauge,+ recordIncrement,+ traceException,+} from "@langfuse/shared/src/server";+import { env } from "../../env";+import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";+import { processTraceDeleteBatchAction } from "../batchAction/processTraceDeleteBatchAction";++const METRIC_PREFIX = "langfuse.trace_delete_batch_action_runner";++export const TRACE_DELETE_BATCH_ACTION_RUNNER_LOCK_KEY =+ "langfuse:trace-delete-batch-action-runner";++const ACTIVE_BATCH_ACTION_STATUSES = [+ BatchActionStatus.Queued,+ BatchActionStatus.Processing,+];++const ACTIVE_TRACE_DELETE_BATCH_ACTION_WHERE = {+ actionType: ActionId.TraceDelete,+ tableName: BatchExportTableName.Traces,+ status: { in: ACTIVE_BATCH_ACTION_STATUSES },+};++type ActiveTraceDeleteBatchAction = {+ id: string;+ projectId: string;+ status: string;+ processedCount: number | null;+ failedCount: number | null;+ updatedAt: Date;+ config: unknown;+};++type ActiveTraceDeleteBatchActionWorkload = {+ activeActionCount: number;+ batchAction: ActiveTraceDeleteBatchAction | null;+};++export class TraceDeleteBatchActionRunner extends PeriodicExclusiveRunner {+ private readonly intervalMs: number;+ private readonly lockTtlSeconds: number;+ private readonly batchSize: number;+ private readonly maxBatchesPerRun: number;++ protected get defaultIntervalMs(): number {+ return this.intervalMs;+ }++ constructor(+ opts: {+ intervalMs?: number;+ lockTtlSeconds?: number;+ batchSize?: number;+ maxBatchesPerRun?: number;+ } = {},+ ) {+ const lockTtlSeconds =+ opts.lockTtlSeconds ??+ env.LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_LOCK_TTL_SECONDS;++ super({+ name: "TraceDeleteBatchActionRunner",+ lockKey: TRACE_DELETE_BATCH_ACTION_RUNNER_LOCK_KEY,+ lockTtlSeconds,+ onUnavailable: "fail",+ });++ this.lockTtlSeconds = lockTtlSeconds;+ this.intervalMs =+ opts.intervalMs ??+ env.LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_INTERVAL_MS;+ this.batchSize = opts.batchSize ?? env.LANGFUSE_DELETE_BATCH_SIZE;+ this.maxBatchesPerRun =+ opts.maxBatchesPerRun ??+ env.LANGFUSE_TRACE_DELETE_BATCH_ACTION_RUNNER_MAX_BATCHES_PER_RUN;+ }++ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ intervalMs: this.intervalMs,+ lockTtlSeconds: this.lockTtlSeconds,+ batchSize: this.batchSize,+ maxBatchesPerRun: this.maxBatchesPerRun,+ });+ super.start();+ }++ protected async execute(): Promise<number | void> {+ return await this.withLock(+ async () => {+ // Treat active trace-delete BatchActions as a global work queue. Each+ // processing pass handles only maxBatchesPerRun; if it yields, the+ // updated row moves to the back via updatedAt, and returning 0 makes+ // the runner immediately poll again so other active actions can run.+ let workload: ActiveTraceDeleteBatchActionWorkload;+ try {+ workload = await this.getActiveWorkload();+ } catch (error) {+ logger.error(`${this.instanceName}: Failed to query active actions`, {+ error,+ });+ traceException(error);+ recordIncrement(`${METRIC_PREFIX}.query_failures`, 1);+ throw error;+ }++ const { activeActionCount, batchAction } = workload;+ recordGauge(`${METRIC_PREFIX}.active_actions`, activeActionCount);+ if (!batchAction) {+ logger.debug(`${this.instanceName}: No active trace delete actions`);+ recordGauge(`${METRIC_PREFIX}.oldest_active_action_age_seconds`, 0);+ return;+ }++ const config = TraceDeleteBatchActionConfigSchema.safeParse(+ batchAction.config,+ );+ const source = config.success ? config.data.source : "unknown";+ const oldestActionAgeSeconds = Math.max(+ Math.floor((Date.now() - batchAction.updatedAt.getTime()) / 1000),+ 0,+ );+ recordGauge(+ `${METRIC_PREFIX}.oldest_active_action_age_seconds`,+ oldestActionAgeSeconds,+ );++ logger.info(`${this.instanceName}: Processing trace delete action`, {+ batchActionId: batchAction.id,+ projectId: batchAction.projectId,+ status: batchAction.status,+ source,+ activeActionCount,+ oldestActionAgeSeconds,+ processedCount: batchAction.processedCount,+ failedCount: batchAction.failedCount,+ });++ const result = await processTraceDeleteBatchAction({+ batchActionId: batchAction.id,+ batchSize: this.batchSize,+ maxBatchesPerRun: this.maxBatchesPerRun,+ canCommitProgress: () => this.lock.isHeldByCurrentProcess(),+ extendLease: () => this.lock.extend(),+ });++ logger.info(`${this.instanceName}: Trace delete action processed`, {+ batchActionId: batchAction.id,+ projectId: batchAction.projectId,+ source,+ resultStatus: result.status,+ processedBatches: result.processedBatches,+ processedCount:+ result.status === "yielded" ? result.processedCount : undefined,+ });++ recordIncrement(`${METRIC_PREFIX}.actions_processed`, 1, {+ status: result.status,+ source,+ });+ recordIncrement(+ `${METRIC_PREFIX}.batches_processed`,+ result.processedBatches,+ {+ status: result.status,+ source,+ },+ );++ return result.status === "yielded" ? 0 : undefined;+ },+ () => {+ recordIncrement(`${METRIC_PREFIX}.processing_failures`, 1);+ },+ );+ }++ private async getActiveWorkload(): Promise<ActiveTraceDeleteBatchActionWorkload> {+ const [activeActionCount, batchAction] = await prisma.$transaction([+ prisma.batchAction.count({+ where: ACTIVE_TRACE_DELETE_BATCH_ACTION_WHERE,+ }),+ prisma.batchAction.findFirst({+ where: ACTIVE_TRACE_DELETE_BATCH_ACTION_WHERE,+ orderBy: [{ updatedAt: "asc" }],+ select: {+ id: true,+ projectId: true,+ status: true,+ processedCount: true,+ failedCount: true,+ updatedAt: true,+ config: true,+ },+ }),+ ]);++ return {+ activeActionCount,+ batchAction,+ };+ }+}diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 78b1957ee8..3bf28b3a92 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -24,6 +24,7 @@ import {TraceRecordReadType,createOrgProjectAndApiKey,createIngestionEventSchema,+ getObservationsV2FromEventsTableForPublicApi,queryClickhouse,setNoEvalConfigsCache,} from "@langfuse/shared/src/server";@@ -31,6 +32,10 @@ import waitForExpect from "wait-for-expect";import { ClickhouseWriter, TableName } from "../../ClickhouseWriter";import { IngestionService } from "../../IngestionService";import { ModelUsageUnit, ScoreSourceEnum } from "@langfuse/shared";+import {+ clickhouseTableExists,+ skipUnlessClickhouseTablesExist,+} from "../../../__tests__/helpers/clickhouseTables";let projectId = "";const environment = "default";@@ -39,7 +44,14 @@ const testIngestionAttribution = {ingestionSdkName: "langfuse-test",ingestionSdkVersion: "0.0.0",};-let observationsBatchStagingTableEnabled: boolean | undefined;++async function skipUnlessEventsTablesExist(ctx: TestContext): Promise<void> {+ await skipUnlessClickhouseTablesExist(+ ctx,+ [TableName.EventsFull],+ "events ClickHouse tables are not enabled",+ );+}describe("Ingestion end-to-end tests", () => {let ingestionService: IngestionService;@@ -119,6 +131,104 @@ describe("Ingestion end-to-end tests", () => {expect(trace.timestamp).toBe(timestamp);});+ it("should paginate events with sub-millisecond wire timestamps after ingestion normalization", async (ctx) => {+ await skipUnlessEventsTablesExist(ctx);++ const traceId = randomUUID();+ const firstSpanId = randomUUID();+ const secondSpanId = randomUUID();+ const wireStartTimeA = "2026-01-01T12:00:00.123456Z";+ const wireStartTimeB = "2026-01-01T12:00:00.123789Z";+ const normalizedStartTime = Date.parse(wireStartTimeA) * 1000;++ const eventRecords = await Promise.all(+ [+ { spanId: firstSpanId, startTimeISO: wireStartTimeA },+ { spanId: secondSpanId, startTimeISO: wireStartTimeB },+ ].map((event) =>+ ingestionService.createEventRecord(+ {+ projectId,+ traceId,+ spanId: event.spanId,+ parentSpanId: "",+ name: `sub-ms-cursor-${event.spanId}`,+ type: "SPAN",+ environment,+ startTimeISO: event.startTimeISO,+ endTimeISO: "2026-01-01T12:00:00.124000Z",+ metadata: {},+ source: "test",+ },+ `sub-ms-cursor/${event.spanId}.json`,+ ),+ ),+ );++ expect(eventRecords.map((record) => record.start_time)).toEqual([+ normalizedStartTime,+ normalizedStartTime,+ ]);+ expect(eventRecords.every((record) => record.start_time % 1000 === 0)).toBe(+ true,+ );++ eventRecords.forEach((record) => ingestionService.writeEventRecord(record));+ await clickhouseWriter.flushAll(true);++ await waitForExpect(async () => {+ const rows = await queryClickhouse<{ count: string }>({+ query: `+ SELECT count() AS count+ FROM events_core+ WHERE project_id = {projectId: String}+ AND trace_id = {traceId: String}+ AND span_id IN ({spanIds: Array(String)})+ `,+ params: {+ projectId,+ traceId,+ spanIds: [firstSpanId, secondSpanId],+ },+ });++ expect(Number(rows[0]?.count ?? 0)).toBe(2);+ }, 5_000);++ const firstPageItems = await getObservationsV2FromEventsTableForPublicApi({+ projectId,+ traceId,+ page: 1,+ limit: 1,+ fields: ["core"],+ });+ const firstPage = firstPageItems.slice(0, 1);+ expect(firstPage).toHaveLength(1);++ const firstItem = firstPage[0]!;+ expect(firstItem.startTime.getTime()).toBe(Date.parse(wireStartTimeA));++ const secondPageItems = await getObservationsV2FromEventsTableForPublicApi({+ projectId,+ traceId,+ page: 1,+ limit: 1,+ fields: ["core"],+ cursor: {+ lastStartTimeTo: firstItem.startTime,+ lastTraceId: firstItem.traceId!,+ lastId: firstItem.id,+ },+ });+ const secondPage = secondPageItems.slice(0, 1);+ expect(secondPage).toHaveLength(1);++ expect(secondPage[0]!.id).not.toBe(firstItem.id);+ expect(new Set([firstItem.id, secondPage[0]!.id])).toEqual(+ new Set([firstSpanId, secondSpanId]),+ );+ });+it("should write ingestion attribution to observation staging records", async (ctx) => {await skipUnlessObservationsBatchStagingEnabled(ctx);@@ -3067,28 +3177,7 @@ type RecordReadType<T extends TableName> = T extends TableName.Scores: never;async function isObservationsBatchStagingEnabled(): Promise<boolean> {- if (observationsBatchStagingTableEnabled !== undefined) {- return observationsBatchStagingTableEnabled;- }-- try {- const rows = await queryClickhouse<{ count: number | string }>({- query: `- SELECT count() AS count- FROM system.tables- WHERE database = currentDatabase()- AND name = {table: String}- `,- params: {- table: TableName.ObservationsBatchStaging,- },- });- observationsBatchStagingTableEnabled = Number(rows[0]?.count ?? 0) > 0;- } catch {- observationsBatchStagingTableEnabled = false;- }-- return observationsBatchStagingTableEnabled;+ return clickhouseTableExists(TableName.ObservationsBatchStaging);}async function skipUnlessObservationsBatchStagingEnabled(diff --git a/worker/src/utils/RedisLock.ts b/worker/src/utils/RedisLock.tsindex 2c7e2f5f8b..57e2c07945 100644--- a/worker/src/utils/RedisLock.ts+++ b/worker/src/utils/RedisLock.ts@@ -59,10 +59,62 @@ export class RedisLock {end`;+ private static readonly EXTEND_LOCK_SCRIPT = `+ if redis.call("get", KEYS[1]) == ARGV[1] then+ return redis.call("expire", KEYS[1], ARGV[2])+ else+ return 0+ end+ `;+public get key(): string {return this.lockKey;}+ public async isHeldByCurrentProcess(): Promise<boolean> {+ if (!redis) {+ return this.onUnavailable === "proceed";+ }++ try {+ return (await redis.get(this.lockKey)) === this.lockValue;+ } catch (error) {+ logger.error(`[${this.name}] Failed to check lock ownership`, error);+ return false;+ }+ }++ public async extend(): Promise<boolean> {+ if (!redis) {+ return this.onUnavailable === "proceed";+ }++ try {+ const result = await redis.eval(+ RedisLock.EXTEND_LOCK_SCRIPT,+ 1,+ this.lockKey,+ this.lockValue,+ String(this.ttlSeconds),+ );++ if (result === 1) {+ logger.debug(+ `[${this.name}] Extended lock with TTL ${this.ttlSeconds}s`,+ );+ return true;+ }++ logger.warn(+ `[${this.name}] Lock was not extended (not owned or already expired)`,+ );+ return false;+ } catch (error) {+ logger.error(`[${this.name}] Failed to extend lock`, error);+ return false;+ }+ }+constructor(lockKey: string,options: {diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex 8265a06c51..95c7e2b480 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -17,6 +17,7 @@ import {batchProjectMediaCleaner,batchProjectBlobCleaner,batchTraceDeletionCleaner,+ traceDeleteBatchActionRunner,deletedMaskCleaner,queueMetricsRunner,monitorRunners,@@ -52,6 +53,9 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {// Stop batch trace deletion cleanerbatchTraceDeletionCleaner?.stop();+ // Stop durable trace-delete batch action runner+ traceDeleteBatchActionRunner?.stop();+// Stop deleted-mask cleanerdeletedMaskCleaner?.stop();