Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(annotation): introduce conditional read from events table for batch action (#13585)

marliessophie053185ed989f
diff --git a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
index e36b5a92e3..f574235123 100644
--- a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
+++ b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
@@ -59,7 +59,10 @@ const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<
},
[AnnotationQueueObjectType.OBSERVATION]: {
actionId: ActionId.ObservationAddToAnnotationQueue,
- tableName: BatchExportTableName.Observations,
+ tableName:
+ env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true"
+ ? BatchExportTableName.Events
+ : BatchExportTableName.Observations,
},
};
@@ -296,10 +299,7 @@ export const queueItemRouter = createTRPCRouter({
let createdCount = 0;
if (input.isBatchAction && input.query) {
- const actionProps =
- MAP_OBJECT_TYPE_TO_ACTION_PROPS[
- input.objectType as "TRACE" | "SESSION"
- ];
+ const actionProps = MAP_OBJECT_TYPE_TO_ACTION_PROPS[input.objectType];
if (!actionProps) {
throw new TRPCError({
code: "BAD_REQUEST",
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index 8f23ba181b..9e863cbd4a 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -672,6 +672,122 @@ describe("select all test suite", () => {
expect(jobs).toHaveLength(0);
});
});
+
+ it("should add traces to annotation queue", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId1 = uuidv4();
+ const traceId2 = uuidv4();
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: traceId1,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ id: traceId2,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ const queueId = uuidv4();
+ await prisma.annotationQueue.create({
+ data: {
+ id: queueId,
+ projectId,
+ name: "test-queue",
+ },
+ });
+
+ await handleBatchActionJob({
+ id: uuidv4(),
+ timestamp: new Date(),
+ name: QueueJobs.BatchActionProcessingJob as const,
+ payload: {
+ projectId,
+ actionId: "trace-add-to-annotation-queue" as const,
+ tableName: BatchExportTableName.Traces,
+ cutoffCreatedAt: new Date("2024-01-02"),
+ targetId: queueId,
+ query: { filter: [], orderBy: { column: "timestamp", order: "DESC" } },
+ type: BatchActionType.Create,
+ },
+ });
+
+ const queueItems = await prisma.annotationQueueItem.findMany({
+ where: { queueId, projectId },
+ });
+
+ expect(queueItems).toHaveLength(2);
+ const objectIds = queueItems.map((item) => item.objectId);
+ expect(objectIds).toContain(traceId1);
+ expect(objectIds).toContain(traceId2);
+ expect(queueItems.every((item) => item.objectType === "TRACE")).toBe(true);
+ });
+
+ it("should add sessions to annotation queue", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const sessionId1 = uuidv4();
+ const sessionId2 = uuidv4();
+
+ // Create traces with sessions
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: uuidv4(),
+ session_id: sessionId1,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ id: uuidv4(),
+ session_id: sessionId2,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ const queueId = uuidv4();
+ await prisma.annotationQueue.create({
+ data: {
+ id: queueId,
+ projectId,
+ name: "test-queue",
+ },
+ });
+
+ await handleBatchActionJob({
+ id: uuidv4(),
+ timestamp: new Date(),
+ name: QueueJobs.BatchActionProcessingJob as const,
+ payload: {
+ projectId,
+ actionId: "session-add-to-annotation-queue" as const,
+ tableName: BatchExportTableName.Sessions,
+ cutoffCreatedAt: new Date("2024-01-02"),
+ targetId: queueId,
+ query: { filter: [], orderBy: { column: "createdAt", order: "DESC" } },
+ type: BatchActionType.Create,
+ },
+ });
+
+ const queueItems = await prisma.annotationQueueItem.findMany({
+ where: { queueId, projectId },
+ });
+
+ expect(queueItems).toHaveLength(2);
+ const objectIds = queueItems.map((item) => item.objectId);
+ expect(objectIds).toContain(sessionId1);
+ expect(objectIds).toContain(sessionId2);
+ expect(queueItems.every((item) => item.objectType === "SESSION")).toBe(
+ true,
+ );
+ });
});
maybeDescribe("events table batch actions", () => {
@@ -813,8 +929,8 @@ maybeDescribe("events table batch actions", () => {
const event = createEvent({
project_id: projectId,
trace_id: traceId,
- input: eventInput,
- output: eventOutput,
+ input: JSON.stringify(eventInput),
+ output: JSON.stringify(eventOutput),
metadata_names: Object.keys(eventMetadata),
metadata_values: Object.values(eventMetadata),
});
@@ -935,4 +1051,68 @@ maybeDescribe("events table batch actions", () => {
expect(updatedBatchAction?.status).toBe(BatchActionStatus.Completed);
expect(updatedBatchAction?.processedCount).toBe(1);
});
+
+ it("should add observations to annotation queue from events table", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId = uuidv4();
+ const trace = createTrace({
+ project_id: projectId,
+ id: traceId,
+ timestamp: new Date().getTime(),
+ });
+ await createTracesCh([trace]);
+
+ const event1 = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ input: JSON.stringify({ prompt: "Hello" }),
+ output: JSON.stringify({ response: "Hi" }),
+ });
+ const event2 = createEvent({
+ project_id: projectId,
+ trace_id: traceId,
+ input: JSON.stringify({ prompt: "Goodbye" }),
+ output: JSON.stringify({ response: "Bye" }),
+ });
+
+ await createEventsCh([event1, event2]);
+
+ // Create annotation queue
+ const queueId = uuidv4();
+ await prisma.annotationQueue.create({
+ data: {
+ id: queueId,
+ projectId,
+ name: "test-queue",
+ },
+ });
+
+ await handleBatchActionJob({
+ id: uuidv4(),
+ timestamp: new Date(),
+ name: QueueJobs.BatchActionProcessingJob as const,
+ payload: {
+ projectId,
+ actionId: "observation-add-to-annotation-queue" as const,
+ tableName: BatchTableNames.Events,
+ cutoffCreatedAt: new Date(),
+ targetId: queueId,
+ query: { filter: [], orderBy: null },
+ type: BatchActionType.Create,
+ },
+ });
+
+ const queueItems = await prisma.annotationQueueItem.findMany({
+ where: { queueId, projectId },
+ });
+
+ expect(queueItems).toHaveLength(2);
+
+ const eventSpanIds = [event1.span_id, event2.span_id];
+ for (const item of queueItems) {
+ expect(eventSpanIds).toContain(item.objectId);
+ expect(item.objectType).toBe("OBSERVATION");
+ }
+ });
});
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index ef7e07d318..faeb54d801 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -34,6 +34,7 @@ import { getObservationStream } from "../database-read-stream/observation-stream
import {
getEventsStreamForEval,
getEventsStreamForDataset,
+ getEventsStreamForAnnotationQueue,
} from "../database-read-stream/event-stream";
import { processAddObservationsToDataset } from "./processAddObservationsToDataset";
import { ObservationAddToDatasetConfigSchema } from "@langfuse/shared";
@@ -173,33 +174,29 @@ export const handleBatchActionJob = async (
throw new Error(`Target ID is required for create action`);
}
+ const streamParams = {
+ projectId: projectId,
+ cutoffCreatedAt: new Date(cutoffCreatedAt),
+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),
+ searchQuery: query.searchQuery ?? undefined,
+ searchType: query.searchType ?? ["id" as const],
+ };
+
const dbReadStream =
actionId === "trace-delete"
? await getTraceIdentifierStream({
- projectId: projectId,
- cutoffCreatedAt: new Date(cutoffCreatedAt),
- filter: convertDatesInFiltersFromStrings(query.filter ?? []),
+ ...streamParams,
orderBy: query.orderBy,
- searchQuery: query.searchQuery ?? undefined,
- searchType: query.searchType ?? ["id" as const],
})
- : tableName === BatchTableNames.Observations
- ? await getObservationStream({
- projectId: projectId,
- cutoffCreatedAt: new Date(cutoffCreatedAt),
- filter: convertDatesInFiltersFromStrings(query.filter ?? []),
- searchQuery: query.searchQuery ?? undefined,
- searchType: query.searchType ?? ["id" as const],
- })
- : await getDatabaseReadStreamPaginated({
- projectId: projectId,
- cutoffCreatedAt: new Date(cutoffCreatedAt),
- filter: convertDatesInFiltersFromStrings(query.filter ?? []),
- orderBy: query.orderBy,
- tableName: tableName as BatchTableNames,
- searchQuery: query.searchQuery ?? undefined,
- searchType: query.searchType ?? ["id" as const],
- });
+ : tableName === BatchTableNames.Events
+ ? await getEventsStreamForAnnotationQueue(streamParams)
+ : tableName === BatchTableNames.Observations
+ ? await getObservationStream(streamParams)
+ : await getDatabaseReadStreamPaginated({
+ ...streamParams,
+ orderBy: query.orderBy,
+ tableName: tableName as BatchTableNames,
+ });
// Process stream in database-sized batches
// 1. Read all records
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
index 9676914e74..af265d1334 100644
--- a/worker/src/features/database-read-stream/event-stream.ts
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -602,3 +602,109 @@ export const getEventsStreamForDataset = async (props: {
})(),
);
};
+
+/**
+ * Lightweight event stream for batch add-to-annotation-queue.
+ * Only fetches the fields needed for annotation queue item creation:
+ * id, traceId.
+ */
+export const getEventsStreamForAnnotationQueue = async (props: {
+ projectId: string;
+ cutoffCreatedAt: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit?: number;
+}): Promise<Readable> => {
+ const {
+ projectId,
+ cutoffCreatedAt,
+ filter = [],
+ searchQuery,
+ searchType,
+ rowLimit = env.BATCH_EXPORT_ROW_LIMIT,
+ } = props;
+
+ const eventOnlyFilters = (filter ?? []).filter((f) => {
+ const columnDef = eventsTableUiColumnDefinitions.find(
+ (col) => col.uiTableName === f.column || col.uiTableId === f.column,
+ );
+
+ return (
+ columnDef?.clickhouseTableName !== "scores" &&
+ columnDef?.clickhouseTableName !== "comments"
+ );
+ });
+
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ [
+ ...eventOnlyFilters,
+ {
+ column: "startTime",
+ operator: "<" as const,
+ value: cutoffCreatedAt,
+ type: "datetime" as const,
+ },
+ ],
+ eventsTableUiColumnDefinitions,
+ eventsTableCols,
+ ),
+ );
+
+ const appliedEventsFilter = eventsFilter.apply();
+
+ const search = clickhouseSearchCondition(searchQuery, searchType, "e", [
+ "span_id",
+ "name",
+ "trace_name",
+ "user_id",
+ "session_id",
+ "trace_id",
+ ]);
+
+ const eventsQuery = new EventsQueryBuilder({ projectId })
+ .selectFieldSet("core")
+ .where(appliedEventsFilter)
+ .where(search)
+ .whereRaw("e.is_deleted = 0")
+ .orderByDefault()
+ .limitBy("e.span_id", "e.project_id")
+ .limit(rowLimit);
+
+ const { query, params: queryParams } = eventsQuery.buildWithParams();
+
+ type AnnotationQueueEventRow = {
+ id: string;
+ trace_id: string;
+ };
+
+ const asyncGenerator = queryClickhouseStream<AnnotationQueueEventRow>({
+ query,
+ params: queryParams,
+ clickhouseConfigs: {
+ request_timeout: 180_000,
+ clickhouse_settings: {
+ http_send_timeout: 300,
+ http_receive_timeout: 300,
+ },
+ },
+ tags: {
+ feature: "batch-add-to-annotation-queue",
+ type: "event",
+ kind: "annotation",
+ projectId,
+ },
+ });
+
+ return Readable.from(
+ (async function* () {
+ for await (const row of asyncGenerator) {
+ yield {
+ id: row.id,
+ traceId: row.trace_id,
+ };
+ }
+ })(),
+ );
+};