Skip to content

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

chore: migrate additional queries to traces amts (#8249)

Steffen Schmitz90247ab64cdb
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 568d55844c..e7c1807850 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -23,7 +23,8 @@ import {
observationsTableUiColumnDefinitions,
} from "../../tableDefinitions";
import { OrderByState } from "../../interfaces/orderBy";
-import { getTracesByIds } from "./traces";
+import { getTimeframesTracesAMT, getTracesByIds } from "./traces";
+import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
import { convertObservation } from "./observations_converters";
import { clickhouseSearchCondition } from "../queries/clickhouse-sql/search";
@@ -612,12 +613,14 @@ const getObservationsTableInternal = async <T>(
} = opts;
const selectString = selectIOAndMetadata
- ? `
- ${select},
- ${selectIOAndMetadata ? `o.input, o.output, o.metadata` : ""}
- `
+ ? `${select}, o.input, o.output, o.metadata`
: select;
+ const timeFilter = filter.find(
+ (f) =>
+ f.column === "Start Time" && (f.operator === ">=" || f.operator === ">"),
+ );
+
const scoresFilter = new FilterList([
new StringFilter({
clickhouseTable: "scores",
@@ -627,33 +630,22 @@ const getObservationsTableInternal = async <T>(
}),
]);
- const timeFilter = opts.filter.find(
- (f) =>
- f.column === "Start Time" && (f.operator === ">=" || f.operator === ">"),
+ const hasScoresFilter = filter.some((f) =>
+ f.column.toLowerCase().includes("scores"),
);
// query optimisation: joining traces onto observations is expensive. Hence, only join if the UI table contains filters on traces.
- const traceTableFilter = opts.filter.filter(
- (f) =>
- observationsTableTraceUiColumnDefinitions
- .map((c) => c.uiTableId)
- .includes(f.column) ||
- observationsTableTraceUiColumnDefinitions
- .map((c) => c.uiTableName)
- .includes(f.column),
- );
-
- const hasScoresFilter = filter.some((f) =>
- f.column.toLowerCase().includes("scores"),
+ const traceTableFilter = filter.filter((f) =>
+ observationsTableTraceUiColumnDefinitions.some(
+ (c) => c.uiTableId === f.column || c.uiTableName === f.column,
+ ),
);
- const orderByTraces = opts.orderBy
- ? observationsTableTraceUiColumnDefinitions
- .map((c) => c.uiTableId)
- .includes(opts.orderBy.column) ||
- observationsTableTraceUiColumnDefinitions
- .map((c) => c.uiTableName)
- .includes(opts.orderBy.column)
+ const orderByTraces = orderBy
+ ? observationsTableTraceUiColumnDefinitions.some(
+ (c) =>
+ c.uiTableId === orderBy.column || c.uiTableName === orderBy.column,
+ )
: undefined;
timeFilter
@@ -759,7 +751,7 @@ const getObservationsTableInternal = async <T>(
SELECT
${selectString}
FROM observations o
- ${traceTableFilter.length > 0 || orderByTraces || search.query ? "LEFT JOIN traces t FINAL ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${traceTableFilter.length > 0 || orderByTraces || search.query ? "LEFT JOIN __TRACE_TABLE__ t FINAL ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
${hasScoresFilter ? `LEFT JOIN scores_agg AS s ON s.trace_id = o.trace_id and s.observation_id = o.id` : ""}
WHERE ${appliedObservationsFilter.query}
@@ -769,30 +761,50 @@ const getObservationsTableInternal = async <T>(
${opts.select === "rows" ? "LIMIT 1 BY o.id, o.project_id" : ""}
${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : ""};`;
- const res = await queryClickhouse<T>({
- query,
- params: {
- ...appliedScoresFilter.params,
- ...appliedObservationsFilter.params,
- ...(timeFilter
- ? {
- tracesTimestampFilter: convertDateToClickhouseDateTime(
- timeFilter.value as Date,
- ),
- }
- : {}),
- ...search.params,
+ return measureAndReturn({
+ operationName: "getObservationsTableInternal",
+ projectId,
+ input: {
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedObservationsFilter.params,
+ ...(timeFilter
+ ? {
+ tracesTimestampFilter: convertDateToClickhouseDateTime(
+ timeFilter.value as Date,
+ ),
+ }
+ : {}),
+ ...search.params,
+ },
+ tags: {
+ ...(opts.tags ?? {}),
+ feature: "tracing",
+ type: "observation",
+ projectId,
+ kind: opts.select,
+ },
},
- tags: {
- ...(opts.tags ?? {}),
- feature: "tracing",
- type: "observation",
- projectId,
+ existingExecution: async (input) => {
+ return queryClickhouse<T>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs,
+ });
+ },
+ newExecution: async (input) => {
+ const traceAmt = getTimeframesTracesAMT(
+ (timeFilter?.value as Date) || undefined,
+ );
+ return queryClickhouse<T>({
+ query: query.replace("__TRACE_TABLE__", traceAmt),
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs,
+ });
},
- clickhouseConfigs,
});
-
- return res;
};
export const getObservationsGroupedByModel = async (
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index d621bbfea8..9a7aa06046 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -32,6 +32,7 @@ import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
import { prisma } from "../../db";
+import { measureAndReturn } from "../clickhouse/measureAndReturn";
export const searchExistingAnnotationScore = async (
projectId: string,
@@ -942,31 +943,48 @@ const getScoresUiGeneric = async <T>(props: {
SELECT
${select}
FROM scores s final
- ${performTracesJoin ? "LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
+ ${performTracesJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
WHERE s.project_id = {projectId: String}
${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitions)}
${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
`;
- const rows = await queryClickhouse<T>({
- query: query,
- params: {
- projectId: projectId,
- ...(scoresFilterRes ? scoresFilterRes.params : {}),
- limit: limit,
- offset: offset,
+ return measureAndReturn({
+ operationName: "getScoresUiGeneric",
+ projectId,
+ input: {
+ params: {
+ projectId: projectId,
+ ...(scoresFilterRes ? scoresFilterRes.params : {}),
+ limit: limit,
+ offset: offset,
+ },
+ tags: {
+ ...(props.tags ?? {}),
+ feature: "tracing",
+ type: "score",
+ projectId,
+ select: props.select,
+ },
},
- tags: {
- ...(props.tags ?? {}),
- feature: "tracing",
- type: "score",
- projectId,
+ existingExecution: async (input) => {
+ return queryClickhouse<T>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs,
+ });
+ },
+ newExecution: async (input) => {
+ return queryClickhouse<T>({
+ query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
+ params: input.params,
+ tags: input.tags,
+ clickhouseConfigs,
+ });
},
- clickhouseConfigs,
});
-
- return rows;
};
export const getScoreNames = async (
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index 30d7179102..e81ebf4097 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -4,6 +4,7 @@ import {
type ObservationRecordReadType,
queryClickhouse,
convertObservation,
+ measureAndReturn,
} from "@langfuse/shared/src/server";
type QueryType = {
@@ -31,64 +32,87 @@ export const generateObservationsForPublicApi = async (props: QueryType) => {
id,
project_id,
type,
- toDate(start_time),
+ toDate(start_time)
FROM observations o
- ${traceFilter ? `LEFT JOIN traces t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
+ ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
WHERE o.project_id = {projectId: String}
- ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
- AND ${appliedFilter.query}
+ ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
+ AND ${appliedFilter.query}
ORDER BY start_time DESC
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
)
- SELECT
- id,
- trace_id,
- project_id,
- type,
- parent_observation_id,
- environment,
- start_time,
- end_time,
- name,
- metadata,
- level,
- status_message,
- version,
- input,
- output,
- provided_model_name,
- internal_model_id,
- model_parameters,
- provided_usage_details,
- usage_details,
- provided_cost_details,
- cost_details,
- total_cost,
- completion_start_time,
- prompt_id,
- prompt_name,
- prompt_version,
- created_at,
- updated_at,
- event_ts
- FROM observations o FINAL
- WHERE o.project_id = {projectId: String}
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ type,
+ parent_observation_id,
+ environment,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ input,
+ output,
+ provided_model_name,
+ internal_model_id,
+ model_parameters,
+ provided_usage_details,
+ usage_details,
+ provided_cost_details,
+ cost_details,
+ total_cost,
+ completion_start_time,
+ prompt_id,
+ prompt_name,
+ prompt_version,
+ created_at,
+ updated_at,
+ event_ts
+ FROM observations o FINAL
+ WHERE o.project_id = {projectId: String}
AND (id, project_id, type, toDate(start_time)) in (select * from clickhouse_keys)
- ORDER BY start_time DESC
- `;
+ ORDER BY start_time DESC
+ `;
- const result = await queryClickhouse<ObservationRecordReadType>({
- query,
- params: {
- ...appliedFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
+ return measureAndReturn({
+ operationName: "generateObservationsForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ projectId: props.projectId,
+ },
+ },
+ existingExecution: async (input) => {
+ const result = await queryClickhouse<ObservationRecordReadType>({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ });
+ return result.map(convertObservation);
+ },
+ newExecution: async (input) => {
+ const result = await queryClickhouse<ObservationRecordReadType>({
+ query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
+ params: input.params,
+ tags: input.tags,
+ });
+ return result.map(convertObservation);
},
});
- return result.map(convertObservation);
};
export const getObservationsCountForPublicApi = async (props: QueryType) => {
@@ -99,17 +123,40 @@ export const getObservationsCountForPublicApi = async (props: QueryType) => {
const query = `
SELECT count() as count
FROM observations o
- ${traceFilter ? `LEFT JOIN traces t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
+ ${traceFilter ? `LEFT JOIN __TRACE_TABLE__ t ON o.trace_id = t.id AND t.project_id = o.project_id` : ""}
WHERE o.project_id = {projectId: String}
${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
AND ${filter.query}
`;
- const records = await queryClickhouse<{ count: string }>({
- query,
- params: { ...filter.params, projectId: props.projectId },
+ return measureAndReturn({
+ operationName: "getObservationsCountForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: { ...filter.params, projectId: props.projectId },
+ tags: {
+ feature: "tracing",
+ type: "observation",
+ projectId: props.projectId,
+ },
+ },
+ existingExecution: async (input) => {
+ 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();
+ },
+ newExecution: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
+ params: input.params,
+ tags: input.tags,
+ });
+ return records.map((record) => Number(record.count)).shift();
+ },
});
- return records.map((record) => Number(record.count)).shift();
};
const filterParams = [
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index eebc76068e..b754f5b5dc 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -1,7 +1,11 @@
import { convertApiProvidedFilterToClickhouseFilter } from "@/src/features/public-api/server/filter-builder";
-import { convertToScore, StringFilter } from "@langfuse/shared/src/server";
-import { type ScoreRecordReadType } from "@langfuse/shared/src/server";
-import { queryClickhouse } from "@langfuse/shared/src/server";
+import {
+ convertToScore,
+ StringFilter,
+ type ScoreRecordReadType,
+ queryClickhouse,
+ measureAndReturn,
+} from "@langfuse/shared/src/server";
export type ScoreQueryType = {
page: number;
@@ -66,7 +70,7 @@ export const _handleGenerateScoresForPublicApi = async ({
s.dataset_run_id as dataset_run_id
FROM
scores s
- LEFT JOIN traces t ON s.trace_id = t.id
+ LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id
AND s.project_id = t.project_id
WHERE
s.project_id = {projectId: String}
@@ -98,36 +102,77 @@ export const _handleGenerateScoresForPublicApi = async ({
${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
`;
- const records = await queryClickhouse<
- ScoreRecordReadType & {
- tags: string[];
- user_id: string;
- trace_environment: string;
- }
- >({
- query,
- params: {
- ...appliedScoresFilter.params,
- ...appliedTracesFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
+ return measureAndReturn({
+ operationName: "_handleGenerateScoresForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedTracesFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: props.projectId,
+ scoreScope,
+ },
},
- });
+ existingExecution: async (input) => {
+ const records = await queryClickhouse<
+ ScoreRecordReadType & {
+ tags: string[];
+ user_id: string;
+ trace_environment: string;
+ }
+ >({
+ query: query.replace("__TRACE_TABLE__", "traces"),
+ params: input.params,
+ tags: input.tags,
+ });
+
+ return records.map((record) => ({
+ ...convertToScore(record),
+ trace:
+ record.trace_id !== null
+ ? {
+ userId: record.user_id,
+ tags: record.tags,
+ environment: record.trace_environment,
+ }
+ : null,
+ }));
+ },
+ newExecution: async (input) => {
+ const records = await queryClickhouse<
+ ScoreRecordReadType & {
+ tags: string[];
+ user_id: string;
+ trace_environment: string;
+ }
+ >({
+ query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
+ params: input.params,
+ tags: input.tags,
+ });
- return records.map((record) => ({
- ...convertToScore(record),
- trace:
- record.trace_id !== null
- ? {
- userId: record.user_id,
- tags: record.tags,
- environment: record.trace_environment,
- }
- : null,
- }));
+ return records.map((record) => ({
+ ...convertToScore(record),
+ trace:
+ record.trace_id !== null
+ ? {
+ userId: record.user_id,
+ tags: record.tags,
+ environment: record.trace_environment,
+ }
+ : null,
+ }));
+ },
+ });
};
/**
@@ -152,7 +197,7 @@ export const _handleGetScoresCountForPublicApi = async ({
count() as count
FROM
scores s
- LEFT JOIN traces t ON s.trace_id = t.id
+ LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id
AND s.project_id = t.project_id
WHERE
s.project_id = {projectId: String}
@@ -178,15 +223,39 @@ export const _handleGetScoresCountForPublicApi = async ({
${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
`;
- const records = await queryClickhouse<{ count: string }>({
- query,
- params: {
- ...appliedScoresFilter.params,
- ...appliedTracesFilter.params,
- projectId: props.projectId,
+ return measureAndReturn({
+ operationName: "_handleGetScoresCountForPublicApi",
+ projectId: props.projectId,
+ input: {
+ params: {
+ ...appliedScoresFilter.params,
+ ...appliedTracesFilter.params,
+ projectId: props.projectId,
+ },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: props.projectId,
+ scoreScope,
+ },
+ },
+ existingExecution: async (input) => {
+ 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();
+ },
+ newExecution: async (input) => {
+ const records = await queryClickhouse<{ count: string }>({
+ query: query.replace("__TRACE_TABLE__", "traces_all_amt"),
+ params: input.params,
+ tags: input.tags,
+ });
+ return records.map((record) => Number(record.count)).shift();
},
});
- return records.map((record) => Number(record.count)).shift();
};
const secureScoreFilterOptions = [
diff --git a/worker/src/services/IngestionService/README.md b/worker/src/services/IngestionService/README.md
index fae06dabe8..a77162caf9 100644
--- a/worker/src/services/IngestionService/README.md
+++ b/worker/src/services/IngestionService/README.md
@@ -494,6 +494,16 @@ This checklist documents all references and invocations to the `traces` table gr
### 4. Aggregation and Analytics Queries
+- [ ] **getTracesCountForPublicApi()** - `web/src/features/public-api/server/traces.ts:299`
+- [ ] **generateDailyMetrics()** - `web/src/features/public-api/server/dailyMetrics.ts:93`
+- [ ] **getDailyMetricsCount()** - `web/src/features/public-api/server/dailyMetrics.ts:153`
+- [x] **generateObservationsForPublicApi()** - `web/src/features/public-api/server/observations.ts:80`
+- [x] **getObservationsCountForPublicApi()** - `web/src/features/public-api/server/observations.ts:108`
+- [x] **getObservationsTableInternal()** - `packages/shared/src/server/repositories/observations.ts:565`
+- [x] **_handleGenerateScoresForPublicApi()** - `web/src/features/public-api/server/scores.ts:101`
+- [x] **_handleGetScoresCountForPublicApi()** - `web/src/features/public-api/server/scores.ts:181`
+- [x] **getScoresUiGeneric()** - `packages/shared/src/server/repositories/scores.ts:825`
+- [ ] **getNumericScoreHistogram()** - `packages/shared/src/server/repositories/scores.ts:1074`
- [x] **getTracesGroupedByName()** - `packages/shared/src/server/repositories/traces.ts:489-535`
- [x] **getTracesGroupedByUsers()** - `packages/shared/src/server/repositories/traces.ts:537-597`
- [x] **getTracesGroupedByTags()** - `packages/shared/src/server/repositories/traces.ts:605-640`
@@ -510,6 +520,8 @@ We need to cover these queries manually and cannot run a comparison.
We could use an opt-in on a projectId basis.
- [ ] **getTracesForPostHog()** - `packages/shared/src/server/repositories/traces.ts:1026-1113`
+- [ ] **getScoresForPostHog()** - `packages/shared/src/server/repositories/scores.ts:1328`
+- [ ] **getGenerationsForPosthog()** - `packages/shared/src/server/repositories/observations.ts:1481`
- [ ] **getTracesForBlobStorageExport()** - `packages/shared/src/server/repositories/traces.ts:980-1024`
### 6. Count and Statistics Queries
@@ -520,3 +532,7 @@ We could use an opt-in on a projectId basis.
### 7. Cross-Project Queries
- [x] **getTracesByIdsForAnyProject()** - `packages/shared/src/server/repositories/traces.ts:1115-1141`
+
+### 8. Writes
+
+- [ ] **upsertTrace()** - `packages/shared/src/server/repositories/traces.ts:224`