🪢 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: update order by clauses to include project_id (sometimes drastically improves perf) (#11766)
Valery Meleshkin8a32f6d90a85
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex b6745e698e..e38f020e1e 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -1,5 +1,11 @@import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories/constants";+/**+ * Types for structured ORDER BY API+ */+export type OrderByDirection = "ASC" | "DESC";+export type OrderByEntry = { column: string; direction: OrderByDirection };+/*** Field mapping: each field defined once with its full SELECT expression* All queries use `FROM events e` with alias, so all fields use `e.` prefix@@ -416,6 +422,43 @@ abstract class BaseEventsQueryBuilder<this.projectId = options.projectId;}+ /**+ * Set ORDER BY clause with automatic project_id prepending for optimal ClickHouse performance.+ * The events table has ORDER BY (project_id, start_time, ...) so queries should match.+ *+ * @example+ * builder.orderByColumns([+ * { column: "e.start_time", direction: "DESC" },+ * { column: "e.event_ts", direction: "DESC" },+ * ])+ * // Produces: ORDER BY e.project_id DESC, e.start_time DESC, e.event_ts DESC+ */+ orderByColumns(entries: OrderByEntry[]): this {+ if (!entries.length) {+ return this;+ }++ // Use the direction of the first column for project_id+ const primaryDirection = entries[0].direction;++ // Build ORDER BY clause with project_id prepended+ const columns = [+ `e.project_id ${primaryDirection}`,+ ...entries.map((e) => `${e.column} ${e.direction}`),+ ];++ this.orderByClause = `ORDER BY ${columns.join(", ")}`;+ return this;+ }++ /**+ * Apply default ORDER BY for events table queries.+ * Uses start_time DESC (project_id is auto-prepended).+ */+ orderByDefault(): this {+ return this.orderByColumns([{ column: "e.start_time", direction: "DESC" }]);+ }+/*** Build the SELECT clause - implemented by subclasses*/diff --git a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.tsindex 0d898809a1..2a03010627 100644--- a/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/orderby-factory.ts@@ -2,6 +2,7 @@ import z from "zod/v4";import { OrderByState } from "../../../interfaces/orderBy";import { UiColumnMappings } from "../../../tableDefinitions";import { logger } from "../../logger";+import type { OrderByDirection, OrderByEntry } from "./event-query-builder";type OrderByStateNotNull = Exclude<OrderByState, null>;@@ -56,3 +57,54 @@ export function orderByToClickhouseSql(// Join all order by clauses with a comma and returnreturn `ORDER BY ${orderByClauses.join(", ")}`;}++/**+ * Convert OrderByState to structured OrderByEntry array for use with BaseEventsQueryBuilder.+ * Returns empty array if no valid orderBy is provided.+ */+export function orderByToEntries(+ orderBy: OrderByState | OrderByState[] = [],+ tableColumns: UiColumnMappings,+): OrderByEntry[] {+ if (+ !orderBy ||+ (Array.isArray(orderBy) && orderBy.filter(Boolean).length === 0)+ ) {+ return [];+ }++ if (!Array.isArray(orderBy)) {+ orderBy = [orderBy];+ }++ const entries: OrderByEntry[] = [];++ for (const ob of orderBy.filter((o): o is OrderByStateNotNull =>+ Boolean(o),+ )) {+ const col = tableColumns.find(+ (c) => c.uiTableName === ob.column || c.uiTableId === ob.column,+ );++ if (!col) {+ logger.warn(`Invalid order by column: ${ob.column}`);+ throw new Error("Invalid order by column: " + ob.column);+ }++ const orderByOrder = z.enum(["ASC", "DESC"]);+ const order = orderByOrder.safeParse(ob.order);+ if (!order.success) {+ logger.warn(`Invalid order: ${ob.order}. Expected "ASC" or "DESC"`);+ throw new Error("Invalid order: " + ob.order);+ }++ const column = `${col.queryPrefix ? col.queryPrefix + "." : ""}${col.clickhouseSelect}`;++ entries.push({+ column,+ direction: order.data as OrderByDirection,+ });+ }++ return entries;+}diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.tsindex 364b11034b..cbeee24d73 100644--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts@@ -28,7 +28,7 @@ export const eventsTracesAggregation = (.selectFieldSet("all").withTraceIds(params.traceIds).withStartTimeFrom(params.startTimeFrom)- .orderBy("ORDER BY timestamp DESC")+ .orderByColumns([{ column: "timestamp", direction: "DESC" }]));};diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex 674d5376fb..319ba965b6 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -18,7 +18,10 @@ export {NullFilter,type ClickhouseOperator,} from "./clickhouse-sql/clickhouse-filter";-export { orderByToClickhouseSql } from "./clickhouse-sql/orderby-factory";+export {+ orderByToClickhouseSql,+ orderByToEntries,+} from "./clickhouse-sql/orderby-factory";export { createFilterFromFilterState } from "./clickhouse-sql/factory";export { clickhouseSearchCondition } from "./clickhouse-sql/search";export {diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 231bea00a8..25943cf138 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -18,6 +18,7 @@ import {FilterList,FullEventsObservations,orderByToClickhouseSql,+ orderByToEntries,createPublicApiObservationsColumnMapping,createPublicApiTracesColumnMapping,deriveFilters,@@ -357,7 +358,7 @@ async function getObservationsFromEventsTableInternal<T>(// TODO further optimize by checking if specific trace fields are filtered on.const needsTraceJoin = search.query;- const chOrderBy = orderByToClickhouseSql(+ const orderByEntries = orderByToEntries([orderBy ?? null],eventsTableUiColumnDefinitions,);@@ -403,7 +404,7 @@ async function getObservationsFromEventsTableInternal<T>().where(appliedObservationsFilter).where(search)- .orderBy(chOrderBy)+ .when(orderByEntries.length > 0, (b) => b.orderByColumns(orderByEntries)).limit(limit, offset);const { query, params } = queryBuilder.buildWithParams();@@ -527,7 +528,10 @@ async function getObservationByIdFromEventsTableInternal({.when(Boolean(traceId), (b) =>b.whereRaw("trace_id = {traceId: String}", { traceId }),)- .orderBy("ORDER BY start_time DESC, event_ts DESC")+ .orderByColumns([+ { column: "start_time", direction: "DESC" },+ { column: "event_ts", direction: "DESC" },+ ]).limit(1, 0);const { query, params } = queryBuilder.buildWithParams();@@ -762,9 +766,11 @@ function applyOrderByForObservationsQuery(return (queryBuilder// Order by to match table ordering- .orderBy(- "ORDER BY e.start_time DESC, xxHash32(e.trace_id) DESC, e.span_id DESC",- )+ .orderByColumns([+ { column: "e.start_time", direction: "DESC" },+ { column: "xxHash32(e.trace_id)", direction: "DESC" },+ { column: "e.span_id", direction: "DESC" },+ ]));}@@ -1128,7 +1134,7 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(orderByToClickhouseSql(orderBy ? [orderBy] : [],TRACES_ORDER_BY_COLUMNS,- ) || "ORDER BY t.timestamp DESC";+ ) || "ORDER BY t.project_id DESC, t.timestamp DESC";queryBuilder.orderBy(chOrderBy).limit(limit, (page - 1) * limit);}