Skip to content

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

perf: events table io loading (#11178)

Max Deichmann0dbc7945e516
diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.ts
index 0aebf2b37c..9fa630c07d 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts
@@ -6,13 +6,18 @@ export const clickhouseSearchCondition = (
query?: string,
searchType?: TracingSearchType[],
tablePrefix?: string,
+ searchColumns?: string[],
) => {
const prefix = tablePrefix ? `${tablePrefix}.` : "";
+ const cols = searchColumns
+ ? searchColumns
+ : [`${prefix}id`, `t.user_id`, `${prefix}name`];
+
// We use a hard-coded prefix for user_id as it only occurs in the trace context.
const conditions = [
!searchType || searchType.includes("id")
- ? `${prefix}id ILIKE {searchString: String} OR t.user_id ILIKE {searchString: String} OR ${prefix}name ILIKE {searchString: String}`
+ ? cols.map((col) => `${col} ILIKE {searchString: String}`).join(" OR ")
: null,
searchType && searchType.includes("content")
? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 39987f2e31..f497f9564c 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -37,7 +37,11 @@ import {
eventsTableUiColumnDefinitions,
} from "../tableMappings/mapEventsTable";
import { tracesTableUiColumnDefinitions } from "../tableMappings/mapTracesTable";
-import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";
+import {
+ applyInputOutputRendering,
+ DEFAULT_RENDERING_PROPS,
+ RenderingProps,
+} from "../utils/rendering";
import { commandClickhouse, queryClickhouse } from "./clickhouse";
import { ObservationRecordReadType, TraceRecordReadType } from "./definitions";
import {
@@ -55,6 +59,7 @@ import {
} from "../queries/clickhouse-sql/event-query-builder";
import { type EventsObservationPublic } from "../queries/createGenerationsQuery";
import { UiColumnMappings } from "../../tableDefinitions";
+import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
type ObservationsTableQueryResultWitouhtTraceFields = Omit<
ObservationsTableQueryResult,
@@ -335,6 +340,7 @@ async function getObservationsFromEventsTableInternal<T>(
opts.searchQuery,
opts.searchType,
"e",
+ ["span_id", "name", "user_id", "session_id", "trace_id"],
);
// Query optimization: joining traces onto observations is expensive.
@@ -1720,3 +1726,78 @@ export const deleteEventsOlderThanDays = async (
},
});
};
+
+export const getObservationsBatchIOFromEventsTable = async (opts: {
+ projectId: string;
+ observations: Array<{
+ id: string;
+ traceId: string;
+ startTime: Date;
+ }>;
+}): Promise<
+ Array<Pick<Observation, "id" | "input" | "output" | "metadata">>
+> => {
+ if (opts.observations.length === 0) {
+ return [];
+ }
+
+ // Extract IDs and trace IDs for filtering
+ const observationIds = opts.observations.map((o) => o.id);
+ const traceIds = [...new Set(opts.observations.map((o) => o.traceId))];
+
+ // Calculate timestamp range with buffer for efficient filtering
+ const timestamps = opts.observations.map((o) => o.startTime.getTime());
+ const minTimestamp = new Date(Math.min(...timestamps) - 1000); // -1 second buffer
+ const maxTimestamp = new Date(Math.max(...timestamps) + 1000); // +1 second buffer
+
+ const query = `
+ SELECT
+ e.span_id as id,
+ leftUTF8(e.input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as input,
+ leftUTF8(e.output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT}) as output,
+ mapFromArrays(e.metadata_names, e.metadata_prefixes) as metadata
+ FROM events e
+ WHERE e.project_id = {projectId: String}
+ AND e.span_id IN {observationIds: Array(String)}
+ AND e.trace_id IN {traceIds: Array(String)}
+ AND e.start_time >= {minTimestamp: DateTime64(3)}
+ AND e.start_time <= {maxTimestamp: DateTime64(3)}
+ `;
+
+ const results = await queryClickhouse<{
+ id: string;
+ input: string | null;
+ output: string | null;
+ metadata: Record<string, string>;
+ }>({
+ query,
+ params: {
+ projectId: opts.projectId,
+ observationIds,
+ traceIds,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ tags: {
+ feature: "tracing",
+ type: "events",
+ kind: "batchIO",
+ projectId: opts.projectId,
+ },
+ preferredClickhouseService: "ReadOnly",
+ });
+
+ return results.map((r) => ({
+ id: r.id,
+ input:
+ r.input !== undefined
+ ? applyInputOutputRendering(r.input, DEFAULT_RENDERING_PROPS)
+ : null,
+ output:
+ r.output !== undefined
+ ? applyInputOutputRendering(r.output, DEFAULT_RENDERING_PROPS)
+ : null,
+ metadata:
+ r.metadata !== undefined ? parseMetadataCHRecordToDomain(r.metadata) : {},
+ }));
+};
diff --git a/web/src/__tests__/async/events-service.servertest.ts b/web/src/__tests__/async/events-service.servertest.ts
deleted file mode 100644
index 8996769199..0000000000
--- a/web/src/__tests__/async/events-service.servertest.ts
+++ /dev/null
@@ -1,853 +0,0 @@
-import { v4 } from "uuid";
-import { createEvent, createTraceScore } from "@langfuse/shared/src/server";
-import { createEventsCh, createScoresCh } from "@langfuse/shared/src/server";
-import {
- getEventList,
- getEventCount,
- getEventFilterOptions,
-} from "@/src/features/events/server/eventsService";
-import { type ObservationType } from "@langfuse/shared";
-import { env } from "@/src/env.mjs";
-
-// Helper to wait for ClickHouse to process data
-const waitForClickHouse = (ms = 2000) =>
- new Promise((resolve) => setTimeout(resolve, ms));
-
-const maybe =
- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"
- ? describe
- : describe.skip;
-
-describe("Events Service", () => {
- it("should kill redis connection", () => {
- // we need at least one test case to avoid hanging
- // redis connection when everything else is skipped.
- });
- maybe("getEventList", () => {
- it.each([
- {
- column: "startTime",
- eventConfigs: [
- { start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000 },
- { start_time: new Date("2024-01-02T00:00:00.000Z").getTime() * 1000 },
- { start_time: new Date("2024-01-03T00:00:00.000Z").getTime() * 1000 },
- ],
- expectedDescOrder: [2, 1, 0], // indices for DESC order
- expectedAscOrder: [0, 1, 2], // indices for ASC order
- },
- {
- column: "endTime",
- eventConfigs: [
- { end_time: new Date("2024-01-01T01:00:00.000Z").getTime() * 1000 },
- { end_time: new Date("2024-01-02T01:00:00.000Z").getTime() * 1000 },
- { end_time: new Date("2024-01-03T01:00:00.000Z").getTime() * 1000 },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "type",
- eventConfigs: [
- { type: "EVENT" as const },
- { type: "GENERATION" as const },
- { type: "SPAN" as const },
- ],
- expectedDescOrder: [2, 1, 0], // SPAN > GENERATION > EVENT
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "name",
- eventConfigs: [
- { name: "alpha-event" },
- { name: "beta-event" },
- { name: "gamma-event" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "level",
- eventConfigs: [
- { level: "DEFAULT" },
- { level: "ERROR" },
- { level: "WARNING" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "providedModelName",
- eventConfigs: [
- { provided_model_name: "claude-3" },
- { provided_model_name: "gpt-3.5-turbo" },
- { provided_model_name: "gpt-4" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "promptName",
- eventConfigs: [
- { prompt_name: "prompt-a" },
- { prompt_name: "prompt-b" },
- { prompt_name: "prompt-c" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "version",
- eventConfigs: [
- { version: "v1.0" },
- { version: "v2.0" },
- { version: "v3.0" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "traceId",
- eventConfigs: [
- { trace_id: "00000000-0000-0000-0000-000000000001" },
- { trace_id: "00000000-0000-0000-0000-000000000002" },
- { trace_id: "00000000-0000-0000-0000-000000000003" },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "latency",
- eventConfigs: [
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:01.000Z").getTime() * 1000, // 1s
- },
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:03.000Z").getTime() * 1000, // 3s
- },
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:05.000Z").getTime() * 1000, // 5s
- },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "timeToFirstToken",
- eventConfigs: [
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- completion_start_time:
- new Date("2024-01-01T00:00:00.500Z").getTime() * 1000, // 0.5s
- },
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- completion_start_time:
- new Date("2024-01-01T00:00:01.500Z").getTime() * 1000, // 1.5s
- },
- {
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- completion_start_time:
- new Date("2024-01-01T00:00:02.500Z").getTime() * 1000, // 2.5s
- },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "inputTokens",
- eventConfigs: [
- { usage_details: { input: 100 } },
- { usage_details: { input: 200 } },
- { usage_details: { input: 300 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "outputTokens",
- eventConfigs: [
- { usage_details: { output: 50 } },
- { usage_details: { output: 150 } },
- { usage_details: { output: 250 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "totalTokens",
- eventConfigs: [
- { usage_details: { total: 150 } },
- { usage_details: { total: 350 } },
- { usage_details: { total: 550 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "inputCost",
- eventConfigs: [
- { cost_details: { input: 0.001 } },
- { cost_details: { input: 0.002 } },
- { cost_details: { input: 0.003 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "outputCost",
- eventConfigs: [
- { cost_details: { output: 0.005 } },
- { cost_details: { output: 0.01 } },
- { cost_details: { output: 0.015 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "totalCost",
- eventConfigs: [
- { cost_details: { total: 0.006 } },
- { cost_details: { total: 0.012 } },
- { cost_details: { total: 0.018 } },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- {
- column: "tokensPerSecond",
- eventConfigs: [
- {
- usage_details: { output: 100 },
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:10.000Z").getTime() * 1000, // 10 tokens/s
- },
- {
- usage_details: { output: 200 },
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:10.000Z").getTime() * 1000, // 20 tokens/s
- },
- {
- usage_details: { output: 300 },
- start_time: new Date("2024-01-01T00:00:00.000Z").getTime() * 1000,
- end_time: new Date("2024-01-01T00:00:10.000Z").getTime() * 1000, // 30 tokens/s
- },
- ],
- expectedDescOrder: [2, 1, 0],
- expectedAscOrder: [0, 1, 2],
- },
- ])(
- "should sort events by $column",
- async ({ column, eventConfigs, expectedDescOrder, expectedAscOrder }) => {
- const projectId = v4();
- const baseTraceId = v4();
- const baseTimestamp = new Date("2024-01-01T00:00:00.000Z");
-
- // Create events with specific configurations for each test case
- const eventIds = [v4(), v4(), v4()];
- const events = eventConfigs.map((config, index) => {
- const baseConfig = {
- span_id: eventIds[index],
- id: eventIds[index],
- trace_id: ("trace_id" in config
- ? config.trace_id
- : baseTraceId) as string,
- type: ("type" in config
- ? config.type
- : "GENERATION") as ObservationType,
- name: ("name" in config ? config.name : `event-${index}`) as string,
- start_time: ("start_time" in config
- ? config.start_time
- : (baseTimestamp.getTime() + index * 1000) * 1000) as number,
- project_id: projectId,
- level: ("level" in config ? config.level : "DEFAULT") as string,
- };
-
- return createEvent({
- ...baseConfig,
- ...config,
- });
- });
-
- await createEventsCh(events);
- await waitForClickHouse();
-
- // Test sorting DESC
- const resultDesc = await getEventList({
- projectId,
- filter: [],
- searchType: [],
- orderBy: { column, order: "DESC" },
- page: 0,
- limit: 10,
- });
-
- expect(resultDesc.observations).toBeDefined();
- expect(resultDesc.observations.length).toBe(3);
-
- // Verify DESC order by checking event IDs
- expectedDescOrder.forEach((expectedIndex, position) => {
- expect(resultDesc.observations[position].id).toBe(
- eventIds[expectedIndex],
- );
- });
-
- // Test sorting ASC
- const resultAsc = await getEventList({
- projectId,
- filter: [],
- searchType: [],
- orderBy: { column, order: "ASC" },
- page: 0,
- limit: 10,
- });
-
- expect(resultAsc.observations).toBeDefined();
- expect(resultAsc.observations.length).toBe(3);
-
- // Verify ASC order by checking event IDs
- expectedAscOrder.forEach((expectedIndex, position) => {
- expect(resultAsc.observations[position].id).toBe(
- eventIds[expectedIndex],
- );
- });
- },
- );
-
- it("should return paginated list of events", async () => {
- const projectId = v4();
- const traceId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
-
- // Create events
- const events = [];
- for (let i = 0; i < 5; i++) {
- const eventId = v4();
- events.push(
- createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: "GENERATION",
- name: `test-event-${i}`,
- start_time: timestamp.getTime() * 1000, // Convert to microseconds
- project_id: projectId,
- }),
- );
- }
-
- // Insert events into ClickHouse
- await createEventsCh(events);
-
- // Wait for ClickHouse to process
- await waitForClickHouse();
-
- const result = await getEventList({
- projectId,
- filter: [],
- searchType: [],
- orderBy: null,
- page: 0,
- limit: 3,
- });
-
- expect(result.observations).toBeDefined();
- expect(result.observations.length).toBeGreaterThanOrEqual(0);
- if (result.observations.length > 0) {
- expect(result.observations.length).toBeLessThanOrEqual(3);
- }
- });
-
- it.each([
- [
- "GENERATION",
- {
- column: "Type",
- operator: "any of",
- value: ["GENERATION"],
- type: "stringOptions",
- },
- ],
- [
- "test-event",
- {
- column: "Name",
- operator: "any of",
- value: ["test-event"],
- type: "stringOptions",
- },
- ],
- [
- "DEFAULT",
- {
- column: "Level",
- operator: "any of",
- value: ["DEFAULT"],
- type: "stringOptions",
- },
- ],
- ])("should filter events by %s = %s", async (filterValue, filterState) => {
- const traceId = v4();
- const eventId = v4();
- const projectId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
-
- const event = createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: filterValue as ObservationType,
- name: filterValue === "test-event" ? "test-event" : "other-name",
- level: filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",
- start_time: timestamp.getTime() * 1000,
- project_id: projectId,
- });
-
- await createEventsCh([event]);
- await waitForClickHouse();
-
- const result = await getEventList({
- projectId,
- filter: [filterState],
- searchType: [],
- orderBy: null,
- page: 0,
- limit: 10,
- });
-
- expect(result.observations.length).toBeGreaterThanOrEqual(1);
- expect(result.observations.length).toBeLessThanOrEqual(10);
- expect(result.observations[0].name).toBe(
- filterValue === "test-event" ? "test-event" : "other-name",
- );
- expect(result.observations[0].type).toBe(filterValue as ObservationType);
- expect(result.observations[0].level).toBe(
- filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",
- );
- expect(result.observations[0].projectId).toBe(projectId);
- expect(result.observations[0].traceId).toBe(traceId);
- });
-
- it("should handle pagination correctly", async () => {
- const traceId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
- const projectId = v4();
-
- const ids: string[] = [];
-
- // Create multiple events
- const events = [];
- for (let i = 0; i < 10; i++) {
- const eventId = v4();
- ids.push(eventId);
- events.push(
- createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: "GENERATION",
- name: `test-event-${i}`,
- start_time: (timestamp.getTime() + i * 1000) * 1000,
- project_id: projectId,
- }),
- );
- }
-
- await createEventsCh(events);
- await waitForClickHouse();
-
- // Get first page
- const page1 = await getEventList({
- projectId,
- filter: [],
- searchType: [],
- orderBy: null,
- page: 0,
- limit: 5,
- });
-
- // Get second page
- const page2 = await getEventList({
- projectId,
- filter: [],
- searchType: [],
- orderBy: null,
- page: 1,
- limit: 5,
- });
-
- expect(page1.observations).toBeDefined();
- expect(page2.observations).toBeDefined();
-
- expect(page1.observations.map((o) => o.id)).not.toEqual(
- page2.observations.map((o) => o.id),
- );
- expect(page1.observations.map((o) => o.id)).toEqual(ids.slice(0, 5));
- expect(page2.observations.map((o) => o.id)).toEqual(ids.slice(5, 10));
- });
- });
-
- maybe("getEventCount", () => {
- it("should return correct count of events", async () => {
- const traceId = v4();
- const projectId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
-
- // Create multiple events
- const eventCount = 7;
- const events = [];
- for (let i = 0; i < eventCount; i++) {
- const eventId = v4();
- events.push(
- createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: "GENERATION",
- name: `test-event-count-${i}`,
- start_time: (timestamp.getTime() + i * 1000) * 1000,
- project_id: projectId,
- }),
- );
- }
-
- await createEventsCh(events);
- await waitForClickHouse();
-
- const result = await getEventCount({
- projectId,
- filter: [],
- searchType: [],
- orderBy: null,
- });
-
- expect(result.totalCount).toBe(eventCount);
- });
-
- it.each([
- [
- "GENERATION",
- {
- column: "Type",
- operator: "any of",
- value: ["GENERATION"],
- type: "stringOptions",
- },
- ],
- [
- "test-event",
- {
- column: "Name",
- operator: "any of",
- value: ["test-event"],
- type: "stringOptions",
- },
- ],
- [
- "DEFAULT",
- {
- column: "Level",
- operator: "any of",
- value: ["DEFAULT"],
- type: "stringOptions",
- },
- ],
- ])(
- "should count events filtered by %s = %s",
- async (filterValue, filterState) => {
- const traceId = v4();
- const eventId = v4();
- const projectId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
-
- const event = createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: filterValue as ObservationType,
- name: filterValue === "test-event" ? "test-event" : "other-name",
- level: filterValue === "DEFAULT" ? "DEFAULT" : "ERROR",
- start_time: timestamp.getTime() * 1000,
- project_id: projectId,
- });
-
- await createEventsCh([event]);
- await waitForClickHouse();
-
- const result = await getEventCount({
- projectId,
- filter: [filterState],
- searchType: [],
- orderBy: null,
- });
-
- expect(result.totalCount).toBeDefined();
- expect(typeof result.totalCount).toBe("number");
- expect(result.totalCount).toBe(1);
- },
- );
- });
-
- maybe("getEventFilterOptions", () => {
- it("should return correct filter options for various event types", async () => {
- const projectId = v4();
- const traceId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
- const promptId = v4();
- const promptName = `test-prompt-${v4()}`;
- const modelId = v4();
-
- // Create diverse events with different properties
- const events = [
- // Event with model information
- createEvent({
- span_id: v4(),
- id: v4(),
- trace_id: traceId,
- type: "GENERATION",
- name: "event-with-model",
- start_time: timestamp.getTime() * 1000,
- project_id: projectId,
- provided_model_name: "gpt-4",
- model_id: modelId,
- user_id: "user-123",
- session_id: v4(),
- version: "v1.0",
- environment: "production",
- level: "DEFAULT",
- }),
- // Event with prompt information
- createEvent({
- span_id: v4(),
- id: v4(),
- trace_id: traceId,
- type: "GENERATION",
- name: "event-with-prompt",
- start_time: (timestamp.getTime() + 1000) * 1000,
- project_id: projectId,
- prompt_id: promptId,
- prompt_name: promptName,
- level: "WARNING",
- }),
- // SPAN type event
- createEvent({
- span_id: v4(),
- id: v4(),
- trace_id: traceId,
- type: "SPAN",
- name: "span-event",
- start_time: (timestamp.getTime() + 2000) * 1000,
- project_id: projectId,
- environment: "staging",
- }),
- // EVENT type event
- createEvent({
- span_id: v4(),
- id: v4(),
- trace_id: traceId,
- type: "EVENT",
- name: "custom-event",
- start_time: (timestamp.getTime() + 3000) * 1000,
- project_id: projectId,
- level: "ERROR",
- }),
- ];
-
- const eventId = events[0].span_id;
-
- await createEventsCh(events);
-
- // Create scores for filter options
- const numericScore = createTraceScore({
- id: v4(),
- timestamp: timestamp.getTime(),
- project_id: projectId,
- trace_id: traceId,
- name: "accuracy",
- value: 0.95,
- source: "API",
- observation_id: eventId,
- });
-
- const categoricalScore = createTraceScore({
- id: v4(),
- timestamp: timestamp.getTime(),
- project_id: projectId,
- trace_id: traceId,
- name: "sentiment",
- string_value: "positive",
- source: "API",
- observation_id: eventId,
- });
-
- await createScoresCh([numericScore, categoricalScore]);
- await waitForClickHouse();
-
- // Test without time filter
- const result = await getEventFilterOptions({
- projectId,
- });
-
- // Verify all filter option categories exist and are arrays
- expect(result).toBeDefined();
- expect(Array.isArray(result.providedModelName)).toBe(true);
- expect(Array.isArray(result.modelId)).toBe(true);
- expect(Array.isArray(result.name)).toBe(true);
- expect(Array.isArray(result.scores_avg)).toBe(true);
- expect(Array.isArray(result.score_categories)).toBe(true);
- expect(Array.isArray(result.promptName)).toBe(true);
- expect(Array.isArray(result.traceTags)).toBe(true);
- expect(Array.isArray(result.type)).toBe(true);
- expect(Array.isArray(result.userId)).toBe(true);
- expect(Array.isArray(result.version)).toBe(true);
- expect(Array.isArray(result.sessionId)).toBe(true);
- expect(Array.isArray(result.level)).toBe(true);
- expect(Array.isArray(result.environment)).toBe(true);
-
- // Verify populated options have correct values
- const modelNameOption = result.providedModelName.find(
- (opt) => opt.value === "gpt-4",
- );
- expect(modelNameOption).toBeDefined();
- expect(modelNameOption?.count).toBeGreaterThanOrEqual(1);
-
- const modelIdOption = result.modelId.find((opt) => opt.value === modelId);
- expect(modelIdOption).toBeDefined();
- expect(modelIdOption?.count).toBeGreaterThanOrEqual(1);
-
- const nameOptions = result.name.map((opt) => opt.value);
- expect(nameOptions).toContain("event-with-model");
- expect(nameOptions).toContain("event-with-prompt");
- expect(nameOptions).toContain("span-event");
- expect(nameOptions).toContain("custom-event");
-
- const typeOptions = result.type.map((opt) => opt.value);
- expect(typeOptions).toContain("GENERATION");
- expect(typeOptions).toContain("SPAN");
- expect(typeOptions).toContain("EVENT");
-
- const levelOptions = result.level.map((opt) => opt.value);
- expect(levelOptions).toContain("DEFAULT");
- expect(levelOptions).toContain("WARNING");
- expect(levelOptions).toContain("ERROR");
-
- const environmentOptions = result.environment.map((opt) => opt.value);
- expect(environmentOptions).toContain("production");
- expect(environmentOptions).toContain("staging");
-
- const promptNameOption = result.promptName.find(
- (opt) => opt.value === promptName,
- );
- expect(promptNameOption).toBeDefined();
-
- expect(result.scores_avg).toContain("accuracy");
- expect(Array.isArray(result.score_categories)).toBe(true);
-
- // Test with time filter
- const resultWithTimeFilter = await getEventFilterOptions({
- projectId,
- startTimeFilter: [
- {
- column: "Start Time" as const,
- operator: ">" as const,
- value: new Date("2023-01-01T00:00:00.000Z"),
- type: "datetime" as const,
- },
- ],
- });
-
- expect(resultWithTimeFilter).toBeDefined();
- expect(Array.isArray(resultWithTimeFilter.name)).toBe(true);
- expect(Array.isArray(resultWithTimeFilter.type)).toBe(true);
- });
- });
-
- maybe("Integration tests", () => {
- it("should have consistent count between getEventCount and getEventList", async () => {
- const traceId = v4();
- const projectId = v4();
- const timestamp = new Date("2024-01-01T00:00:00.000Z");
-
- // Create specific number of events
- const expectedCount = 5;
- const events = [];
- for (let i = 0; i < expectedCount; i++) {
- const eventId = v4();
- events.push(
- createEvent({
- span_id: eventId,
- id: eventId,
- trace_id: traceId,
- type: "GENERATION",
- name: `test-consistency-${i}`,
- start_time: (timestamp.getTime() + i * 1000) * 1000, // Microseconds
- project_id: projectId,
- }),
- );
- }
-
- await createEventsCh(events);
- await waitForClickHouse();
-
- const filters = [
- {
- column: "Name",
- operator: "contains",
- value: "test-consistency",
- type: "string",
- },
- ];
-
- const countResult = await getEventCount({
- projectId,
- filter: filters,
- searchType: [],
- orderBy: null,
- });
-
- const listResult = await getEventList({
- projectId,
- filter: filters,
- searchType: [],
- orderBy: null,
- page: 0,
- limit: 100,
- });
-
- expect(listResult.observations.length).toBeLessThanOrEqual(
- countResult.totalCount,
- );
- });
-
- it("should handle empty project gracefully", async () => {
- const emptyProjectId = v4();
-
- const [count, list, options] = await Promise.all([
- getEventCount({
- projectId: emptyProjectId,
- filter: [],
- searchType: [],
- orderBy: null,
- }),
- getEventList({
- projectId: emptyProjectId,
- filter: [],
- searchType: [],
- orderBy: null,
- page: 0,
- limit: 10,
- }),
- getEventFilterOptions({
- projectId: emptyProjectId,
- }),
- ]);
-
- expect(count.totalCount).toBe(0);
- expect(list.observations).toHaveLength(0);
- expect(options.name).toHaveLength(0);
- expect(options.type).toHaveLength(0);
- });
- });
-});
diff --git a/web/src/__tests__/async/repositories/event-repository.servertest.ts b/web/src/__tests__/async/repositories/event-repository.servertest.ts
index fa02c340e4..d200da0c8e 100644
--- a/web/src/__tests__/async/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/async/repositories/event-repository.servertest.ts
@@ -8,6 +8,7 @@ import {
getObservationsCountFromEventsTableForPublicApi,
updateEvents,
getTraceByIdFromEventsTable,
+ getObservationsBatchIOFromEventsTable,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import { randomUUID } from "crypto";
@@ -1697,4 +1698,179 @@ describe("Clickhouse Events Repository Test", () => {
expect(result?.public).toBe(true);
});
});
+
+ maybe("getObservationsBatchIOFromEventsTable", () => {
+ it("should fetch I/O and metadata for multiple observations", async () => {
+ const traceId = randomUUID();
+ const observation1Id = randomUUID();
+ const observation2Id = randomUUID();
+ const observation3Id = randomUUID();
+
+ const nowMicro = Date.now() * 1000;
+ const timestamp = new Date(nowMicro / 1000);
+
+ // Create events with different I/O content and metadata
+ const events = [
+ createEvent({
+ id: observation1Id,
+ span_id: observation1Id,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-observation-1",
+ input: "This is input for observation 1",
+ output: "This is output for observation 1",
+ metadata: { key1: "value1", source: "test" },
+ start_time: nowMicro,
+ }),
+ createEvent({
+ id: observation2Id,
+ span_id: observation2Id,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "test-observation-2",
+ input: "This is input for observation 2",
+ output: "This is output for observation 2",
+ metadata: { key2: "value2", environment: "production" },
+ start_time: nowMicro + 1000,
+ }),
+ createEvent({
+ id: observation3Id,
+ span_id: observation3Id,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-observation-3",
+ input: "This is input for observation 3",
+ output: "This is output for observation 3",
+ metadata: { key3: "value3" },
+ start_time: nowMicro + 2000,
+ }),
+ ];
+
+ await createEventsCh(events);
+
+ // Batch fetch I/O and metadata
+ const result = await getObservationsBatchIOFromEventsTable({
+ projectId,
+ observations: [
+ { id: observation1Id, traceId, startTime: timestamp },
+ { id: observation2Id, traceId, startTime: timestamp },
+ { id: observation3Id, traceId, startTime: timestamp },
+ ],
+ });
+
+ expect(result).toBeDefined();
+ expect(result.length).toBe(3);
+
+ // Check observation 1
+ const io1 = result.find((r) => r.id === observation1Id);
+ expect(io1).toBeDefined();
+ expect(io1?.input).toBe("This is input for observation 1");
+ expect(io1?.output).toBe("This is output for observation 1");
+ expect(io1?.metadata).toBeDefined();
+ expect(io1?.metadata?.key1).toBe("value1");
+ expect(io1?.metadata?.source).toBe("test");
+
+ // Check observation 2
+ const io2 = result.find((r) => r.id === observation2Id);
+ expect(io2).toBeDefined();
+ expect(io2?.input).toBe("This is input for observation 2");
+ expect(io2?.output).toBe("This is output for observation 2");
+ expect(io2?.metadata).toBeDefined();
+ expect(io2?.metadata?.key2).toBe("value2");
+ expect(io2?.metadata?.environment).toBe("production");
+
+ // Check observation 3
+ const io3 = result.find((r) => r.id === observation3Id);
+ expect(io3).toBeDefined();
+ expect(io3?.input).toBe("This is input for observation 3");
+ expect(io3?.output).toBe("This is output for observation 3");
+ expect(io3?.metadata).toBeDefined();
+ expect(io3?.metadata?.key3).toBe("value3");
+ });
+
+ it("should handle empty observation array", async () => {
+ const result = await getObservationsBatchIOFromEventsTable({
+ projectId,
+ observations: [],
+ });
+
+ expect(result).toBeDefined();
+ expect(result).toEqual([]);
+ });
+
+ it("should handle partial results when some observations not found", async () => {
+ const traceId = randomUUID();
+ const existingId = randomUUID();
+ const nonExistentId = randomUUID();
+ const nowMicro = Date.now() * 1000;
+ const timestamp = new Date(nowMicro / 1000);
+
+ // Create only one event
+ const event = createEvent({
+ id: existingId,
+ span_id: existingId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-existing",
+ input: "Existing input",
+ output: "Existing output",
+ start_time: nowMicro,
+ });
+
+ await createEventsCh([event]);
+
+ // Request I/O for both existing and non-existent
+ const result = await getObservationsBatchIOFromEventsTable({
+ projectId,
+ observations: [
+ { id: existingId, traceId, startTime: timestamp },
+ { id: nonExistentId, traceId, startTime: timestamp },
+ ],
+ });
+
+ // Should only return the existing one
+ expect(result).toBeDefined();
+ expect(result.length).toBe(1);
+ expect(result[0]?.id).toBe(existingId);
+ expect(result[0]?.input).toBe("Existing input");
+ expect(result[0]?.output).toBe("Existing output");
+ });
+
+ it("should filter by projectId correctly", async () => {
+ const differentProjectId = randomUUID();
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const nowMicro = Date.now() * 1000;
+ const timestamp = new Date(nowMicro / 1000);
+
+ // Create event in different project
+ const event = createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: differentProjectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-different-project",
+ input: "Secret input",
+ output: "Secret output",
+ start_time: nowMicro,
+ });
+
+ await createEventsCh([event]);
+
+ // Try to fetch with wrong projectId
+ const result = await getObservationsBatchIOFromEventsTable({
+ projectId, // Using default projectId, not differentProjectId
+ observations: [{ id: observationId, traceId, startTime: timestamp }],
+ });
+
+ // Should not return anything since projectId doesn't match
+ expect(result).toBeDefined();
+ expect(result.length).toBe(0);
+ });
+ });
});
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index bed5c7f295..54ef2d6a4e 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -239,36 +239,40 @@ export default function ObservationsEventsTable({
const filterState = queryFilter.filterState.concat(dateRangeFilter);
// Use the custom hook for observations data fetching
- const { observations, totalCount, handleAddToAnnotationQueue } =
- useEventsTableData({
- projectId,
- filterState,
- paginationState,
- orderByState,
- searchQuery,
- searchType,
- selectedRows,
- selectAll,
- setSelectedRows,
- });
+ const {
+ observations,
+ totalCount,
+ handleAddToAnnotationQueue,
+ dataUpdatedAt,
+ } = useEventsTableData({
+ projectId,
+ filterState,
+ paginationState,
+ orderByState,
+ searchQuery,
+ searchType,
+ selectedRows,
+ selectAll,
+ setSelectedRows,
+ });
useEffect(() => {
- if (observations.isSuccess) {
+ if (observations.status === "success") {
setDetailPageList(
"observations",
- observations.data.observations.map((o) => ({
- id: o.id,
- params: o.traceTimestamp
+ observations?.rows?.map((o) => ({
+ id: o?.id,
+ params: o?.startTime
? {
- timestamp: o.traceTimestamp.toISOString(),
- traceId: o.traceId || "",
+ timestamp: o?.startTime.toISOString(),
+ traceId: o?.traceId || "",
}
: undefined,
- })),
+ })) ?? [],
);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [observations.isSuccess, observations.data]);
+ }, [observations.status, observations.rows]);
const { scoreColumns, isLoading: isColumnLoading } =
useScoreColumns<EventsTableRow>({
@@ -468,7 +472,7 @@ export default function ObservationsEventsTable({
enableHiding: true,
defaultHidden: true,
cell: () => {
- return observations.isPending ? (
+ return observations.status === "loading" ? (
<Skeleton className="h-3 w-1/2" />
) : null;
},
@@ -538,7 +542,7 @@ export default function ObservationsEventsTable({
enableHiding: true,
defaultHidden: true,
cell: () => {
- return observations.isPending ? (
+ return observations.status === "loading" ? (
<Skeleton className="h-3 w-1/2" />
) : null;
},
@@ -849,68 +853,73 @@ export default function ObservationsEventsTable({
customTitlePrefix: "Observation ID:",
detailNavigationKey: "observations",
children: <PeekViewObservationDetail projectId={projectId} />,
- tableDataUpdatedAt: observations.dataUpdatedAt,
+ tableDataUpdatedAt: dataUpdatedAt,
...peekNavigationProps,
}),
- [projectId, observations.dataUpdatedAt, peekNavigationProps],
+ [projectId, dataUpdatedAt, peekNavigationProps],
);
const rows: EventsTableRow[] = useMemo(() => {
- return observations.isSuccess
- ? observations.data.observations.map((observation) => {
- return {
- id: observation.id,
- traceId: observation.traceId ?? undefined,
- type: observation.type ?? undefined,
- spanId: observation.id, // span_id maps to id
- parentSpanId: observation.parentObservationId ?? undefined,
- startTime: observation.startTime,
- endTime: observation.endTime ?? undefined,
- timeToFirstToken: observation.timeToFirstToken ?? undefined,
- scores: {}, // TODO: scores not included in FullObservation type
- latency: observation.latency ?? undefined,
- totalCost: observation.totalCost ?? undefined,
- cost: {
- inputCost: observation.inputCost ?? undefined,
- outputCost: observation.outputCost ?? undefined,
- },
- name: observation.name ?? undefined,
- version: observation.version ?? "",
- providedModelName: observation.model ?? "",
- modelId: observation.internalModelId ?? undefined,
- level: observation.level,
- statusMessage: observation.statusMessage ?? undefined,
- usage: {
- inputUsage: observation.inputUsage,
- outputUsage: observation.outputUsage,
- totalUsage: observation.totalUsage,
- },
- promptId: observation.promptId ?? undefined,
- promptName: observation.promptName ?? undefined,
- promptVersion: observation.promptVersion?.toString() ?? undefined,
- traceTags: observation.traceTags ?? undefined,
- timestamp: observation.traceTimestamp ?? undefined,
- usageDetails: observation.usageDetails ?? {},
- costDetails: observation.costDetails ?? {},
- usagePricingTierName: observation.usagePricingTierName ?? undefined,
- environment: observation.environment ?? undefined,
- input: observation.input
- ? typeof observation.input === "string"
- ? observation.input
- : JSON.stringify(observation.input)
- : undefined,
- output: observation.output
- ? typeof observation.output === "string"
- ? observation.output
- : JSON.stringify(observation.output)
- : undefined,
- metadata: observation.metadata,
- userId: observation.userId ?? undefined,
- sessionId: observation.sessionId ?? undefined,
- completionStartTime: observation.completionStartTime ?? undefined,
- };
- })
- : [];
+ const result =
+ observations.status === "success" && observations.rows
+ ? observations.rows.map((observation) => {
+ return {
+ id: observation.id,
+ traceId: observation.traceId ?? undefined,
+ type: observation.type ?? undefined,
+ spanId: observation.id, // span_id maps to id
+ parentSpanId: observation.parentObservationId ?? undefined,
+ startTime: observation.startTime,
+ endTime: observation.endTime ?? undefined,
+ timeToFirstToken: observation.timeToFirstToken ?? undefined,
+ scores: {}, // TODO: scores not included in FullObservation type
+ latency: observation.latency ?? undefined,
+ totalCost: observation.totalCost ?? undefined,
+ cost: {
+ inputCost: observation.inputCost ?? undefined,
+ outputCost: observation.outputCost ?? undefined,
+ },
+ name: observation.name ?? undefined,
+ version: observation.version ?? "",
+ providedModelName: observation.model ?? "",
+ modelId: observation.internalModelId ?? undefined,
+ level: observation.level,
+ statusMessage: observation.statusMessage ?? undefined,
+ usage: {
+ inputUsage: observation.inputUsage,
+ outputUsage: observation.outputUsage,
+ totalUsage: observation.totalUsage,
+ },
+ promptId: observation.promptId ?? undefined,
+ promptName: observation.promptName ?? undefined,
+ promptVersion: observation.promptVersion?.toString() ?? undefined,
+ traceTags: undefined, // TODO: traceTags not available in EventsObservation
+ timestamp: observation.startTime ?? undefined,
+ usageDetails: observation.usageDetails ?? {},
+ costDetails: observation.costDetails ?? {},
+ usagePricingTierName:
+ observation.usagePricingTierName ?? undefined,
+ environment: observation.environment ?? undefined,
+ // I/O data comes from joined data already
+ input: observation.input
+ ? typeof observation.input === "string"
+ ? observation.input
+ : JSON.stringify(observation.input)
+ : undefined,
+ output: observation.output
+ ? typeof observation.output === "string"
+ ? observation.output
+ : JSON.stringify(observation.output)
+ : undefined,
+ metadata: observation.metadata,
+ userId: observation.userId ?? undefined,
+ sessionId: observation.sessionId ?? undefined,
+ completionStartTime: observation.completionStartTime ?? undefined,
+ };
+ })
+ : [];
+
+ return result;
}, [observations]);
return (
@@ -956,9 +965,7 @@ export default function ObservationsEventsTable({
key="batchExport"
/>,
Object.keys(selectedRows).filter((observationId) =>
- observations.data?.observations
- .map((o) => o.id)
- .includes(observationId),
+ observations.rows?.map((o) => o.id).includes(observationId),
).length > 0 ? (
<TableActionMenu
key="observations-multi-select-actions"
@@ -971,11 +978,10 @@ export default function ObservationsEventsTable({
multiSelect={{
selectAll,
setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((observationId) =>
- observations.data?.observations
- .map((o) => o.id)
- .includes(observationId),
- ),
+ selectedRowIds:
+ Object.keys(selectedRows).filter((observationId) =>
+ observations.rows?.map((o) => o.id).includes(observationId),
+ ) ?? [],
setRowSelection: setSelectedRows,
totalCount,
pageSize: paginationState.limit,
@@ -989,17 +995,18 @@ export default function ObservationsEventsTable({
<div className="flex flex-1 flex-col overflow-hidden">
<DataTable
+ key={`observations-table-${dataUpdatedAt}-${rows.length > 0 && rows[0]?.input ? "with-io" : "without-io"}`}
tableName={"observations"}
columns={columns}
peekView={peekConfig}
data={
- observations.isPending || isViewLoading
+ observations.status === "loading" || isViewLoading
? { isLoading: true, isError: false }
- : observations.error
+ : observations.status === "error"
? {
isLoading: false,
isError: true,
- error: observations.error.message,
+ error: "",
}
: {
isLoading: false,
diff --git a/web/src/features/events/hooks/useEventsTableData.ts b/web/src/features/events/hooks/useEventsTableData.ts
index 4bf12f475d..bdedd16b10 100644
--- a/web/src/features/events/hooks/useEventsTableData.ts
+++ b/web/src/features/events/hooks/useEventsTableData.ts
@@ -1,7 +1,13 @@
import { api } from "@/src/utils/api";
import { useMemo } from "react";
-import { type FilterState, AnnotationQueueObjectType } from "@langfuse/shared";
+import {
+ type FilterState,
+ AnnotationQueueObjectType,
+ type EventsObservation,
+} from "@langfuse/shared";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
+import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
type UseEventsTableDataParams = {
projectId: string;
@@ -66,6 +72,50 @@ export function useEventsTableData({
refetchOnWindowFocus: true,
});
+ const observationsForIO = useMemo(
+ () =>
+ observations.data?.observations
+ ?.filter((o) => o.id && o.traceId && o.startTime)
+ .map((o) => {
+ if (!o.traceId) {
+ throw new Error("Trace ID is required");
+ }
+ if (!o.startTime) {
+ throw new Error("Start time is required");
+ }
+ return {
+ id: o.id,
+ traceId: o.traceId,
+ startTime: o.startTime,
+ };
+ }) ?? [],
+ [observations.data?.observations],
+ );
+
+ // Fetch I/O data
+ const ioDataQuery = api.events.batchIO.useQuery(
+ {
+ projectId,
+ observations: observationsForIO,
+ },
+ {
+ enabled: observations.isSuccess && observationsForIO.length > 0,
+ refetchOnWindowFocus: false,
+ staleTime: 0,
+ },
+ );
+
+ // Memoize joined data to prevent infinite re-renders
+ // Include ioDataQuery.isSuccess to ensure re-render when I/O loads
+ const joinedData = useMemo(
+ () =>
+ joinTableCoreAndMetrics<EventsObservation, EventBatchIOOutput>(
+ observations.data?.observations,
+ ioDataQuery.data,
+ ),
+ [observations.data?.observations, ioDataQuery.data],
+ );
+
// Fetch total count
const totalCountQuery = api.events.countAll.useQuery(getCountPayload, {
refetchOnWindowFocus: true,
@@ -117,7 +167,8 @@ export function useEventsTableData({
};
return {
- observations,
+ observations: joinedData,
+ dataUpdatedAt: observations.dataUpdatedAt,
totalCountQuery,
totalCount,
addToQueueMutation,
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index fbbd54f4af..164e954018 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -4,12 +4,18 @@ import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { type OrderByState, paginationZod, timeFilter } from "@langfuse/shared";
+import {
+ type Observation,
+ type OrderByState,
+ paginationZod,
+ timeFilter,
+} from "@langfuse/shared";
import { EventsTableOptions } from "./types";
import {
getEventList,
getEventCount,
getEventFilterOptions,
+ getEventBatchIO,
} from "./eventsService";
import { instrumentAsync } from "@langfuse/shared/src/server";
import type * as opentelemetry from "@opentelemetry/api";
@@ -18,6 +24,11 @@ const GetAllEventsInput = EventsTableOptions.extend({
...paginationZod,
});
+export type EventBatchIOOutput = Pick<
+ Observation,
+ "id" | "input" | "output" | "metadata"
+>;
+
export type GetAllEventsInput = z.infer<typeof GetAllEventsInput>;
const GetEventFilterOptionsInput = zodSchema.object({
@@ -29,6 +40,19 @@ export type GetEventFilterOptionsInput = z.infer<
typeof GetEventFilterOptionsInput
>;
+export const BatchIOInput = zodSchema.object({
+ projectId: zodSchema.string(),
+ observations: zodSchema.array(
+ zodSchema.object({
+ id: zodSchema.string(),
+ traceId: zodSchema.string(),
+ startTime: zodSchema.date(),
+ }),
+ ),
+});
+
+export type BatchIOInput = z.infer<typeof BatchIOInput>;
+
export const eventsRouter = createTRPCRouter({
all: protectedProjectProcedure
.input(GetAllEventsInput)
@@ -93,6 +117,22 @@ export const eventsRouter = createTRPCRouter({
},
);
}),
+ batchIO: protectedProjectProcedure
+ .input(BatchIOInput)
+ .query(async ({ input, ctx }) => {
+ return instrumentAsync(
+ { name: "get-event-batch-io-trpc" },
+ async (span) => {
+ span.setAttribute("project_id", input.projectId);
+ span.setAttribute("observation_count", input.observations.length);
+
+ return getEventBatchIO({
+ projectId: ctx.session.projectId,
+ observations: input.observations,
+ });
+ },
+ );
+ }),
});
export const addAttributesToSpan = ({
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index 65dbf8e8e5..54e214267e 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -15,8 +15,10 @@ import {
getEventsGroupedByEnvironment,
getNumericScoresGroupedByName,
getTracesGroupedByTags,
+ getObservationsBatchIOFromEventsTable,
} from "@langfuse/shared/src/server";
import { type timeFilter } from "@langfuse/shared";
+import { type EventBatchIOOutput } from "@/src/features/events/server/eventsRouter";
type TimeFilter = z.infer<typeof timeFilter>;
@@ -54,8 +56,8 @@ export async function getEventList(params: GetObservationsListParams) {
searchType: params.searchType,
orderBy: params.orderBy,
limit: params.limit,
- offset: params.page * params.limit,
- selectIOAndMetadata: true, // Include input/output truncated fields
+ offset: (params.page - 1) * params.limit, // Page is 1-indexed (page 1 = offset 0)
+ selectIOAndMetadata: false, // Exclude I/O for performance - fetched separately via batchIO endpoint
renderingProps: { truncated: true, shouldJsonParse: false },
};
@@ -205,3 +207,24 @@ export async function getEventFilterOptions(
})),
};
}
+
+interface GetEventBatchIOParams {
+ projectId: string;
+ observations: Array<{
+ id: string;
+ traceId: string;
+ startTime: Date;
+ }>;
+}
+
+/**
+ * Batch fetch input/output and metadata for multiple observations
+ */
+export async function getEventBatchIO(
+ params: GetEventBatchIOParams,
+): Promise<Array<EventBatchIOOutput>> {
+ return getObservationsBatchIOFromEventsTable({
+ projectId: params.projectId,
+ observations: params.observations,
+ });
+}