Skip to content

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

chore(events): consolidate event-stream query construction (#14973)

Valery Meleshkin240e5a1107b0
diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts
new file mode 100644
index 0000000000..3e442536c9
--- /dev/null
+++ b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.test.ts
@@ -0,0 +1,125 @@
+import type { FilterCondition } from "../../../types";
+import { describe, expect, it } from "vitest";
+import { buildEventsStreamQuery } from "./events-stream-query";
+
+const projectId = "project-characterization";
+const cutoffCreatedAt = new Date("2025-01-02T03:04:05.678Z");
+const nativeFilter: FilterCondition = {
+ column: "type",
+ operator: "any of",
+ value: ["GENERATION"],
+ type: "stringOptions",
+};
+
+const normalizeSql = (query: string) => query.replace(/\s+/g, " ").trim();
+
+describe("buildEventsStreamQuery", () => {
+ it("builds the common event-stream selection", () => {
+ const { query: rawQuery, params } = buildEventsStreamQuery({
+ projectId,
+ cutoffCreatedAt,
+ filter: [nativeFilter],
+ searchQuery: "needle",
+ searchType: ["id", "content"],
+ rowLimit: 17,
+ configureQuery: (builder) =>
+ builder.selectRaw("'configured' AS configured"),
+ });
+ const query = normalizeSql(rawQuery);
+
+ expect(query).toContain("'configured' AS configured");
+ expect(query).toContain("FROM events_full e");
+ expect(query).toContain("e.project_id = {projectId: String}");
+ expect(query).toMatch(/e\."type" IN \(\{[^}]+: Array\(String\)\}\)/);
+ expect(query).toMatch(
+ /e\."start_time" < \{dateTimeFilter[^}]+: DateTime64\(3\)\}/,
+ );
+ expect(query).toContain("hasAllTokens(lower(e.input)");
+ expect(query).toContain("hasAllTokens(lower(e.output)");
+ for (const column of [
+ "span_id",
+ "name",
+ "trace_name",
+ "user_id",
+ "session_id",
+ "trace_id",
+ ]) {
+ expect(query).toContain(`e.${column} ILIKE {searchString: String}`);
+ }
+ expect(query).toContain("e.is_deleted = 0");
+
+ const orderIndex = query.indexOf(
+ "ORDER BY e.project_id DESC, toStartOfMinute(e.start_time) DESC, e.start_time DESC",
+ );
+ const deduplicationIndex = query.indexOf(
+ "LIMIT 1 BY e.span_id, e.project_id",
+ );
+ const rowLimitIndex = query.indexOf("LIMIT {limit: Int32}");
+ expect(orderIndex).toBeGreaterThan(-1);
+ expect(orderIndex).toBeLessThan(deduplicationIndex);
+ expect(deduplicationIndex).toBeLessThan(rowLimitIndex);
+
+ expect(params).toMatchObject({
+ projectId,
+ searchString: "%needle%",
+ limit: 17,
+ });
+ expect(Object.values(params)).toContainEqual(["GENERATION"]);
+ expect(Object.values(params)).toContain(cutoffCreatedAt.getTime());
+ });
+
+ it("omits the optional cutoff when it is absent", () => {
+ const { query, params } = buildEventsStreamQuery({
+ projectId,
+ filter: null,
+ rowLimit: 7,
+ configureQuery: (builder) => builder.selectFieldSet("eval"),
+ });
+
+ expect(normalizeSql(query)).not.toMatch(/e\."start_time" < \{/);
+ expect(params).toEqual({ projectId, limit: 7 });
+ });
+
+ it("keeps score filters out of the legacy stream selection", () => {
+ const { query, params, eventOnlyFilters } = buildEventsStreamQuery({
+ projectId,
+ filter: [
+ nativeFilter,
+ {
+ column: "Scores",
+ key: "quality",
+ operator: ">",
+ value: 0.5,
+ type: "numberObject",
+ },
+ ],
+ rowLimit: 7,
+ configureQuery: (builder) => builder.selectFieldSet("eval"),
+ });
+
+ expect(eventOnlyFilters).toEqual([nativeFilter]);
+ expect(normalizeSql(query)).not.toContain("scores_agg");
+ expect(Object.values(params)).not.toContain("quality");
+ });
+
+ it("keeps comment filters out of the legacy stream selection", () => {
+ const { query, params, eventOnlyFilters } = buildEventsStreamQuery({
+ projectId,
+ filter: [
+ nativeFilter,
+ {
+ column: "commentContent",
+ operator: "contains",
+ value: "comment-needle",
+ type: "string",
+ },
+ ],
+ rowLimit: 7,
+ configureQuery: (builder) => builder.selectFieldSet("eval"),
+ });
+
+ expect(eventOnlyFilters).toEqual([nativeFilter]);
+ expect(normalizeSql(query)).not.toContain("commentContent");
+ expect(Object.values(params)).not.toContain("comment-needle");
+ });
+});
diff --git a/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts
new file mode 100644
index 0000000000..9dce36f099
--- /dev/null
+++ b/packages/shared/src/server/queries/clickhouse-sql/events-stream-query.ts
@@ -0,0 +1,112 @@
+import type { FilterCondition } from "../../../types";
+import { eventsTableCols } from "../../../eventsTable";
+import type { TracingSearchType } from "../../../interfaces/search";
+import { eventsTableUiColumnDefinitions } from "../../tableMappings/mapEventsTable";
+import { FilterList } from "./clickhouse-filter";
+import { EventsQueryBuilder } from "./event-query-builder";
+import { createFilterFromFilterState } from "./factory";
+import { clickhouseSearchCondition } from "./search";
+
+const EVENT_SEARCH_COLUMNS = [
+ "span_id",
+ "name",
+ "trace_name",
+ "user_id",
+ "session_id",
+ "trace_id",
+] as const;
+
+export const eventSearchCondition = (opts: {
+ query?: string;
+ searchType?: TracingSearchType[];
+}) =>
+ clickhouseSearchCondition({
+ query: opts.query,
+ searchType: opts.searchType,
+ tablePrefix: "e",
+ searchColumns: EVENT_SEARCH_COLUMNS,
+ useEventsTablePath: true,
+ });
+
+export type EventsStreamQueryInput = {
+ projectId: string;
+ cutoffCreatedAt?: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit: number;
+ configureQuery: (builder: EventsQueryBuilder) => EventsQueryBuilder;
+};
+
+export type EventsStreamQuery = {
+ query: string;
+ params: Record<string, any>;
+ eventOnlyFilters: FilterCondition[];
+};
+
+/**
+ * Builds the common event selection used by streaming consumers.
+ *
+ * Score and comment filters are intentionally excluded here to preserve the
+ * legacy stream behavior. They are applied by the shared row-selection planner
+ * in a later, behavior-changing step.
+ */
+export const buildEventsStreamQuery = ({
+ projectId,
+ cutoffCreatedAt,
+ filter,
+ searchQuery,
+ searchType,
+ rowLimit,
+ configureQuery,
+}: EventsStreamQueryInput): EventsStreamQuery => {
+ const eventOnlyFilters = (filter ?? []).filter((filterItem) => {
+ const columnDefinition = eventsTableUiColumnDefinitions.find(
+ (column) =>
+ column.uiTableName === filterItem.column ||
+ column.uiTableId === filterItem.column,
+ );
+
+ return (
+ columnDefinition?.clickhouseTableName !== "scores" &&
+ columnDefinition?.clickhouseTableName !== "comments"
+ );
+ });
+
+ const filterConditions: FilterCondition[] = [...eventOnlyFilters];
+ if (cutoffCreatedAt) {
+ filterConditions.push({
+ column: "startTime",
+ operator: "<",
+ value: cutoffCreatedAt,
+ type: "datetime",
+ });
+ }
+
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ filterConditions,
+ eventsTableUiColumnDefinitions,
+ eventsTableCols,
+ ),
+ );
+
+ const search = eventSearchCondition({
+ query: searchQuery,
+ searchType,
+ });
+
+ const eventsQuery = configureQuery(new EventsQueryBuilder({ projectId }))
+ .when(search.requiresEventsFull, (builder) => builder.forceFullTable())
+ .where(eventsFilter.apply())
+ .where(search)
+ .whereRaw("e.is_deleted = 0")
+ .orderByDefault()
+ .limitBy("e.span_id", "e.project_id")
+ .limit(rowLimit);
+
+ return {
+ ...eventsQuery.buildWithParams(),
+ eventOnlyFilters,
+ };
+};
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 85a2d69c54..890d1b3366 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -87,3 +87,9 @@ export {
eventsTracesScoresAggregation,
scoreBooleansAggregation,
} from "./clickhouse-sql/query-fragments";
+export {
+ buildEventsStreamQuery,
+ eventSearchCondition,
+ type EventsStreamQuery,
+ type EventsStreamQueryInput,
+} from "./clickhouse-sql/events-stream-query";
diff --git a/packages/shared/src/server/repositories/events-stream.ts b/packages/shared/src/server/repositories/events-stream.ts
new file mode 100644
index 0000000000..31b5d1e95f
--- /dev/null
+++ b/packages/shared/src/server/repositories/events-stream.ts
@@ -0,0 +1,103 @@
+import { Readable } from "stream";
+import type { FilterCondition } from "../../types";
+import type { TracingSearchType } from "../../interfaces/search";
+import { buildEventsStreamQuery } from "../queries";
+import { queryClickhouseStream } from "./clickhouse";
+
+/**
+ * Lightweight event stream for batch observation evaluation.
+ * Selects the eval field set and maps ClickHouse aliases toward ObservationForEval.
+ */
+export const getEventsStreamForEval = async (props: {
+ projectId: string;
+ cutoffCreatedAt?: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit: number;
+}): Promise<Readable> => {
+ const {
+ projectId,
+ cutoffCreatedAt,
+ filter = [],
+ searchQuery,
+ searchType,
+ rowLimit,
+ } = props;
+
+ const { query, params: queryParams } = buildEventsStreamQuery({
+ projectId,
+ cutoffCreatedAt,
+ filter,
+ searchQuery,
+ searchType,
+ rowLimit,
+ configureQuery: (builder) =>
+ builder.selectFieldSet("eval").selectIO(false).selectFieldSet("metadata"),
+ });
+
+ type EvalEventRow = {
+ id: string;
+ trace_id: string;
+ project_id: string;
+ parent_observation_id: string | null;
+ type: string;
+ name: string | null;
+ environment: string | null;
+ version: string | null;
+ level: string;
+ status_message: string | null;
+ trace_name: string | null;
+ user_id: string | null;
+ session_id: string | null;
+ tags: string[];
+ release: string | null;
+ provided_model_name: string | null;
+ model_parameters: unknown;
+ prompt_id: string | null;
+ prompt_name: string | null;
+ prompt_version: number | null;
+ provided_usage_details: Record<string, number>;
+ usage_details: Record<string, number>;
+ provided_cost_details: Record<string, number>;
+ cost_details: Record<string, number>;
+ tool_definitions: Record<string, unknown>;
+ tool_calls: unknown[];
+ tool_call_names: string[];
+ input: unknown;
+ output: unknown;
+ metadata: Record<string, unknown> | null;
+ experiment_id: string | null;
+ experiment_item_root_span_id: string | null;
+ experiment_item_expected_output: string | null;
+ experiment_item_metadata: Record<string, unknown> | null;
+ };
+
+ const asyncGenerator = queryClickhouseStream<EvalEventRow>({
+ query,
+ params: queryParams,
+ clickhouseConfigs: {
+ request_timeout: 180_000,
+ clickhouse_settings: {
+ http_send_timeout: 300,
+ http_receive_timeout: 300,
+ },
+ },
+ tags: { projectId },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+
+ // Remap ClickHouse aliases to schema field names.
+ // Schema validation is left to the consumer so per-row errors can be handled gracefully.
+ return Readable.from(
+ (async function* () {
+ for await (const row of asyncGenerator) {
+ yield {
+ ...row,
+ span_id: row.id,
+ parent_span_id: row.parent_observation_id,
+ };
+ }
+ })(),
+ );
+};
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index ab8b793e9e..78f5f03f58 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -1,5 +1,4 @@
import { prisma } from "../../db";
-import { Readable } from "stream";
import type { ClickHouseClientConfigOptions } from "@clickhouse/client";
import type {
EventsObservation,
@@ -35,6 +34,7 @@ import {
type Filter,
FilterList,
FullEventsObservations,
+ eventSearchCondition,
orderByToClickhouseSql,
orderByToEntries,
createPublicApiObservationsColumnMapping,
@@ -48,11 +48,7 @@ import {
ObservationPriceFields,
} from "../queries";
import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";
-import type {
- EventsTableFilterState,
- FilterCondition,
- FilterState,
-} from "../../types";
+import type { EventsTableFilterState, FilterState } from "../../types";
import type { TracingSearchType } from "../../interfaces/search";
import {
eventsScoresAggregation,
@@ -61,7 +57,6 @@ import {
eventsTracesAggregation,
eventsTracesScoresAggregation,
} from "../queries/clickhouse-sql/query-fragments";
-import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
import {
eventsTableNativeUiColumnDefinitions,
eventsTableUiColumnDefinitions,
@@ -174,27 +169,6 @@ type ObservationsTableQueryResultWitouhtTraceFields = Omit<
"trace_tags" | "trace_name" | "trace_user_id"
>;
-const EVENT_SEARCH_COLUMNS = [
- "span_id",
- "name",
- "trace_name",
- "user_id",
- "session_id",
- "trace_id",
-] as const;
-
-const eventSearchCondition = (opts: {
- query?: string;
- searchType?: TracingSearchType[];
-}) =>
- clickhouseSearchCondition({
- query: opts.query,
- searchType: opts.searchType,
- tablePrefix: "e",
- searchColumns: EVENT_SEARCH_COLUMNS,
- useEventsTablePath: true,
- });
-
/**
* Internal helper: enrich observations with model pricing data
* Uses events-specific converter to include userId and sessionId
@@ -870,143 +844,6 @@ export const getObservationByIdFromEventsTable = async ({
return mapped.shift();
};
-/**
- * Lightweight event stream for batch observation evaluation.
- * Selects the eval field set and maps ClickHouse aliases toward ObservationForEval.
- */
-export const getEventsStreamForEval = async (props: {
- projectId: string;
- cutoffCreatedAt?: Date;
- filter: FilterCondition[] | null;
- searchQuery?: string;
- searchType?: TracingSearchType[];
- rowLimit: number;
-}): Promise<Readable> => {
- const {
- projectId,
- cutoffCreatedAt,
- filter = [],
- searchQuery,
- searchType,
- rowLimit,
- } = 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 filterConditions: FilterCondition[] = [...eventOnlyFilters];
- if (cutoffCreatedAt) {
- filterConditions.push({
- column: "startTime",
- operator: "<",
- value: cutoffCreatedAt,
- type: "datetime",
- });
- }
-
- const eventsFilter = new FilterList(
- createFilterFromFilterState(
- filterConditions,
- eventsTableUiColumnDefinitions,
- eventsTableCols,
- ),
- );
-
- const appliedEventsFilter = eventsFilter.apply();
-
- const search = eventSearchCondition({
- query: searchQuery,
- searchType,
- });
-
- const eventsQuery = new EventsQueryBuilder({ projectId })
- .selectFieldSet("eval")
- .selectIO(false)
- .selectFieldSet("metadata")
- .when(search.requiresEventsFull, (b) => b.forceFullTable())
- .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 EvalEventRow = {
- id: string;
- trace_id: string;
- project_id: string;
- parent_observation_id: string | null;
- type: string;
- name: string | null;
- environment: string | null;
- version: string | null;
- level: string;
- status_message: string | null;
- trace_name: string | null;
- user_id: string | null;
- session_id: string | null;
- tags: string[];
- release: string | null;
- provided_model_name: string | null;
- model_parameters: unknown;
- prompt_id: string | null;
- prompt_name: string | null;
- prompt_version: number | null;
- provided_usage_details: Record<string, number>;
- usage_details: Record<string, number>;
- provided_cost_details: Record<string, number>;
- cost_details: Record<string, number>;
- tool_definitions: Record<string, unknown>;
- tool_calls: unknown[];
- tool_call_names: string[];
- input: unknown;
- output: unknown;
- metadata: Record<string, unknown> | null;
- experiment_id: string | null;
- experiment_item_root_span_id: string | null;
- experiment_item_expected_output: string | null;
- experiment_item_metadata: Record<string, unknown> | null;
- };
-
- const asyncGenerator = queryClickhouseStream<EvalEventRow>({
- query,
- params: queryParams,
- clickhouseConfigs: {
- request_timeout: 180_000,
- clickhouse_settings: {
- http_send_timeout: 300,
- http_receive_timeout: 300,
- },
- },
- tags: { projectId },
- preferredClickhouseService: "EventsReadOnly",
- });
-
- // Remap ClickHouse aliases to schema field names.
- // Schema validation is left to the consumer so per-row errors can be handled gracefully.
- return Readable.from(
- (async function* () {
- for await (const row of asyncGenerator) {
- yield {
- ...row,
- span_id: row.id,
- parent_span_id: row.parent_observation_id,
- };
- }
- })(),
- );
-};
-
async function getObservationByIdFromEventsTableInternal({
id,
projectId,
diff --git a/packages/shared/src/server/repositories/index.ts b/packages/shared/src/server/repositories/index.ts
index 2e527f176b..c4e2d6924e 100644
--- a/packages/shared/src/server/repositories/index.ts
+++ b/packages/shared/src/server/repositories/index.ts
@@ -2,6 +2,7 @@ export * from "./scores";
export * from "./traces";
export * from "./observations";
export * from "./events";
+export * from "./events-stream";
export * from "./types";
export * from "./dashboards";
export * from "./traces_converters";
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
index 0e9ddfdf69..873ee9183e 100644
--- a/worker/src/features/database-read-stream/event-stream.ts
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -12,17 +12,12 @@ import {
type ScoreDataTypeType,
TimeFilter,
TracingSearchType,
- eventsTableCols,
} from "@langfuse/shared";
import {
+ buildEventsStreamQuery,
getDistinctScoreNames,
queryClickhouseStream,
logger,
- FilterList,
- createFilterFromFilterState,
- eventsTableUiColumnDefinitions,
- clickhouseSearchCondition,
- EventsQueryBuilder,
eventsScoresAggregation,
} from "@langfuse/shared/src/server";
import { Readable } from "stream";
@@ -35,27 +30,6 @@ import { fetchCommentsForExport } from "./fetchCommentsForExport";
import { BatchExportEventsRow } from "./types";
const BATCH_SIZE = 1000; // Fetch comments in batches for efficiency
-const EVENT_SEARCH_COLUMNS = [
- "span_id",
- "name",
- "trace_name",
- "user_id",
- "session_id",
- "trace_id",
-] as const;
-
-export const eventSearchCondition = (opts: {
- query?: string;
- searchType?: TracingSearchType[];
-}) =>
- clickhouseSearchCondition({
- query: opts.query,
- searchType: opts.searchType,
- tablePrefix: "e",
- searchColumns: EVENT_SEARCH_COLUMNS,
- useEventsTablePath: true,
- });
-
/**
* Creates a stream of events from ClickHouse for batch export.
* Includes comments fetched in batches and flattened scores.
@@ -91,16 +65,38 @@ export const getEventsStream = async (props: {
},
};
- // Filter out score and comment filters since they require special handling
- const eventOnlyFilters = (filter ?? []).filter((f) => {
- const columnDef = eventsTableUiColumnDefinitions.find(
- (col) => col.uiTableName === f.column || col.uiTableId === f.column,
- );
- // Keep the filter if it's not a scores or comments filter
- return (
- columnDef?.clickhouseTableName !== "scores" &&
- columnDef?.clickhouseTableName !== "comments"
- );
+ const {
+ query,
+ params: queryParams,
+ eventOnlyFilters,
+ } = buildEventsStreamQuery({
+ projectId,
+ cutoffCreatedAt,
+ filter,
+ searchQuery,
+ searchType,
+ rowLimit,
+ configureQuery: (builder) =>
+ builder
+ .selectFieldSet("export")
+ .selectIO(false) // Full I/O, no truncation
+ .selectMetadataExpanded() // Full metadata values from events_full
+ .selectRaw(
+ "s.scores_avg as scores_avg",
+ "s.score_categories as score_categories",
+ "s.score_categories_tuples as score_categories_tuples",
+ )
+ .withCTE(
+ "scores_agg",
+ eventsScoresAggregation({
+ projectId,
+ includeTupleEncoding: true,
+ }),
+ )
+ .leftJoin(
+ "scores_agg s",
+ "ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",
+ ),
});
// Get distinct score names for empty columns
@@ -120,58 +116,6 @@ export const getEventsStream = async (props: {
{} as Record<string, null>,
);
- // Build filters for events (project_id is handled by the query builder)
- 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 = eventSearchCondition({
- query: searchQuery,
- searchType,
- });
-
- // Build the query using EventsQueryBuilder
- const eventsQuery = new EventsQueryBuilder({ projectId })
- .selectFieldSet("export")
- .selectIO(false) // Full I/O, no truncation
- .selectMetadataExpanded() // Full metadata values from events_full
- .selectRaw(
- "s.scores_avg as scores_avg",
- "s.score_categories as score_categories",
- "s.score_categories_tuples as score_categories_tuples",
- )
- .withCTE(
- "scores_agg",
- eventsScoresAggregation({ projectId, includeTupleEncoding: true }),
- )
- .leftJoin(
- "scores_agg s",
- "ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",
- )
- .when(search.requiresEventsFull, (b) => b.forceFullTable())
- .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 EventRow = {
id: string;
trace_id: string;
@@ -377,54 +321,17 @@ export const getEventsStreamForDataset = async (props: {
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 = eventSearchCondition({
- query: searchQuery,
+ const { query, params: queryParams } = buildEventsStreamQuery({
+ projectId,
+ cutoffCreatedAt,
+ filter,
+ searchQuery,
searchType,
+ rowLimit,
+ configureQuery: (builder) =>
+ builder.selectFieldSet("core").selectIO(false).selectFieldSet("metadata"),
});
- const eventsQuery = new EventsQueryBuilder({ projectId })
- .selectFieldSet("core")
- .selectIO(false)
- .selectFieldSet("metadata")
- .when(search.requiresEventsFull, (b) => b.forceFullTable())
- .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 DatasetEventRow = {
id: string;
trace_id: string;
@@ -484,52 +391,16 @@ export const getEventsStreamForAnnotationQueue = async (props: {
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 = eventSearchCondition({
- query: searchQuery,
+ const { query, params: queryParams } = buildEventsStreamQuery({
+ projectId,
+ cutoffCreatedAt,
+ filter,
+ searchQuery,
searchType,
+ rowLimit,
+ configureQuery: (builder) => builder.selectFieldSet("core"),
});
- const eventsQuery = new EventsQueryBuilder({ projectId })
- .selectFieldSet("core")
- .when(search.requiresEventsFull, (b) => b.forceFullTable())
- .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;
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index 6224c3fc6c..d10b735ce2 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -24,6 +24,7 @@ import {
convertEventsObservation,
shouldSkipObservationsFinal,
EventsQueryBuilder,
+ eventSearchCondition,
eventsScoresAggregation,
scoreBooleansAggregation,
} from "@langfuse/shared/src/server";
@@ -34,7 +35,6 @@ import {
prepareScoresForOutput,
} from "./getDatabaseReadStream";
import { fetchCommentsForExport } from "./fetchCommentsForExport";
-import { eventSearchCondition } from "./event-stream";
const DEFAULT_BATCH_SIZE = 1000;
const REDUCED_BATCH_SIZE = 200; // Smaller batch for JSON/JSONL which hold parsed objects in memory