🪢 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
chore: remove obsolete measureAndReturn wrapper (#15396)
Steffen Schmitz28a5c268a7d9
diff --git a/packages/shared/src/features/query/server/queryExecutor.ts b/packages/shared/src/features/query/server/queryExecutor.tsindex 1fc538f3e2..7142b78755 100644--- a/packages/shared/src/features/query/server/queryExecutor.ts+++ b/packages/shared/src/features/query/server/queryExecutor.ts@@ -2,7 +2,6 @@ import {queryClickhouse,type ClickhouseQueryOpts,} from "../../../server/repositories/clickhouse";-import { measureAndReturn } from "../../../server/clickhouse/measureAndReturn";import { type PreferredClickhouseService } from "../../../server/clickhouse/client";import { QueryBuilder } from "./queryBuilder";import { type QueryType, type ViewVersion } from "../types";@@ -107,22 +106,10 @@ export async function executeQuery(return queryClickhouse<Record<string, unknown>>(chOpts);}- return measureAndReturn({- operationName: "executeQuery",- projectId,- input: {- query: prepared.compiledQuery,- params: prepared.parameters,- fromTimestamp: prepared.fromTimestamp,- tags: prepared.tags,- },- fn: async (input) => {- return queryClickhouse<Record<string, unknown>>({- ...chOpts,- query: input.query,- params: input.params,- tags: input.tags,- });- },+ return queryClickhouse<Record<string, unknown>>({+ ...chOpts,+ query: prepared.compiledQuery,+ params: prepared.parameters,+ tags: prepared.tags,});}diff --git a/packages/shared/src/server/clickhouse/measureAndReturn.ts b/packages/shared/src/server/clickhouse/measureAndReturn.tsdeleted file mode 100644index 99274c145a..0000000000--- a/packages/shared/src/server/clickhouse/measureAndReturn.ts+++ /dev/null@@ -1,49 +0,0 @@-import * as opentelemetry from "@opentelemetry/api";-import { instrumentAsync } from "../instrumentation";--const executionWrapper = async <T, Y>(- input: T,- fn: (input: T) => Promise<Y>,- span?: opentelemetry.Span,- attributePrefix?: string,-): Promise<[Y, number]> => {- const startTime = Date.now();- const res = await fn(input);- const duration = Date.now() - startTime;- span?.setAttribute(- `langfuse.experiment.amts.${attributePrefix}-duration`,- duration,- );- return [res, duration];-};--/**- * Measures the execution time of a query functions and returns the result based on the experiment configuration.- * Presently this is but a simple wrapper around single execution, but it is designed to be- * extended for A/B testing or canary releases.- */-export const measureAndReturn = async <T, Y>(args: {- operationName: string;- projectId: string;- input: T;- fn: (input: T) => Promise<Y>;-}): Promise<Y> => {- return instrumentAsync(- {- name: `experiment-${args.operationName}`,- spanKind: opentelemetry.SpanKind.CLIENT,- },- async (currentSpan) => {- const { input, fn } = args;-- // When we want do to multiple executions for A/B testing or canary releases,- // or some other form of a more complex wrapper we used to try-catch- // using the wrapper function and fallback to a simple f(input) when it failed.- const [[existingResult, _existingDuration]] = await Promise.all([- executionWrapper(input, fn, currentSpan, "existing"),- ]);-- return existingResult;- },- );-};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 11fcdb0f93..1d69c59392 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -150,7 +150,6 @@ export * from "./services/DefaultViewService";export * from "./services/DefaultEvaluationModelService";export * from "./services/blockEvaluatorConfigs";export * from "./services/getProjectAdminEmails";-export * from "./clickhouse/measureAndReturn";export * from "./services/SlackService";export * from "./services/buildColoredAttachmentSlackMessage";export * from "./tableMappings";diff --git a/packages/shared/src/server/repositories/daily-metrics.ts b/packages/shared/src/server/repositories/daily-metrics.tsindex 53f757cdd5..c1c82f940f 100644--- a/packages/shared/src/server/repositories/daily-metrics.ts+++ b/packages/shared/src/server/repositories/daily-metrics.ts@@ -2,7 +2,6 @@ import { type DateTimeFilter, FilterList } from "../queries";import { queryClickhouse } from "./clickhouse";import { TRACE_TO_OBSERVATIONS_INTERVAL } from "./constants";import { convertDateToClickhouseDateTime } from "../clickhouse/client";-import { measureAndReturn } from "../clickhouse/measureAndReturn";export const generateDailyMetrics = async ({projectId,@@ -82,68 +81,56 @@ export const generateDailyMetrics = async ({${pagination !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;- const timestamp = timeFilter?.value;-- return measureAndReturn({- operationName: "generateDailyMetrics",- projectId,- input: {- params: {- ...appliedTracesFilter.params,- ...appliedFilter.params,- projectId,- ...(pagination !== undefined- ? {- limit: pagination.limit,- offset: (pagination.page - 1) * pagination.limit,- }- : {}),- ...(timeFilter- ? {- cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),- }- : {}),- },- tags: { projectId },- timestamp,+ const input = {+ params: {+ ...appliedTracesFilter.params,+ ...appliedFilter.params,+ projectId,+ ...(pagination !== undefined+ ? {+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,+ }+ : {}),+ ...(timeFilter+ ? {+ cteTimeFilter: convertDateToClickhouseDateTime(timeFilter.value),+ }+ : {}),},- fn: async (input: {- params: Record<string, unknown>;- tags: Record<string, string>;- timestamp?: Date;- }) => {- const result = await queryClickhouse<{- date: string;- countTraces: number;- countObservations: number;- totalCost: number;- usage: (string | null)[][];- }>({- query: query.replaceAll("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- clickhouseConfigs: {- request_timeout: 60_000,- },- });+ tags: { projectId },+ };- return result.map((record) => ({- date: record.date,- countTraces: Number(record.countTraces),- countObservations: Number(record.countObservations),- totalCost: Number(record.totalCost),- usage: record.usage.map((u) => ({- model: u[0],- inputUsage: Number(u[1]),- outputUsage: Number(u[2]),- totalUsage: Number(u[3]),- totalCost: Number(u[4]),- countObservations: Number(u[5]),- countTraces: Number(u[6]),- })),- }));+ const result = await queryClickhouse<{+ date: string;+ countTraces: number;+ countObservations: number;+ totalCost: number;+ usage: (string | null)[][];+ }>({+ query: query.replaceAll("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ clickhouseConfigs: {+ request_timeout: 60_000,},});++ return result.map((record) => ({+ date: record.date,+ countTraces: Number(record.countTraces),+ countObservations: Number(record.countObservations),+ totalCost: Number(record.totalCost),+ usage: record.usage.map((u) => ({+ model: u[0],+ inputUsage: Number(u[1]),+ outputUsage: Number(u[2]),+ totalUsage: Number(u[3]),+ totalCost: Number(u[4]),+ countObservations: Number(u[5]),+ countTraces: Number(u[6]),+ })),+ }));};export const getDailyMetricsCount = async ({@@ -156,14 +143,6 @@ export const getDailyMetricsCount = async ({const tracesFilter = filter.filter((f) => f.clickhouseTable === "traces");const appliedFilter = tracesFilter.apply();- const timeFilter = filter.find(- (f) =>- f.clickhouseTable === "traces" &&- f.field.includes("timestamp") &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined;- const timestamp = timeFilter?.value;-const query = `SELECT count(distinct toDate(timestamp)) as countFROM __TRACE_TABLE__ t@@ -171,25 +150,15 @@ export const getDailyMetricsCount = async ({${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}`;- return measureAndReturn({- operationName: "getDailyMetricsCount",- projectId,- input: {- params: { ...appliedFilter.params, projectId },- tags: { projectId },- timestamp,- },- fn: async (input: {- params: Record<string, unknown>;- tags: Record<string, string>;- timestamp?: Date;- }) => {- const records = await queryClickhouse<{ count: string }>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- });- return records.map((record) => Number(record.count)).shift();- },+ const input = {+ params: { ...appliedFilter.params, projectId },+ tags: { projectId },+ };++ const records = await queryClickhouse<{ count: string }>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,});+ return records.map((record) => Number(record.count)).shift();};diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex bc141ff810..7f34872bb1 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -15,7 +15,6 @@ import {convertDateToClickhouseDateTime,PreferredClickhouseService,} from "../clickhouse/client";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import { recordDistribution } from "../instrumentation";import { logger } from "../logger";import {@@ -886,23 +885,12 @@ async function getObservationsFromEventsTableInternal<T>(const { query, params } = queryBuilder.buildWithParams();- return measureAndReturn({- operationName: "getObservationsFromEventsTableInternal",- projectId,- input: {- params,- tags: { projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs,- preferredClickhouseService:- preferredClickhouseService ?? "EventsReadOnly",- });- },+ return queryClickhouse<T>({+ query,+ params,+ tags: { projectId },+ clickhouseConfigs,+ preferredClickhouseService: preferredClickhouseService ?? "EventsReadOnly",});}@@ -1117,22 +1105,11 @@ export const getTraceByIdFromEventsTable = async ({const { query, params } = queryBuilder.buildWithParams();- const records = await measureAndReturn({- operationName: "getTraceByIdFromEventsTable",- projectId,- input: {- params,- tags: { projectId },- },- fn: async (input) => {- return queryClickhouse<TraceRecordReadType>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService:- preferredClickhouseService ?? "EventsReadOnly",- });- },+ const records = await queryClickhouse<TraceRecordReadType>({+ query,+ params,+ tags: { projectId },+ preferredClickhouseService: preferredClickhouseService ?? "EventsReadOnly",});const res = records.map((record) =>@@ -1224,20 +1201,13 @@ export const hasAnyTraceFromEventsTable = async (LIMIT 1`;- const rows = await measureAndReturn({- operationName: "hasAnyTraceFromEventsTable",- projectId,- input: { params: { projectId } },- fn: async (input) => {- return queryClickhouse<{ 1: number }>({- query,- params: input.params,- tags: { projectId },- preferredClickhouseService: "EventsReadOnly",- clickhouseSettings: {- max_threads: 1,- },- });+ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: { projectId },+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",+ clickhouseSettings: {+ max_threads: 1,},});@@ -1555,26 +1525,15 @@ function applyCursorPagination(async function getObservationsRowsFromBuilder<T>(projectId: string,queryBuilder: QueryWithParams,- operationName = "getObservationsFromEventsTableForPublicApi_rows",extraTags: Record<string, string> = {},): Promise<Array<T>> {const { query, params } = queryBuilder.buildWithParams();- return await measureAndReturn({- operationName,- projectId,- input: {- params,- tags: { projectId, ...extraTags },- },- fn: async (input) => {- return await queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ return await queryClickhouse<T>({+ query,+ params,+ tags: { projectId, ...extraTags },+ preferredClickhouseService: "EventsReadOnly",});}@@ -1594,21 +1553,11 @@ async function getObservationsCountFromEventsTableForPublicApiInternal(const { query, params } = queryBuilder.buildWithParams();- const result = await measureAndReturn({- operationName: "getObservationsFromEventsTableForPublicApi_count",- projectId,- input: {- params,- tags: { projectId },- },- fn: async (input) => {- return await queryClickhouse<{ count: string }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ const result = await queryClickhouse<{ count: string }>({+ query,+ params,+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",});return result;@@ -1928,21 +1877,11 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(const { query, params } = queryBuilder.buildWithParams();- const result = await measureAndReturn({- operationName: `getTracesFromEventsTableForPublicApi_${opts.select}`,- projectId,- input: {- params,- tags: { projectId },- },- fn: async (input) => {- return await queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ const result = await queryClickhouse<T>({+ query,+ params,+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",});return result;@@ -2431,21 +2370,11 @@ export async function getAgentGraphDataFromEventsTable(params: {AND e.start_time <= {chMaxStartTime: DateTime64(3)}`;- return measureAndReturn({- operationName: "getAgentGraphDataFromEventsTable",- projectId,- input: {- params: { projectId, traceId, chMinStartTime, chMaxStartTime },- tags: { projectId },- },- fn: async (input) => {- return queryClickhouse({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ return queryClickhouse({+ query,+ params: { projectId, traceId, chMinStartTime, chMaxStartTime },+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",});}@@ -3333,18 +3262,11 @@ export const hasAnySessionFromEventsTable = async (LIMIT 1`;- const rows = await measureAndReturn({- operationName: "hasAnySessionFromEventsTable",- projectId,- input: { params: { projectId } },- fn: async (input) => {- return queryClickhouse<{ 1: number }>({- query,- params: input.params,- tags: { projectId },- preferredClickhouseService: "EventsReadOnly",- });- },+ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: { projectId },+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",});return rows.length > 0;@@ -3368,26 +3290,17 @@ export const getTraceMetadataByIdsFromEvents = async (props: {const { query, params } = builder.buildWithParams();- return measureAndReturn({- operationName: "getTraceMetadataByIdsFromEvents",- projectId: props.projectId,- input: {- params,- tags: { projectId: props.projectId },- },- fn: async (input) =>- queryClickhouse<{- id: string;- name: string;- user_id: string;- tags: string[];- }>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs: props.clickhouseConfigs,- preferredClickhouseService: "EventsReadOnly",- }),+ return queryClickhouse<{+ id: string;+ name: string;+ user_id: string;+ tags: string[];+ }>({+ query,+ params,+ tags: { projectId: props.projectId },+ clickhouseConfigs: props.clickhouseConfigs,+ preferredClickhouseService: "EventsReadOnly",});};@@ -3454,20 +3367,11 @@ export const getSessionMetricsFromEvents = async (props: {const { query, params } = builder.buildWithParams();- const rows = await measureAndReturn({- operationName: "getSessionMetricsFromEvents",- projectId: props.projectId,- input: {- params,- tags: { projectId: props.projectId },- },- fn: async (input) =>- queryClickhouse<SessionEventsMetricsRow>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- }),+ const rows = await queryClickhouse<SessionEventsMetricsRow>({+ query,+ params,+ tags: { projectId: props.projectId },+ preferredClickhouseService: "EventsReadOnly",});return rows.map((row) => ({@@ -3618,27 +3522,17 @@ export const getTracesIdentifierForSessionFromEvents = async (const { query, params } = queryBuilder.buildWithParams();- const rows = await measureAndReturn({- operationName: "getTracesIdentifierForSessionFromEvents",- projectId,- input: {- params,- tags: { projectId },- },- fn: async (input) => {- return await queryClickhouse<{- id: string;- user_id: string;- name: string;- timestamp: string;- environment: string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ const rows = await queryClickhouse<{+ id: string;+ user_id: string;+ name: string;+ timestamp: string;+ environment: string;+ }>({+ query,+ params,+ tags: { projectId },+ preferredClickhouseService: "EventsReadOnly",});return rows.map((row) => ({diff --git a/packages/shared/src/server/repositories/experiments.ts b/packages/shared/src/server/repositories/experiments.tsindex d9879fd280..3a9409cb99 100644--- a/packages/shared/src/server/repositories/experiments.ts+++ b/packages/shared/src/server/repositories/experiments.ts@@ -3,7 +3,6 @@ import { type ScoreSourceType } from "../../domain";import { type OrderByState } from "../../interfaces/orderBy";import { type FilterState } from "../../types";import { convertDateToClickhouseDateTime } from "../clickhouse/client";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import {FilterList,StringOptionsFilter,@@ -189,21 +188,11 @@ export const getExperimentMetricsFromEvents = async (props: {const { query, params } = queryBuilder.buildWithParams();- const res = await measureAndReturn({- operationName: "getExperimentMetricsFromEvents",- projectId: props.projectId,- input: {- params,- tags: { projectId: props.projectId },- },- fn: async (input) => {- return queryClickhouse<ExperimentMetricsReturnType>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ const res = await queryClickhouse<ExperimentMetricsReturnType>({+ query,+ params,+ tags: { projectId: props.projectId },+ preferredClickhouseService: "EventsReadOnly",});return res.map((row) => ({@@ -361,21 +350,11 @@ const getExperimentsFromEventsGeneric = async <T>(const finalParams = built.params;- return measureAndReturn({- operationName: "getExperimentsFromEventsGeneric",- projectId,- input: {- params: finalParams,- tags: { ...(props.tags ?? {}), projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query: finalQuery,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });- },+ return queryClickhouse<T>({+ query: finalQuery,+ params: finalParams,+ tags: { ...(props.tags ?? {}), projectId },+ preferredClickhouseService: "EventsReadOnly",});};diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex fe6f95b1be..3824fc897c 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -33,7 +33,6 @@ import {import { OrderByState } from "../../interfaces/orderBy";import { matchesUiColumnMapping } from "../../tableDefinitions";import { getTracesByIds } from "./traces";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import {convertDateToClickhouseDateTime,PreferredClickhouseService,@@ -838,32 +837,27 @@ const getObservationsTableInternal = async <T>(${opts.select === "rows" && !skipDedup ? "LIMIT 1 BY o.id, o.project_id" : ""}${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : ""};`;- return measureAndReturn({- operationName: "getObservationsTableInternal",- projectId,- input: {- params: {- ...appliedScoresFilter.params,- ...appliedObservationsFilter.params,- ...(timeFilter- ? {- tracesTimestampFilter: convertDateToClickhouseDateTime(- timeFilter.value as Date,- ),- }- : {}),- ...search.params,- },- tags: { projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- clickhouseConfigs,- });+ const input = {+ params: {+ ...appliedScoresFilter.params,+ ...appliedObservationsFilter.params,+ ...(timeFilter+ ? {+ tracesTimestampFilter: convertDateToClickhouseDateTime(+ timeFilter.value as Date,+ ),+ }+ : {}),+ ...search.params,},+ tags: { projectId },+ };++ return queryClickhouse<T>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,});};@@ -2106,28 +2100,23 @@ export const generateObservationsForPublicApi = async ({ORDER BY start_time DESC`;- return measureAndReturn({- operationName: "generateObservationsForPublicApi",- projectId,- input: {- params: {- ...appliedFilter.params,- projectId,- limit: pagination.limit,- offset: (pagination.page - 1) * pagination.limit,- },- tags: { projectId },- },- fn: async (input) => {- const result = await queryClickhouse<ObservationRecordReadType>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });- return result.map((r) => convertObservation(r));+ const input = {+ params: {+ ...appliedFilter.params,+ projectId,+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,},+ tags: { projectId },+ };++ const result = await queryClickhouse<ObservationRecordReadType>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});+ return result.map((r) => convertObservation(r));};export const getObservationsCountForPublicApi = async ({@@ -2149,21 +2138,11 @@ export const getObservationsCountForPublicApi = async ({AND ${appliedFilter.query}`;- return measureAndReturn({- operationName: "getObservationsCountForPublicApi",- projectId,- input: {- params: { ...appliedFilter.params, projectId },- tags: { projectId },- },- fn: async (input) => {- const records = await queryClickhouse<{ count: string }>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });- return records.map((record) => Number(record.count)).shift();- },+ const records = await queryClickhouse<{ count: string }>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: { ...appliedFilter.params, projectId },+ tags: { projectId },+ preferredClickhouseService: "ReadOnly",});+ return records.map((record) => Number(record.count)).shift();};diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 415b4f4fa4..f5ed7025e0 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -63,7 +63,6 @@ import { ClickHouseClientConfigOptions } from "@clickhouse/client";import { recordDistribution } from "../instrumentation";import { logger } from "../logger";import { prisma } from "../../db";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import { scoresColumnsTableUiColumnDefinitions } from "../tableMappings/mapScoresColumnsTable";import {eventsTraceMetadata,@@ -760,58 +759,53 @@ export async function queryScoreRecordsForExperimentItems({return [];}- return await measureAndReturn({- operationName: "queryScoreRecordsForExperimentItems",- projectId,- input: {- params: {- projectId,- traceIds: uniqueTraceIds,- observationIds: uniqueObservationIds,- minStartTime: convertDateToClickhouseDateTime(min),- ...(toTimestamp- ? { maxStartTime: convertDateToClickhouseDateTime(toTimestamp) }- : {}),- scoreLimit,- dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),- },- tags: {- projectId,- operation_name: "queryScoreRecordsForExperimentItems",- },+ const input = {+ params: {+ projectId,+ traceIds: uniqueTraceIds,+ observationIds: uniqueObservationIds,+ minStartTime: convertDateToClickhouseDateTime(min),+ ...(toTimestamp+ ? { maxStartTime: convertDateToClickhouseDateTime(toTimestamp) }+ : {}),+ scoreLimit,+ dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),},- fn: async (input) =>- await queryClickhouse<ScoreRecordReadType>({- query: `- SELECT- ${scoreRecordReadSelect}- FROM (- SELECT- ${scoreRecordReadSelect}- FROM scores s- WHERE s.project_id = {projectId: String}- AND s.timestamp >= {minStartTime: DateTime64(3)}- ${toTimestamp ? "AND s.timestamp < {maxStartTime: DateTime64(3)}" : ""}- AND s.data_type IN ({dataTypes: Array(String)})- AND (- s.observation_id IN ({observationIds: Array(String)})- OR (- s.trace_id IN ({traceIds: Array(String)})- AND (s.observation_id IS NULL OR s.observation_id = '')- AND s.session_id IS NULL- AND s.dataset_run_id IS NULL- )- )- ORDER BY s.event_ts DESC- LIMIT 1 BY s.id- ) s- ORDER BY s.event_ts DESC- LIMIT {scoreLimit: UInt32} BY s.trace_id- `,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- }),+ tags: {+ projectId,+ operation_name: "queryScoreRecordsForExperimentItems",+ },+ };+ return await queryClickhouse<ScoreRecordReadType>({+ query: `+ SELECT+ ${scoreRecordReadSelect}+ FROM (+ SELECT+ ${scoreRecordReadSelect}+ FROM scores s+ WHERE s.project_id = {projectId: String}+ AND s.timestamp >= {minStartTime: DateTime64(3)}+ ${toTimestamp ? "AND s.timestamp < {maxStartTime: DateTime64(3)}" : ""}+ AND s.data_type IN ({dataTypes: Array(String)})+ AND (+ s.observation_id IN ({observationIds: Array(String)})+ OR (+ s.trace_id IN ({traceIds: Array(String)})+ AND (s.observation_id IS NULL OR s.observation_id = '')+ AND s.session_id IS NULL+ AND s.dataset_run_id IS NULL+ )+ )+ ORDER BY s.event_ts DESC+ LIMIT 1 BY s.id+ ) s+ ORDER BY s.event_ts DESC+ LIMIT {scoreLimit: UInt32} BY s.trace_id+ `,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});}@@ -834,52 +828,47 @@ export async function queryScoreRecordsForExperiments({return [];}- return await measureAndReturn({- operationName: "queryScoreRecordsForExperiments",- projectId,- input: {- params: {- projectId,- experimentIds: uniqueExperimentIds,- startTimeFrom: convertDateToClickhouseDateTime(fromTimestamp),- ...(toTimestamp- ? { startTimeTo: convertDateToClickhouseDateTime(toTimestamp) }- : {}),- scoreLimit,- dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),- },- tags: {- projectId,- operation_name: "queryScoreRecordsForExperiments",- },+ const input = {+ params: {+ projectId,+ experimentIds: uniqueExperimentIds,+ startTimeFrom: convertDateToClickhouseDateTime(fromTimestamp),+ ...(toTimestamp+ ? { startTimeTo: convertDateToClickhouseDateTime(toTimestamp) }+ : {}),+ scoreLimit,+ dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),},- fn: async (input) =>- await queryClickhouse<ScoreRecordReadType>({- query: `- SELECT- ${scoreRecordReadSelect}- FROM (- SELECT- ${scoreRecordReadSelect}- FROM scores s- WHERE s.project_id = {projectId: String}- AND s.timestamp >= {startTimeFrom: DateTime64(3)}- ${toTimestamp ? "AND s.timestamp < {startTimeTo: DateTime64(3)}" : ""}- AND s.dataset_run_id IN ({experimentIds: Array(String)})- AND s.data_type IN ({dataTypes: Array(String)})- AND s.trace_id IS NULL- AND s.observation_id IS NULL- AND s.session_id IS NULL- ORDER BY s.event_ts DESC- LIMIT 1 BY s.id- ) s- ORDER BY s.dataset_run_id ASC, s.event_ts DESC- LIMIT {scoreLimit: UInt32} BY s.dataset_run_id- `,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- }),+ tags: {+ projectId,+ operation_name: "queryScoreRecordsForExperiments",+ },+ };+ return await queryClickhouse<ScoreRecordReadType>({+ query: `+ SELECT+ ${scoreRecordReadSelect}+ FROM (+ SELECT+ ${scoreRecordReadSelect}+ FROM scores s+ WHERE s.project_id = {projectId: String}+ AND s.timestamp >= {startTimeFrom: DateTime64(3)}+ ${toTimestamp ? "AND s.timestamp < {startTimeTo: DateTime64(3)}" : ""}+ AND s.dataset_run_id IN ({experimentIds: Array(String)})+ AND s.data_type IN ({dataTypes: Array(String)})+ AND s.trace_id IS NULL+ AND s.observation_id IS NULL+ AND s.session_id IS NULL+ ORDER BY s.event_ts DESC+ LIMIT 1 BY s.id+ ) s+ ORDER BY s.dataset_run_id ASC, s.event_ts DESC+ LIMIT {scoreLimit: UInt32} BY s.dataset_run_id+ `,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});}@@ -1398,27 +1387,21 @@ const getScoresUiGeneric = async <T>(props: {${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}`;- return measureAndReturn({- operationName: "getScoresUiGeneric",- projectId,- input: {- params: {- projectId: projectId,- dataTypes: LISTABLE_SCORE_TYPES,- ...(scoresFilterRes ? scoresFilterRes.params : {}),- limit: limit,- offset: offset,- },- tags: { ...(props.tags ?? {}), projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs,- });+ const input = {+ params: {+ projectId: projectId,+ dataTypes: LISTABLE_SCORE_TYPES,+ ...(scoresFilterRes ? scoresFilterRes.params : {}),+ limit: limit,+ offset: offset,},+ tags: { ...(props.tags ?? {}), projectId },+ };+ return queryClickhouse<T>({+ query,+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,});};@@ -1599,31 +1582,23 @@ const getScoresUiGenericFromEvents = async <T>(props: {${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}`;- return measureAndReturn({- operationName: "getScoresUiGenericFromEvents",- projectId,- input: {- params: {- projectId,- dataTypes: LISTABLE_SCORE_TYPES,- ...(scoreOnlyFilterRes ? scoreOnlyFilterRes.params : {}),- ...tracesCTEParams,- limit,- offset,- },- tags: { ...(props.tags ?? {}), projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs,- preferredClickhouseService: needsTracesCTE- ? "EventsReadOnly"- : "ReadOnly",- });+ const input = {+ params: {+ projectId,+ dataTypes: LISTABLE_SCORE_TYPES,+ ...(scoreOnlyFilterRes ? scoreOnlyFilterRes.params : {}),+ ...tracesCTEParams,+ limit,+ offset,},+ tags: { ...(props.tags ?? {}), projectId },+ };+ return queryClickhouse<T>({+ query,+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,+ preferredClickhouseService: needsTracesCTE ? "EventsReadOnly" : "ReadOnly",});};@@ -1951,24 +1926,18 @@ export const getNumericScoreHistogram = async (${limit !== undefined ? `limit {limit: Int32}` : ""}`;- return measureAndReturn({- operationName: "getNumericScoreHistogram",- projectId,- input: {- params: {- projectId,- limit,- ...(chFilterRes ? chFilterRes.params : {}),- },- tags: { projectId },- },- fn: async (input) => {- return queryClickhouse<{ value: number }>({- query,- params: input.params,- tags: input.tags,- });+ const input = {+ params: {+ projectId,+ limit,+ ...(chFilterRes ? chFilterRes.params : {}),},+ tags: { projectId },+ };+ return queryClickhouse<{ value: number }>({+ query,+ params: input.params,+ tags: input.tags,});};@@ -2845,54 +2814,48 @@ export const _handleGenerateScoresForPublicApi = async ({${pagination !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;- return measureAndReturn({- operationName: "_handleGenerateScoresForPublicApi",- projectId,- input: {- params: {- ...appliedScoresFilter.params,- ...appliedTracesFilter.params,- projectId,- ...(pagination !== undefined- ? {- limit: pagination.limit,- offset: (pagination.page - 1) * pagination.limit,- }- : {}),- },- tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },+ const input = {+ params: {+ ...appliedScoresFilter.params,+ ...appliedTracesFilter.params,+ projectId,+ ...(pagination !== undefined+ ? {+ limit: pagination.limit,+ offset: (pagination.page - 1) * pagination.limit,+ }+ : {}),},- fn: async (input) => {- const records = await queryClickhouse<- ScoreRecordReadType & {- tags?: string[];- user_id?: string;- trace_environment?: string;- trace_session_id?: string | null;- }- >({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });+ tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },+ };+ const records = await queryClickhouse<+ ScoreRecordReadType & {+ tags?: string[];+ user_id?: string;+ trace_environment?: string;+ trace_session_id?: string | null;+ }+ >({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",+ });- return records.map((record) => {- const domainScore = convertClickhouseScoreToDomain(record);- return {- ...domainScore,- trace:- includeTrace && record.trace_id !== null- ? {- userId: record.user_id,- tags: record.tags,- environment: record.trace_environment,- sessionId: record.trace_session_id,- }- : null,- };- });- },+ return records.map((record) => {+ const domainScore = convertClickhouseScoreToDomain(record);+ return {+ ...domainScore,+ trace:+ includeTrace && record.trace_id !== null+ ? {+ userId: record.user_id,+ tags: record.tags,+ environment: record.trace_environment,+ sessionId: record.trace_session_id,+ }+ : null,+ };});};@@ -2944,27 +2907,21 @@ export const _handleGetScoresCountForPublicApi = async ({${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}`;- return measureAndReturn({- operationName: "_handleGetScoresCountForPublicApi",- projectId,- input: {- params: {- ...appliedScoresFilter.params,- ...appliedTracesFilter.params,- projectId,- },- tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },- },- fn: async (input) => {- const records = await queryClickhouse<{ count: string }>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });- return records.map((record) => Number(record.count)).shift();+ const input = {+ params: {+ ...appliedScoresFilter.params,+ ...appliedTracesFilter.params,+ projectId,},+ tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },+ };+ const records = await queryClickhouse<{ count: string }>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});+ return records.map((record) => Number(record.count)).shift();};// ─── v3 public-API score query helpers ────────────────────────────────────────@@ -3325,76 +3282,68 @@ export async function listScoresV3ForPublicApi(const { query: filterClause, params: filterParams } =buildDynamicFilters(params);- return measureAndReturn({- operationName: "listScoresV3ForPublicApi",- projectId: params.projectId,- input: {- params: {- projectId: params.projectId,- limit: params.limit + 1,- ...(params.cursor && {- lastTimestamp: convertDateToClickhouseDateTime(- params.cursor.lastTimestamp,- ),- lastId: params.cursor.lastId,- }),- ...filterParams,- },- tags: { projectId: params.projectId },- },- fn: async (input) => {- const records = await queryClickhouse<ScoreRecordReadType>({- query: buildV3ListQuery(- Boolean(params.cursor),- params.fields,- filterClause,+ const input = {+ params: {+ projectId: params.projectId,+ limit: params.limit + 1,+ ...(params.cursor && {+ lastTimestamp: convertDateToClickhouseDateTime(+ params.cursor.lastTimestamp,),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });-- const hasMore = records.length > params.limit;- const pageRecords = hasMore ? records.slice(0, params.limit) : records;-- let nextCursor: string | undefined;- if (hasMore && pageRecords.length > 0) {- const last = pageRecords[pageRecords.length - 1];- nextCursor = encodeCursorV3({- v: 1,- lastTimestamp: parseClickhouseUTCDateTimeFormat(- String(last.timestamp),- ),- lastId: last.id,- });- }-- const items: APIScoreV3[] = [];- for (const row of pageRecords) {- try {- items.push(- scoreDomainToV3(convertClickhouseScoreToDomain(row), params.fields),- );- } catch (error) {- logger.error("v3 score row dropped from response: conversion error", {- error,- scoreId: row.id,- projectId: params.projectId,- });- }- }- return {- data: filterAndValidateV3GetScoreList(items, (error) => {- logger.error(- "v3 score row dropped from response: schema validation error",- {- issues: error.issues,- projectId: params.projectId,- },- );- }),- cursor: nextCursor,- };+ lastId: params.cursor.lastId,+ }),+ ...filterParams,},+ tags: { projectId: params.projectId },+ };+ const records = await queryClickhouse<ScoreRecordReadType>({+ query: buildV3ListQuery(+ Boolean(params.cursor),+ params.fields,+ filterClause,+ ),+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});++ const hasMore = records.length > params.limit;+ const pageRecords = hasMore ? records.slice(0, params.limit) : records;++ let nextCursor: string | undefined;+ if (hasMore && pageRecords.length > 0) {+ const last = pageRecords[pageRecords.length - 1];+ nextCursor = encodeCursorV3({+ v: 1,+ lastTimestamp: parseClickhouseUTCDateTimeFormat(String(last.timestamp)),+ lastId: last.id,+ });+ }++ const items: APIScoreV3[] = [];+ for (const row of pageRecords) {+ try {+ items.push(+ scoreDomainToV3(convertClickhouseScoreToDomain(row), params.fields),+ );+ } catch (error) {+ logger.error("v3 score row dropped from response: conversion error", {+ error,+ scoreId: row.id,+ projectId: params.projectId,+ });+ }+ }+ return {+ data: filterAndValidateV3GetScoreList(items, (error) => {+ logger.error(+ "v3 score row dropped from response: schema validation error",+ {+ issues: error.issues,+ projectId: params.projectId,+ },+ );+ }),+ cursor: nextCursor,+ };}diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex c239f8578d..e1986d7fef 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -44,7 +44,6 @@ import { env } from "../../env";import { ClickHouseClientConfigOptions } from "@clickhouse/client";import { recordDistribution } from "../instrumentation";import type { AnalyticsTraceEvent } from "../analytics-integrations/types";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import { DEFAULT_RENDERING_PROPS, RenderingProps } from "../utils/rendering";import { logger } from "../logger";import { traceException } from "../instrumentation";@@ -140,66 +139,59 @@ export const checkTraceExistsAndGetTimestamp = async ({)`;- return measureAndReturn({- operationName: "checkTraceExistsAndGetTimestamp",- projectId,- input: {- params: {- projectId,- ...tracesFilterRes.params,- ...(observationFilterRes ? observationFilterRes.params : {}),- ...(timestamp- ? { timestamp: convertDateToClickhouseDateTime(timestamp) }- : {}),- ...(maxTimeStamp- ? { maxTimeStamp: convertDateToClickhouseDateTime(maxTimeStamp) }- : {}),- ...(exactTimestamp- ? { exactTimestamp: convertDateToClickhouseDateTime(exactTimestamp) }- : {}),- },- tags: { projectId },- timestamp: timestamp ?? exactTimestamp,- },- fn: async (input) => {- const query = `- ${observations_cte}- SELECT- t.id as id,- t.project_id as project_id,- t.timestamp as timestamp- -- We skip FINAL here. If one trace exists that matches the conditions, we consider this truthy- -- even if the trace got updated in the meantime to a non-matching state.- -- As updates are usually addittive, this is deemed acceptable given the performance benefits.- FROM traces t- ${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}- WHERE ${tracesFilterRes.query}- AND t.project_id = {projectId: String}- AND t.timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}- ${maxTimeStamp ? `AND t.timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}- ${!maxTimeStamp ? `AND t.timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}- ${exactTimestamp ? `AND toDate(t.timestamp) = toDate({exactTimestamp: DateTime64(3)})` : ""}- GROUP BY t.id, t.project_id, t.timestamp- `;-- const rows = await queryClickhouse<{- id: string;- project_id: string;- timestamp: string;- }>({- query,- params: input.params,- });-- return {- exists: rows.length > 0,- timestamp:- rows.length > 0- ? parseClickhouseUTCDateTimeFormat(rows[0].timestamp)- : undefined,- };+ const input = {+ params: {+ projectId,+ ...tracesFilterRes.params,+ ...(observationFilterRes ? observationFilterRes.params : {}),+ ...(timestamp+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }+ : {}),+ ...(maxTimeStamp+ ? { maxTimeStamp: convertDateToClickhouseDateTime(maxTimeStamp) }+ : {}),+ ...(exactTimestamp+ ? { exactTimestamp: convertDateToClickhouseDateTime(exactTimestamp) }+ : {}),},+ };++ const query = `+ ${observations_cte}+ SELECT+ t.id as id,+ t.project_id as project_id,+ t.timestamp as timestamp+ -- We skip FINAL here. If one trace exists that matches the conditions, we consider this truthy+ -- even if the trace got updated in the meantime to a non-matching state.+ -- As updates are usually addittive, this is deemed acceptable given the performance benefits.+ FROM traces t+ ${observationFilterRes ? `INNER JOIN observations_agg o ON t.id = o.trace_id AND t.project_id = o.project_id` : ""}+ WHERE ${tracesFilterRes.query}+ AND t.project_id = {projectId: String}+ AND t.timestamp >= {timestamp: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}+ ${maxTimeStamp ? `AND t.timestamp <= {maxTimeStamp: DateTime64(3)}` : ""}+ ${!maxTimeStamp ? `AND t.timestamp <= {timestamp: DateTime64(3)} + INTERVAL 2 DAY` : ""}+ ${exactTimestamp ? `AND toDate(t.timestamp) = toDate({exactTimestamp: DateTime64(3)})` : ""}+ GROUP BY t.id, t.project_id, t.timestamp+ `;++ const rows = await queryClickhouse<{+ id: string;+ project_id: string;+ timestamp: string;+ }>({+ query,+ params: input.params,});++ return {+ exists: rows.length > 0,+ timestamp:+ rows.length > 0+ ? parseClickhouseUTCDateTimeFormat(rows[0].timestamp)+ : undefined,+ };};/**@@ -225,37 +217,24 @@ export const getTracesByIds = async (timestamp?: Date,clickhouseConfigs?: ClickHouseClientConfigOptions | undefined,) => {- const records = await measureAndReturn({- operationName: "getTracesByIds",- projectId,- input: {- params: {- traceIds,- projectId,- timestamp: timestamp- ? convertDateToClickhouseDateTime(timestamp)- : null,- },- tags: { projectId },- clickhouseConfigs,- },- fn: (input) => {- const query = `- SELECT *- FROM traces- WHERE id IN ({traceIds: Array(String)})- AND project_id = {projectId: String}- ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}- ORDER BY event_ts DESC- LIMIT 1 by id, project_id;- `;- return queryClickhouse<TraceRecordReadType>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs: input.clickhouseConfigs,- });+ const query = `+ SELECT *+ FROM traces+ WHERE id IN ({traceIds: Array(String)})+ AND project_id = {projectId: String}+ ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}+ ORDER BY event_ts DESC+ LIMIT 1 by id, project_id;+ `;+ const records = await queryClickhouse<TraceRecordReadType>({+ query,+ params: {+ traceIds,+ projectId,+ timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,},+ tags: { projectId },+ clickhouseConfigs,});return records.map((record) =>@@ -268,36 +247,23 @@ export const getTracesBySessionId = async (sessionIds: string[],timestamp?: Date,) => {- const records = await measureAndReturn({- operationName: "getTracesBySessionId",- projectId,- input: {- params: {- sessionIds,- projectId,- timestamp: timestamp- ? convertDateToClickhouseDateTime(timestamp)- : null,- },- tags: { projectId },- timestamp,- },- fn: (input) => {- const query = `- SELECT *- FROM traces- WHERE session_id IN ({sessionIds: Array(String)})- AND project_id = {projectId: String}- ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}- ORDER BY event_ts DESC- LIMIT 1 by id, project_id;- `;- return queryClickhouse<TraceRecordReadType>({- query,- params: input.params,- tags: input.tags,- });+ const query = `+ SELECT *+ FROM traces+ WHERE session_id IN ({sessionIds: Array(String)})+ AND project_id = {projectId: String}+ ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}+ ORDER BY event_ts DESC+ LIMIT 1 by id, project_id;+ `;+ const records = await queryClickhouse<TraceRecordReadType>({+ query,+ params: {+ sessionIds,+ projectId,+ timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,},+ tags: { projectId },});const traces = records.map((record) =>@@ -364,36 +330,26 @@ export const hasAnyTrace = async (projectId: string) => {return true;}- const result = await measureAndReturn({- operationName: "hasAnyTrace",- projectId,- input: {+ const query = `+ SELECT 1+ FROM traces+ WHERE project_id = {projectId: String}+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {projectId,- tags: { projectId },},- fn: async (input) => {- const query = `- SELECT 1- FROM traces- WHERE project_id = {projectId: String}- LIMIT 1- `;-- const rows = await queryClickhouse<{ 1: number }>({- query,- params: {- projectId: input.projectId,- },- tags: input.tags,- clickhouseSettings: {- max_threads: 1,- },- });-- return rows.length > 0;+ tags: { projectId },+ clickhouseSettings: {+ max_threads: 1,},});+ const result = rows.length > 0;+// Persist positive result in PostgreSQL — once a project has traces, it stays trueif (result) {await persistProjectHasTracesFlag(projectId);@@ -409,43 +365,31 @@ export const getTraceCountsByProjectInCreationInterval = async ({start: Date;end: Date;}) => {- return measureAndReturn({- operationName: "getTraceCountsByProjectInCreationInterval",- projectId: "__CROSS_PROJECT__",- input: {- params: {- start: convertDateToClickhouseDateTime(start),- end: convertDateToClickhouseDateTime(end),- },- timestamp: start,+ const query = `+ SELECT+ project_id,+ count(*) as count+ FROM traces+ WHERE created_at >= {start: DateTime64(3)}+ AND created_at < {end: DateTime64(3)}+ GROUP BY project_id+ `;++ const rows = await queryClickhouse<{ project_id: string; count: string }>({+ query,+ params: {+ start: convertDateToClickhouseDateTime(start),+ end: convertDateToClickhouseDateTime(end),},- fn: async (input) => {- const query = `- SELECT- project_id,- count(*) as count- FROM traces- WHERE created_at >= {start: DateTime64(3)}- AND created_at < {end: DateTime64(3)}- GROUP BY project_id- `;-- const rows = await queryClickhouse<{ project_id: string; count: string }>(- {- query,- params: input.params,- clickhouseConfigs: {- request_timeout: 300000, // 5 minutes timeout- },- },- );-- return rows.map((row) => ({- projectId: row.project_id,- count: Number(row.count),- }));+ clickhouseConfigs: {+ request_timeout: 300000, // 5 minutes timeout},});++ return rows.map((row) => ({+ projectId: row.project_id,+ count: Number(row.count),+ }));};export const getLastTraceTimestampsByProjectsFromTracesTable = async ({@@ -487,33 +431,23 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({projectIds: string[];start: Date;}) => {- return measureAndReturn({- operationName: "getTraceCountOfProjectsSinceCreationDate",- projectId: "__CROSS_PROJECT__",- input: {- params: {- projectIds,- start: convertDateToClickhouseDateTime(start),- },- timestamp: start,- },- fn: async (input) => {- const query = `- SELECT- count(*) as count- FROM traces- WHERE project_id IN ({projectIds: Array(String)})- AND created_at >= {start: DateTime64(3)}- `;-- const rows = await queryClickhouse<{ count: string }>({- query,- params: input.params,- });-- return Number(rows[0]?.count ?? 0);+ const query = `+ SELECT+ count(*) as count+ FROM traces+ WHERE project_id IN ({projectIds: Array(String)})+ AND created_at >= {start: DateTime64(3)}+ `;++ const rows = await queryClickhouse<{ count: string }>({+ query,+ params: {+ projectIds,+ start: convertDateToClickhouseDateTime(start),},});++ return Number(rows[0]?.count ?? 0);};/**@@ -546,73 +480,68 @@ export const getTraceByIdFromTracesTable = async ({/** When true, sets metadata column to empty in the query to reduce database load */excludeMetadata?: boolean;}) => {- const records = await measureAndReturn({- operationName: "getTraceById",- projectId,- input: {- params: {- traceId,- projectId,- ...(timestamp- ? { timestamp: convertDateToClickhouseDateTime(timestamp) }- : {}),- ...(fromTimestamp- ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }- : {}),- },- tags: { projectId },- },- fn: (input) => {- const inputColumn = excludeInputOutput- ? "''"- : renderingProps.truncated- ? `leftUTF8(input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})`- : "input";- const outputColumn = excludeInputOutput- ? "''"- : renderingProps.truncated- ? `leftUTF8(output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})`- : "output";- // map() (not a '{}' string literal) so the excluded column keeps the- // Map type and converts to an empty object in the domain model.- const metadataColumn = excludeMetadata ? "map()" : "metadata";-- const query = `- SELECT- id,- name as name,- user_id as user_id,- ${metadataColumn} as metadata,- release as release,- version as version,- project_id,- environment,- public as public,- bookmarked as bookmarked,- tags,- ${inputColumn} as input,- ${outputColumn} as output,- session_id as session_id,- 0 as is_deleted,- timestamp,- created_at,- updated_at- FROM traces- WHERE id = {traceId: String}- AND project_id = {projectId: String}- ${timestamp ? `AND toDate(timestamp) = toDate({timestamp: DateTime64(3)})` : ""}- ${fromTimestamp ? `AND timestamp >= {fromTimestamp: DateTime64(3)}` : ""}- ORDER BY event_ts DESC- LIMIT 1- `;-- return queryClickhouse<TraceRecordReadType>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService,- });+ const input = {+ params: {+ traceId,+ projectId,+ ...(timestamp+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }+ : {}),+ ...(fromTimestamp+ ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }+ : {}),},+ tags: { projectId },+ };++ const inputColumn = excludeInputOutput+ ? "''"+ : renderingProps.truncated+ ? `leftUTF8(input, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})`+ : "input";+ const outputColumn = excludeInputOutput+ ? "''"+ : renderingProps.truncated+ ? `leftUTF8(output, ${env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT})`+ : "output";+ // map() (not a '{}' string literal) so the excluded column keeps the+ // Map type and converts to an empty object in the domain model.+ const metadataColumn = excludeMetadata ? "map()" : "metadata";++ const query = `+ SELECT+ id,+ name as name,+ user_id as user_id,+ ${metadataColumn} as metadata,+ release as release,+ version as version,+ project_id,+ environment,+ public as public,+ bookmarked as bookmarked,+ tags,+ ${inputColumn} as input,+ ${outputColumn} as output,+ session_id as session_id,+ 0 as is_deleted,+ timestamp,+ created_at,+ updated_at+ FROM traces+ WHERE id = {traceId: String}+ AND project_id = {projectId: String}+ ${timestamp ? `AND toDate(timestamp) = toDate({timestamp: DateTime64(3)})` : ""}+ ${fromTimestamp ? `AND timestamp >= {fromTimestamp: DateTime64(3)}` : ""}+ ORDER BY event_ts DESC+ LIMIT 1+ `;++ const records = await queryClickhouse<TraceRecordReadType>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService,});const res = records.map((record) =>@@ -645,42 +574,37 @@ export const getTracesGroupedByName = async (? new FilterList(chFilter).apply(): undefined;- return measureAndReturn({- operationName: "getTracesGroupedByName",- projectId,- input: {- params: {- projectId,- ...(timestampFilterRes ? timestampFilterRes.params : {}),- },- tags: { projectId },- },- fn: async (input) => {- // We mainly use queries like this to retrieve filter options.- // Therefore, we can skip final as some inaccuracy in count is acceptable.- const query = `- select- name as name,- count(*) as count- from traces t- WHERE t.project_id = {projectId: String}- AND t.name IS NOT NULL- ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}- GROUP BY name- ORDER BY count(*) desc- LIMIT 1000;- `;-- return queryClickhouse<{- name: string;- count: string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });+ const input = {+ params: {+ projectId,+ ...(timestampFilterRes ? timestampFilterRes.params : {}),},+ tags: { projectId },+ };++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const query = `+ select+ name as name,+ count(*) as count+ from traces t+ WHERE t.project_id = {projectId: String}+ AND t.name IS NOT NULL+ ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}+ GROUP BY name+ ORDER BY count(*) desc+ LIMIT 1000;+ `;++ return queryClickhouse<{+ name: string;+ count: string;+ }>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});};@@ -711,47 +635,42 @@ export const getTracesGroupedBySessionId = async (tablePrefix: "t",});- return measureAndReturn({- operationName: "getTracesGroupedBySessionId",- projectId,- input: {- params: {- limit,- offset,- projectId,- ...(tracesFilterRes ? tracesFilterRes.params : {}),- ...(searchQuery ? search.params : {}),- },- tags: { projectId },- },- fn: async (input) => {- // We mainly use queries like this to retrieve filter options.- // Therefore, we can skip final as some inaccuracy in count is acceptable.- const query = `- select- session_id as session_id,- count(*) as count- from traces t- WHERE t.project_id = {projectId: String}- AND t.session_id IS NOT NULL- AND t.session_id != ''- ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}- ${search.query}- GROUP BY session_id- ORDER BY count desc- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}- `;-- return queryClickhouse<{- session_id: string;- count: string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });+ const input = {+ params: {+ limit,+ offset,+ projectId,+ ...(tracesFilterRes ? tracesFilterRes.params : {}),+ ...(searchQuery ? search.params : {}),},+ tags: { projectId },+ };++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const query = `+ select+ session_id as session_id,+ count(*) as count+ from traces t+ WHERE t.project_id = {projectId: String}+ AND t.session_id IS NOT NULL+ AND t.session_id != ''+ ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}+ ${search.query}+ GROUP BY session_id+ ORDER BY count desc+ ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ return queryClickhouse<{+ session_id: string;+ count: string;+ }>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});};@@ -782,47 +701,42 @@ export const getTracesGroupedByUsers = async (tablePrefix: "t",});- return measureAndReturn({- operationName: "getTracesGroupedByUsers",- projectId,- input: {- params: {- limit,- offset,- projectId,- ...(tracesFilterRes ? tracesFilterRes.params : {}),- ...(searchQuery ? search.params : {}),- },- tags: { projectId },- },- fn: async (input) => {- // We mainly use queries like this to retrieve filter options.- // Therefore, we can skip final as some inaccuracy in count is acceptable.- const query = `- select- user_id as user,- count(*) as count- from traces t- WHERE t.project_id = {projectId: String}- AND t.user_id IS NOT NULL- AND t.user_id != ''- ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}- ${search.query}- GROUP BY user- ORDER BY count desc- ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}- `;-- return queryClickhouse<{- user: string;- count: string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });+ const input = {+ params: {+ limit,+ offset,+ projectId,+ ...(tracesFilterRes ? tracesFilterRes.params : {}),+ ...(searchQuery ? search.params : {}),},+ tags: { projectId },+ };++ // We mainly use queries like this to retrieve filter options.+ // Therefore, we can skip final as some inaccuracy in count is acceptable.+ const query = `+ select+ user_id as user,+ count(*) as count+ from traces t+ WHERE t.project_id = {projectId: String}+ AND t.user_id IS NOT NULL+ AND t.user_id != ''+ ${tracesFilterRes?.query ? `AND ${tracesFilterRes.query}` : ""}+ ${search.query}+ GROUP BY user+ ORDER BY count desc+ ${limit !== undefined && offset !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ return queryClickhouse<{+ user: string;+ count: string;+ }>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});};@@ -844,34 +758,29 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {const filterRes = new FilterList(chFilter).apply();- return measureAndReturn({- operationName: "getTracesGroupedByTags",- projectId,- input: {- params: {- projectId,- ...(filterRes ? filterRes.params : {}),- },- tags: { projectId },- },- fn: async (input) => {- const query = `- select distinct(arrayJoin(tags)) as value- from traces t- WHERE t.project_id = {projectId: String}- ${filterRes?.query ? `AND ${filterRes.query}` : ""}- LIMIT 1000;- `;-- return queryClickhouse<{- value: string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });+ const input = {+ params: {+ projectId,+ ...(filterRes ? filterRes.params : {}),},+ tags: { projectId },+ };++ const query = `+ select distinct(arrayJoin(tags)) as value+ from traces t+ WHERE t.project_id = {projectId: String}+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}+ LIMIT 1000;+ `;++ return queryClickhouse<{+ value: string;+ }>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "ReadOnly",});};@@ -889,42 +798,32 @@ export const getTracesIdentifierForSessionFromTracesTable = async (projectId: string,sessionId: string,) => {- const rows = await measureAndReturn({- operationName: "getTracesIdentifierForSession",- projectId,- input: {- params: {- projectId,- sessionId,- },- tags: { projectId },- },- fn: (input) => {- const query = `- SELECT- id,- user_id,- name,- timestamp,- project_id,- environment- FROM traces- WHERE (project_id = {projectId: String})- AND (session_id = {sessionId: String})- ORDER BY timestamp ASC- LIMIT 1 BY id, project_id;- `;-- return queryClickhouse<{- id: string;- user_id: string;- name: string;- timestamp: string;- environment: string;- }>({- query,- params: input.params,- });+ const query = `+ SELECT+ id,+ user_id,+ name,+ timestamp,+ project_id,+ environment+ FROM traces+ WHERE (project_id = {projectId: String})+ AND (session_id = {sessionId: String})+ ORDER BY timestamp ASC+ LIMIT 1 BY id, project_id;+ `;++ const rows = await queryClickhouse<{+ id: string;+ user_id: string;+ name: string;+ timestamp: string;+ environment: string;+ }>({+ query,+ params: {+ projectId,+ sessionId,},});@@ -938,65 +837,60 @@ export const getTracesIdentifierForSessionFromTracesTable = async (};export const deleteTraces = async (projectId: string, traceIds: string[]) => {- await measureAndReturn({- operationName: "deleteTraces",- projectId,- input: {- params: {- projectId,- traceIds,- },- tags: { projectId },+ const input = {+ params: {+ projectId,+ traceIds,},- fn: async (input) => {- // Pre-flight query with time bounds computed- const preflight = await queryClickhouse<{- min_ts: string;- max_ts: string;- cnt: string;- }>({- query: `- SELECT- min(timestamp) - INTERVAL 1 HOUR as min_ts,- max(timestamp) + INTERVAL 1 HOUR as max_ts,- count(*) as cnt- FROM traces- WHERE project_id = {projectId: String} AND id IN ({traceIds: Array(String)})- `,- params: input.params,- clickhouseConfigs: {- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,- },- tags: { ...input.tags },- });-- const count = Number(preflight[0]?.cnt ?? 0);- if (count === 0) {- logger.info(- `deleteTraces: no rows found for project ${projectId}, skipping DELETE`,- );- return;- }+ tags: { projectId },+ };- await commandClickhouse({- query: `- DELETE FROM traces- WHERE project_id = {projectId: String}- AND id IN ({traceIds: Array(String)})- AND timestamp >= {minTs: String}::DateTime64(3)- AND timestamp <= {maxTs: String}::DateTime64(3)- `,- params: {- ...input.params,- minTs: preflight[0].min_ts,- maxTs: preflight[0].max_ts,- },- clickhouseConfigs: {- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,- },- tags: input.tags,- });+ // Pre-flight query with time bounds computed+ const preflight = await queryClickhouse<{+ min_ts: string;+ max_ts: string;+ cnt: string;+ }>({+ query: `+ SELECT+ min(timestamp) - INTERVAL 1 HOUR as min_ts,+ max(timestamp) + INTERVAL 1 HOUR as max_ts,+ count(*) as cnt+ FROM traces+ WHERE project_id = {projectId: String} AND id IN ({traceIds: Array(String)})+ `,+ params: input.params,+ clickhouseConfigs: {+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,+ },+ tags: { ...input.tags },+ });++ const count = Number(preflight[0]?.cnt ?? 0);+ if (count === 0) {+ logger.info(+ `deleteTraces: no rows found for project ${projectId}, skipping DELETE`,+ );+ return;+ }++ await commandClickhouse({+ query: `+ DELETE FROM traces+ WHERE project_id = {projectId: String}+ AND id IN ({traceIds: Array(String)})+ AND timestamp >= {minTs: String}::DateTime64(3)+ AND timestamp <= {maxTs: String}::DateTime64(3)+ `,+ params: {+ ...input.params,+ minTs: preflight[0].min_ts,+ maxTs: preflight[0].max_ts,+ },+ clickhouseConfigs: {+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},+ tags: input.tags,});};@@ -1033,31 +927,21 @@ export const deleteTracesOlderThanDays = async (return false;}- await measureAndReturn({- operationName: "deleteTracesOlderThanDays",- projectId,- input: {- params: {- projectId,- cutoffDate: convertDateToClickhouseDateTime(beforeDate),- },- tags: { projectId },+ const query = `+ DELETE FROM traces+ WHERE project_id = {projectId: String}+ AND timestamp < {cutoffDate: DateTime64(3)};+ `;+ await commandClickhouse({+ query: query,+ params: {+ projectId,+ cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- fn: async (input) => {- const query = `- DELETE FROM traces- WHERE project_id = {projectId: String}- AND timestamp < {cutoffDate: DateTime64(3)};- `;- await commandClickhouse({- query: query,- params: input.params,- clickhouseConfigs: {- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,- },- tags: input.tags,- });+ clickhouseConfigs: {+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},+ tags: { projectId },});return true;@@ -1071,64 +955,44 @@ export const deleteTracesByProjectId = async (return false;}- await measureAndReturn({- operationName: "deleteTracesByProjectId",- projectId,- input: {- params: {- projectId,- },- tags: { projectId },+ const query = `+ DELETE FROM traces+ WHERE project_id = {projectId: String};+ `;++ await commandClickhouse({+ query,+ params: {+ projectId,},- fn: async (input) => {- const query = `- DELETE FROM traces- WHERE project_id = {projectId: String};- `;-- await commandClickhouse({- query,- params: input.params,- clickhouseConfigs: {- request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,- },- tags: input.tags,- });+ clickhouseConfigs: {+ request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},+ tags: { projectId },});return true;};export const hasAnyUser = async (projectId: string) => {- return measureAndReturn({- operationName: "hasAnyUser",- projectId,- input: {+ const query = `+ SELECT 1+ FROM traces+ WHERE project_id = {projectId: String}+ AND user_id IS NOT NULL+ AND user_id != ''+ LIMIT 1+ `;++ const rows = await queryClickhouse<{ 1: number }>({+ query,+ params: {projectId,- tags: { projectId },- },- fn: async (input) => {- const query = `- SELECT 1- FROM traces- WHERE project_id = {projectId: String}- AND user_id IS NOT NULL- AND user_id != ''- LIMIT 1- `;-- const rows = await queryClickhouse<{ 1: number }>({- query,- params: {- projectId: input.projectId,- },- tags: input.tags,- });-- return rows.length > 0;},+ tags: { projectId },});++ return rows.length > 0;};export const getTotalUserCount = async (@@ -1154,32 +1018,27 @@ export const getTotalUserCount = async (tablePrefix: "t",});- return measureAndReturn({- operationName: "getTotalUserCount",- projectId,- input: {- params: {- ...tracesFilterRes.params,- ...search.params,- },- tags: { projectId },- },- fn: async (input) => {- const query = `- SELECT COUNT(DISTINCT t.user_id) AS totalCount- FROM traces t- WHERE ${tracesFilterRes.query}- ${search.query}- AND t.user_id IS NOT NULL- AND t.user_id != ''- `;-- return queryClickhouse({- query,- params: input.params,- tags: input.tags,- });+ const input = {+ params: {+ ...tracesFilterRes.params,+ ...search.params,},+ tags: { projectId },+ };++ const query = `+ SELECT COUNT(DISTINCT t.user_id) AS totalCount+ FROM traces t+ WHERE ${tracesFilterRes.query}+ ${search.query}+ AND t.user_id IS NOT NULL+ AND t.user_id != ''+ `;++ return queryClickhouse({+ query,+ params: input.params,+ tags: input.tags,});};@@ -1277,56 +1136,51 @@ export const getUserMetrics = async (min_timestampFROM stats`;- return measureAndReturn({- operationName: "getUserMetrics",- projectId,- input: {- params: {- projectId,- userIds,- ...chFilterRes.params,- ...(timestampFilter- ? {- traceTimestamp: convertDateToClickhouseDateTime(- (timestampFilter as DateTimeFilter).value,- ),- }- : {}),- },- tags: { projectId },- },- fn: async (input) => {- const rows = await queryClickhouse<{- user_id: string;- environment: string;- max_timestamp: string;- min_timestamp: string;- input_usage: string;- output_usage: string;- total_usage: string;- obs_count: string;- trace_count: string;- sum_total_cost: string;- }>({- query: query.replaceAll("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- });-- return rows.map((row) => ({- userId: row.user_id,- environment: row.environment,- maxTimestamp: parseClickhouseUTCDateTimeFormat(row.max_timestamp),- minTimestamp: parseClickhouseUTCDateTimeFormat(row.min_timestamp),- inputUsage: Number(row.input_usage),- outputUsage: Number(row.output_usage),- totalUsage: Number(row.total_usage),- observationCount: Number(row.obs_count),- traceCount: Number(row.trace_count),- totalCost: Number(row.sum_total_cost),- }));+ const input = {+ params: {+ projectId,+ userIds,+ ...chFilterRes.params,+ ...(timestampFilter+ ? {+ traceTimestamp: convertDateToClickhouseDateTime(+ (timestampFilter as DateTimeFilter).value,+ ),+ }+ : {}),},+ tags: { projectId },+ };++ const rows = await queryClickhouse<{+ user_id: string;+ environment: string;+ max_timestamp: string;+ min_timestamp: string;+ input_usage: string;+ output_usage: string;+ total_usage: string;+ obs_count: string;+ trace_count: string;+ sum_total_cost: string;+ }>({+ query: query.replaceAll("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,});++ return rows.map((row) => ({+ userId: row.user_id,+ environment: row.environment,+ maxTimestamp: parseClickhouseUTCDateTimeFormat(row.max_timestamp),+ minTimestamp: parseClickhouseUTCDateTimeFormat(row.min_timestamp),+ inputUsage: Number(row.input_usage),+ outputUsage: Number(row.output_usage),+ totalUsage: Number(row.total_usage),+ observationCount: Number(row.obs_count),+ traceCount: Number(row.trace_count),+ totalCost: Number(row.sum_total_cost),+ }));};// Shared query for both the standard (parsed) and Parquet (`exec` binary)@@ -1509,35 +1363,26 @@ export const getTracesForAnalyticsIntegrations = async function* (* We expect at most 10s of calls per day, so this is acceptable.*/export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {- return measureAndReturn({- operationName: "getTracesByIdsForAnyProject",- projectId: "__CROSS_PROJECT__",- input: {- params: {- traceIds,- },- },- fn: async (input) => {- const query = `- SELECT id, project_id- FROM traces- WHERE id IN ({traceIds: Array(String)})- ORDER BY event_ts DESC- LIMIT 1 by id, project_id;`;- const records = await queryClickhouse<{- id: string;- project_id: string;- }>({- query,- params: input.params,- });-- return records.map((record) => ({- id: record.id,- projectId: record.project_id,- }));+ const query = `+ SELECT id, project_id+ FROM traces+ WHERE id IN ({traceIds: Array(String)})+ ORDER BY event_ts DESC+ LIMIT 1 by id, project_id;`;+ const records = await queryClickhouse<{+ id: string;+ project_id: string;+ }>({+ query,+ params: {+ traceIds,},});++ return records.map((record) => ({+ id: record.id,+ projectId: record.project_id,+ }));};export async function getAgentGraphData(params: {@@ -2049,7 +1894,7 @@ export const generateTracesForPublicApi = async ({const includeObservations = requestedFields.includes("observations");const includeMetrics = requestedFields.includes("metrics");- const { query, params, fromTimeFilter } = await buildTracesBaseQuery(+ const { query, params } = await buildTracesBaseQuery({ projectId, filter, pagination },{includeIO,@@ -2060,31 +1905,19 @@ export const generateTracesForPublicApi = async ({},orderBy,);- const result = await measureAndReturn({- operationName: "getTracesForPublicApi",- projectId,- input: {- params,- tags: { projectId },- fromTimestamp: fromTimeFilter?.value ?? undefined,- preferredClickhouseService: "ReadOnly",- },- fn: (input) => {- return queryClickhouse<- TraceRecordReadType & {- observations?: string[];- scores?: string[];- totalCost?: number;- latency?: number;- htmlPath: string;- }- >({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });- },+ const result = await queryClickhouse<+ TraceRecordReadType & {+ observations?: string[];+ scores?: string[];+ totalCost?: number;+ latency?: number;+ htmlPath: string;+ }+ >({+ query,+ params,+ tags: { projectId },+ preferredClickhouseService: "ReadOnly",});return convertClickhouseTracesListToDomain(result, {@@ -2105,13 +1938,6 @@ export const getTracesCountForPublicApi = async ({}) => {const appliedFilter = filter.apply();- const fromTimeFilter = filter.find(- (f) =>- f.clickhouseTable === "traces" &&- f.field.includes("timestamp") &&- (f.operator === ">=" || f.operator === ">"),- ) as DateTimeFilter | undefined;-const needsComplexQuery = filter.some((f) =>f.clickhouseTable === "observations" ||@@ -2147,24 +1973,11 @@ export const getTracesCountForPublicApi = async ({));}- const timestamp = fromTimeFilter?.value;-- return measureAndReturn({- operationName: "getTracesCountForPublicApi",- projectId,- input: {- params,- tags: { projectId },- timestamp,- },- fn: async (input) => {- const records = await queryClickhouse<{ count: string }>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- preferredClickhouseService: "ReadOnly",- });- return records.map((record) => Number(record.count)).shift();- },+ const records = await queryClickhouse<{ count: string }>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params,+ tags: { projectId },+ preferredClickhouseService: "ReadOnly",});+ return records.map((record) => Number(record.count)).shift();};diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.tsindex 207e5453ae..664beccea9 100644--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts@@ -3,7 +3,6 @@ import { InvalidRequestError } from "../../errors";import { OrderByState } from "../../interfaces/orderBy";import { FilterState } from "../../types";import { convertDateToClickhouseDateTime } from "../clickhouse/client";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import {CTEQueryBuilder,DateTimeFilter,@@ -75,32 +74,27 @@ export const getSessionTracesFromEvents = async (props: {${tracesCte.query}`;- const rows = await measureAndReturn({- operationName: "getSessionTracesFromEvents",- projectId: props.projectId,- input: {- params: {- ...tracesCte.params,- projectId: props.projectId,- sessionId: props.sessionId,- },- tags: { projectId: props.projectId },- },- fn: async (input) => {- return queryClickhouse<{- id: string;- name: string | null;- timestamp: string;- environment: string | null;- user_id: string | null;- observation_count: number | string;- }>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- });+ const input = {+ params: {+ ...tracesCte.params,+ projectId: props.projectId,+ sessionId: props.sessionId,},+ tags: { projectId: props.projectId },+ };++ const rows = await queryClickhouse<{+ id: string;+ name: string | null;+ timestamp: string;+ environment: string | null;+ user_id: string | null;+ observation_count: number | string;+ }>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "EventsReadOnly",});return rows.map((row) => ({@@ -342,24 +336,19 @@ const getSessionsTableFromEventsGeneric = async <T>(const { query, params } = queryBuilder.buildWithParams();- return measureAndReturn({- operationName: "getSessionsTableFromEventsGeneric",- projectId,- input: {- params: {- ...params,- projectId,- },- tags: { ...(props.tags ?? {}), projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query,- params: input.params,- tags: input.tags,- clickhouseConfigs,- preferredClickhouseService: "EventsReadOnly",- });+ const input = {+ params: {+ ...params,+ projectId,},+ tags: { ...(props.tags ?? {}), projectId },+ };++ return queryClickhouse<T>({+ query,+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,+ preferredClickhouseService: "EventsReadOnly",});};diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.tsindex 8232ff2c4c..77e050bec2 100644--- a/packages/shared/src/server/services/sessions-ui-table-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts@@ -6,7 +6,6 @@ import { sessionsViewCols } from "../../tableDefinitions/sessionsView";import { findUiColumnMapping } from "../../tableDefinitions";import { convertDateToClickhouseDateTime } from "../clickhouse/client";import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import { DateTimeFilter, FilterList, orderByToClickhouseSql } from "../queries";import {getProjectIdDefaultFilter,@@ -379,34 +378,29 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {${limit !== undefined && page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}`;- return measureAndReturn({- operationName: "getSessionsTableGeneric",- projectId,- input: {- params: {- projectId,- limit: limit,- offset: limit && page ? limit * page : 0,- ...tracesFilterRes.params,- ...singleTraceFilter?.params,- ...scoresFilterRes.params,- ...(traceTimestampFilter- ? {- observationsStartTime: convertDateToClickhouseDateTime(- traceTimestampFilter.value,- ),- }- : {}),- },- tags: { ...(props.tags ?? {}), projectId },- },- fn: async (input) => {- return queryClickhouse<T>({- query: query.replace("__TRACE_TABLE__", "traces"),- params: input.params,- tags: input.tags,- clickhouseConfigs,- });+ const input = {+ params: {+ projectId,+ limit: limit,+ offset: limit && page ? limit * page : 0,+ ...tracesFilterRes.params,+ ...singleTraceFilter?.params,+ ...scoresFilterRes.params,+ ...(traceTimestampFilter+ ? {+ observationsStartTime: convertDateToClickhouseDateTime(+ traceTimestampFilter.value,+ ),+ }+ : {}),},+ tags: { ...(props.tags ?? {}), projectId },+ };++ return queryClickhouse<T>({+ query: query.replace("__TRACE_TABLE__", "traces"),+ params: input.params,+ tags: input.tags,+ clickhouseConfigs,});};diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex bbf10d0f47..8de29e084d 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -25,7 +25,6 @@ import {queryClickhouse,reduceUsageOrCostDetails,} from "../repositories";-import { measureAndReturn } from "../clickhouse/measureAndReturn";import { TracingSearchType } from "../../interfaces/search";import { ObservationLevelType, TraceDomain } from "../../domain";import { ClickHouseClientConfigOptions } from "@clickhouse/client";@@ -355,185 +354,177 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {)`;- return measureAndReturn({- operationName: "getTracesTableGeneric",- projectId: props.projectId,- input: props,- fn: async (props) => {- let sqlSelect: string;- switch (select) {- case "count":- // Using uniqExact here as we need the correct count to handle pagination right- sqlSelect = "uniqExact(t.id) as count";- break;- case "metrics":- sqlSelect = `- t.id as id,- t.project_id as project_id,- t.timestamp as timestamp,- o.latency_milliseconds / 1000 as latency,- o.cost_details as cost_details,- o.usage_details as usage_details,- o.aggregated_level as level,- o.error_count as error_count,- o.warning_count as warning_count,- o.default_count as default_count,- o.debug_count as debug_count,- o.observation_count as observation_count,- s.scores_avg as scores_avg,- s.score_categories as score_categories,- t.public as public`;- break;- case "rows":- sqlSelect = `- t.id as id,- t.project_id as project_id,- t.timestamp as timestamp,- t.tags as tags,- t.bookmarked as bookmarked,- t.name as name,- t.release as release,- t.version as version,- t.user_id as user_id,- t.environment as environment,- t.session_id as session_id,- t.public as public`;- break;- case "identifiers":- sqlSelect = `- t.id as id,- t.project_id as projectId,- t.timestamp as timestamp`;- break;- default:- throw new Error(`Unknown select type: ${select}`);- }-- const search = clickhouseSearchCondition({- query: searchQuery,- searchType,- tablePrefix: "t",- });-- const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";- const orderByCols = [- ...tracesTableUiColumnDefinitions,- {- clickhouseSelect: "toDate(t.timestamp)",- uiTableName: "timestamp_to_date",- uiTableId: "timestamp_to_date",- clickhouseTableName: "traces",- },- {- clickhouseSelect: "t.event_ts",- uiTableName: "event_ts",- uiTableId: "event_ts",- clickhouseTableName: "traces",- },- ];- const chOrderBy = orderByToClickhouseSql(- [- defaultOrder- ? [- {- column: "timestamp_to_date",- order: orderBy.order,- },- { column: "timestamp", order: orderBy.order },- { column: "event_ts", order: "DESC" as "DESC" },- ]- : null,- orderBy ?? null,- ].flat(),- orderByCols,- );- const canonicalTraceDeleteOrder =- select === "identifiers" && traceDeleteCursorOrder;- const usesNonFinalTraceReadPath =- defaultOrder || canonicalTraceDeleteOrder;- const effectiveOrderBy = canonicalTraceDeleteOrder- ? "ORDER BY t.timestamp DESC, t.id DESC, t.event_ts DESC"- : chOrderBy;- const cursorClause =- canonicalTraceDeleteOrder && traceDeleteCursor- ? `- -- Cursor follows ORDER BY (timestamp DESC, id DESC). Older timestamps- -- must pass regardless of how their ids compare to the cursor id.- AND (- t.timestamp < {cursorTimestamp: DateTime64(3)}- OR (- t.timestamp = {cursorTimestamp: DateTime64(3)}- AND t.id < {cursorTraceId: String}- )- )`- : "";- const limitByClause =- ["metrics", "rows", "identifiers"].includes(select) &&- usesNonFinalTraceReadPath- ? "LIMIT 1 BY id, project_id"- : "";- const limitClause =- limit !== undefined && traceDeleteCursorOrder- ? "LIMIT {limit: Int32}"- : limit !== undefined && page !== undefined- ? "LIMIT {limit: Int32} OFFSET {offset: Int32}"- : "";-- // complex query ahead:- // - we only join scores and observations if we really need them to speed up default views- // - we use FINAL on traces only in case we not need to order by something different than time. Otherwise we cannot guarantee correct reads.- // - we filter the observations and scores as much as possible before joining them to traces.- // - we order by todate(timestamp), event_ts desc per default and do not use FINAL.- // In this case, CH is able to read the data only from the latest date from disk and filtering them in memory. No need to read all data e.g. for 1 month from disk.-- const query = `- ${observationsAndScoresCTE}-- SELECT ${sqlSelect}- -- FINAL is used for non default ordering.- FROM traces t ${usesNonFinalTraceReadPath || select === "count" ? "" : "FINAL"}- ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}- ${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}- WHERE t.project_id = {projectId: String}- ${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}- ${cursorClause}- ${search.query}- ${effectiveOrderBy}- -- This is used for metrics and row queries. Count has only one result.- -- This is only used for default ordering. Otherwise, we use final.- ${limitByClause}- ${limitClause}- `;-- const res = await queryClickhouse<- SelectReturnTypeMap[keyof SelectReturnTypeMap]- >({- query: query,- params: {- limit: limit,- offset: limit && page ? limit * page : 0,- traceTimestamp: timeStampFilter?.value.getTime(),- ...(traceDeleteCursor- ? {- cursorTimestamp: convertDateToClickhouseDateTime(- new Date(traceDeleteCursor.timestamp),- ),- cursorTraceId: traceDeleteCursor.traceId,- }- : {}),- projectId: projectId,- ...tracesFilterRes.params,- ...observationFilterRes.params,- ...scoresFilterRes.params,- ...search.params,- },- tags: { ...(props.tags ?? {}), projectId },- clickhouseConfigs,- });-- return res;+ let sqlSelect: string;+ switch (select) {+ case "count":+ // Using uniqExact here as we need the correct count to handle pagination right+ sqlSelect = "uniqExact(t.id) as count";+ break;+ case "metrics":+ sqlSelect = `+ t.id as id,+ t.project_id as project_id,+ t.timestamp as timestamp,+ o.latency_milliseconds / 1000 as latency,+ o.cost_details as cost_details,+ o.usage_details as usage_details,+ o.aggregated_level as level,+ o.error_count as error_count,+ o.warning_count as warning_count,+ o.default_count as default_count,+ o.debug_count as debug_count,+ o.observation_count as observation_count,+ s.scores_avg as scores_avg,+ s.score_categories as score_categories,+ t.public as public`;+ break;+ case "rows":+ sqlSelect = `+ t.id as id,+ t.project_id as project_id,+ t.timestamp as timestamp,+ t.tags as tags,+ t.bookmarked as bookmarked,+ t.name as name,+ t.release as release,+ t.version as version,+ t.user_id as user_id,+ t.environment as environment,+ t.session_id as session_id,+ t.public as public`;+ break;+ case "identifiers":+ sqlSelect = `+ t.id as id,+ t.project_id as projectId,+ t.timestamp as timestamp`;+ break;+ default:+ throw new Error(`Unknown select type: ${select}`);+ }++ const search = clickhouseSearchCondition({+ query: searchQuery,+ searchType,+ tablePrefix: "t",+ });++ const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";+ const orderByCols = [+ ...tracesTableUiColumnDefinitions,+ {+ clickhouseSelect: "toDate(t.timestamp)",+ uiTableName: "timestamp_to_date",+ uiTableId: "timestamp_to_date",+ clickhouseTableName: "traces",+ },+ {+ clickhouseSelect: "t.event_ts",+ uiTableName: "event_ts",+ uiTableId: "event_ts",+ clickhouseTableName: "traces",+ },+ ];+ const chOrderBy = orderByToClickhouseSql(+ [+ defaultOrder+ ? [+ {+ column: "timestamp_to_date",+ order: orderBy.order,+ },+ { column: "timestamp", order: orderBy.order },+ { column: "event_ts", order: "DESC" as "DESC" },+ ]+ : null,+ orderBy ?? null,+ ].flat(),+ orderByCols,+ );+ const canonicalTraceDeleteOrder =+ select === "identifiers" && traceDeleteCursorOrder;+ const usesNonFinalTraceReadPath = defaultOrder || canonicalTraceDeleteOrder;+ const effectiveOrderBy = canonicalTraceDeleteOrder+ ? "ORDER BY t.timestamp DESC, t.id DESC, t.event_ts DESC"+ : chOrderBy;+ const cursorClause =+ canonicalTraceDeleteOrder && traceDeleteCursor+ ? `+ -- Cursor follows ORDER BY (timestamp DESC, id DESC). Older timestamps+ -- must pass regardless of how their ids compare to the cursor id.+ AND (+ t.timestamp < {cursorTimestamp: DateTime64(3)}+ OR (+ t.timestamp = {cursorTimestamp: DateTime64(3)}+ AND t.id < {cursorTraceId: String}+ )+ )`+ : "";+ const limitByClause =+ ["metrics", "rows", "identifiers"].includes(select) &&+ usesNonFinalTraceReadPath+ ? "LIMIT 1 BY id, project_id"+ : "";+ const limitClause =+ limit !== undefined && traceDeleteCursorOrder+ ? "LIMIT {limit: Int32}"+ : limit !== undefined && page !== undefined+ ? "LIMIT {limit: Int32} OFFSET {offset: Int32}"+ : "";++ // complex query ahead:+ // - we only join scores and observations if we really need them to speed up default views+ // - we use FINAL on traces only in case we not need to order by something different than time. Otherwise we cannot guarantee correct reads.+ // - we filter the observations and scores as much as possible before joining them to traces.+ // - we order by todate(timestamp), event_ts desc per default and do not use FINAL.+ // In this case, CH is able to read the data only from the latest date from disk and filtering them in memory. No need to read all data e.g. for 1 month from disk.++ const query = `+ ${observationsAndScoresCTE}++ SELECT ${sqlSelect}+ -- FINAL is used for non default ordering.+ FROM traces t ${usesNonFinalTraceReadPath || select === "count" ? "" : "FINAL"}+ ${select === "metrics" || requiresObservationsJoin ? `LEFT JOIN observations_stats o on o.project_id = t.project_id and o.trace_id = t.id` : ""}+ ${select === "metrics" || requiresScoresJoin ? `LEFT JOIN scores_avg s on s.project_id = t.project_id and s.trace_id = t.id` : ""}+ WHERE t.project_id = {projectId: String}+ ${tracesFilterRes ? `AND ${tracesFilterRes.query}` : ""}+ ${cursorClause}+ ${search.query}+ ${effectiveOrderBy}+ -- This is used for metrics and row queries. Count has only one result.+ -- This is only used for default ordering. Otherwise, we use final.+ ${limitByClause}+ ${limitClause}+ `;++ const res = await queryClickhouse<+ SelectReturnTypeMap[keyof SelectReturnTypeMap]+ >({+ query: query,+ params: {+ limit: limit,+ offset: limit && page ? limit * page : 0,+ traceTimestamp: timeStampFilter?.value.getTime(),+ ...(traceDeleteCursor+ ? {+ cursorTimestamp: convertDateToClickhouseDateTime(+ new Date(traceDeleteCursor.timestamp),+ ),+ cursorTraceId: traceDeleteCursor.traceId,+ }+ : {}),+ projectId: projectId,+ ...tracesFilterRes.params,+ ...observationFilterRes.params,+ ...scoresFilterRes.params,+ ...search.params,},+ tags: { ...(props.tags ?? {}), projectId },+ clickhouseConfigs,});++ return res;}export const getTracesTableCount = async (props: {diff --git a/web/src/features/experiments/server/public/repository.ts b/web/src/features/experiments/server/public/repository.tsindex 910460ecc8..ddbe7a34ed 100644--- a/web/src/features/experiments/server/public/repository.ts+++ b/web/src/features/experiments/server/public/repository.ts@@ -5,7 +5,6 @@ import {FilterList,ExperimentsAggregationQueryBuilder,buildEventsFullTableSplitQuery,- measureAndReturn,parseClickhouseUTCDateTimeFormat,publicApiExperimentItemColumnDefinitions,publicApiExperimentItemColumnMappings,@@ -319,26 +318,22 @@ async function queryExperimentSummaryRowsForPublicApi(const { query, params: queryParams } = aggregationBuilder.buildWithParams();- const rows = await measureAndReturn({- operationName: "queryExperimentSummaryRowsForPublicApi",- projectId: params.projectId,- input: {- params: queryParams,- tags: {- feature: "experiments",- type: "events",- kind: "publicApi",- projectId: params.projectId,- operation_name: "queryExperimentSummaryRowsForPublicApi",- },+ const input = {+ params: queryParams,+ tags: {+ feature: "experiments",+ type: "events",+ kind: "publicApi",+ projectId: params.projectId,+ operation_name: "queryExperimentSummaryRowsForPublicApi",},- fn: async (input) =>- await queryClickhouse<ExperimentSummaryRow>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- }),+ };++ const rows = await queryClickhouse<ExperimentSummaryRow>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "EventsReadOnly",});return rows;@@ -444,26 +439,22 @@ async function queryExperimentItemRowsForPublicApi(const { query, params: queryParams } = builder.buildWithParams();- const rows = await measureAndReturn({- operationName: "queryExperimentItemRowsForPublicApi",- projectId: params.projectId,- input: {- params: queryParams,- tags: {- feature: "experiments",- type: "events",- kind: "publicApi",- projectId: params.projectId,- operation_name: "queryExperimentItemRowsForPublicApi",- },+ const input = {+ params: queryParams,+ tags: {+ feature: "experiments",+ type: "events",+ kind: "publicApi",+ projectId: params.projectId,+ operation_name: "queryExperimentItemRowsForPublicApi",},- fn: async (input) =>- await queryClickhouse<ExperimentItemRow>({- query,- params: input.params,- tags: input.tags,- preferredClickhouseService: "EventsReadOnly",- }),+ };++ const rows = await queryClickhouse<ExperimentItemRow>({+ query,+ params: input.params,+ tags: input.tags,+ preferredClickhouseService: "EventsReadOnly",});return rows;diff --git a/web/src/features/public-api/server/health-service.ts b/web/src/features/public-api/server/health-service.tsindex 31f9ec0a7b..81254a2878 100644--- a/web/src/features/public-api/server/health-service.ts+++ b/web/src/features/public-api/server/health-service.ts@@ -4,7 +4,6 @@ import { prisma } from "@langfuse/shared/src/db";import {convertDateToClickhouseDateTime,logger,- measureAndReturn,queryClickhouse,traceException,} from "@langfuse/shared/src/server";@@ -51,23 +50,17 @@ export const runHealthCheck = async ({// longer written, so they would always look stale. Ingestion// completeness is instead reflected by recent rows in events_core// (the query-optimized projection of events_full).- const events = await measureAndReturn({- operationName: "healthCheckEvents",- projectId: "__CROSS_PROJECT__",- input: {+ const events = await queryClickhouse<{ span_id: string }>({+ query: `+ SELECT span_id+ FROM events_core+ WHERE start_time <= {now: DateTime64(3)}+ AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE+ LIMIT 1+ `,+ params: {now: clickhouseNow,},- fn: async (params: { now: string }) =>- queryClickhouse<{ span_id: string }>({- query: `- SELECT span_id- FROM events_core- WHERE start_time <= {now: DateTime64(3)}- AND start_time >= {now: DateTime64(3)} - INTERVAL 3 MINUTE- LIMIT 1- `,- params,- }),});if (events.length === 0) {@@ -78,23 +71,17 @@ export const runHealthCheck = async ({};}} else {- const traces = await measureAndReturn({- operationName: "healthCheckTraces",- projectId: "__CROSS_PROJECT__",- input: {+ const traces = await queryClickhouse<{ id: string }>({+ query: `+ SELECT id+ FROM traces+ WHERE timestamp <= {now: DateTime64(3)}+ AND timestamp >= {now: DateTime64(3)} - INTERVAL 3 MINUTE+ LIMIT 1+ `,+ params: {now: clickhouseNow,},- fn: async (params: { now: string }) =>- queryClickhouse<{ id: string }>({- query: `- SELECT id- FROM traces- WHERE timestamp <= {now: DateTime64(3)}- AND timestamp >= {now: DateTime64(3)} - INTERVAL 3 MINUTE- LIMIT 1- `,- params,- }),});const observations = await queryClickhouse<{ id: string }>({