Skip to content

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

chore: add clickhouse tags to queries (#5535)

Steffen Schmitz95d67d65d7db
diff --git a/packages/shared/clickhouse/scripts/seed.ts b/packages/shared/clickhouse/scripts/seed.ts
index e850269571..497a945744 100644
--- a/packages/shared/clickhouse/scripts/seed.ts
+++ b/packages/shared/clickhouse/scripts/seed.ts
@@ -1,7 +1,4 @@
-import {
- clickhouseClient,
- ObservationRecordReadType,
-} from "@langfuse/shared/src/server";
+import { ObservationRecordReadType } from "@langfuse/shared/src/server";
import { prisma } from "../../src/db";
import { redis } from "@langfuse/shared/src/server";
import { prepareClickhouse } from "../../scripts/prepareClickhouse";
@@ -65,7 +62,6 @@ async function main() {
} catch (error) {
console.error("Error during Clickhouse preparation:", error);
} finally {
- await clickhouseClient().close();
await prisma.$disconnect();
redis?.disconnect();
console.log("Disconnected from Clickhouse.");
diff --git a/packages/shared/package.json b/packages/shared/package.json
index d2314f42cc..8fdc1b1a20 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -33,7 +33,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
- "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 110",
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 107",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev",
"db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push",
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index 1202bcb370..d30eab424e 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -97,7 +97,7 @@ async function main() {
},
});
- const orgMembership = await prisma.organizationMembership.upsert({
+ await prisma.organizationMembership.upsert({
where: {
orgId_userId: {
userId: user.id,
@@ -127,7 +127,7 @@ async function main() {
update: {},
});
- const projectMembership = await prisma.projectMembership.upsert({
+ await prisma.projectMembership.upsert({
where: {
projectId_userId: {
projectId: project1.id,
diff --git a/packages/shared/scripts/load-seed.ts b/packages/shared/scripts/load-seed.ts
index 4082b6daab..912dc1f44d 100644
--- a/packages/shared/scripts/load-seed.ts
+++ b/packages/shared/scripts/load-seed.ts
@@ -1,11 +1,6 @@
import { randomUUID } from "crypto";
import { prisma } from "../src/db";
-import {
- clickhouseClient,
- getDisplaySecretKey,
- hashSecretKey,
- logger,
-} from "../src/server";
+import { getDisplaySecretKey, hashSecretKey, logger } from "../src/server";
import { prepareClickhouse } from "./prepareClickhouse";
import { redis } from "../src/server";
@@ -124,7 +119,6 @@ async function main() {
} catch (error) {
logger.error("Error during Clickhouse preparation:", error);
} finally {
- await clickhouseClient().close();
await prisma.$disconnect();
redis?.disconnect();
logger.info("Disconnected from Clickhouse.");
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 4fc0c030bb..095be9e771 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -106,9 +106,4 @@ export const OutputSchema = z.object({
score: z.string(),
});
-export enum EvalTargetObject {
- Trace = "trace",
- Dataset = "dataset",
-}
-
export const DEFAULT_TRACE_JOB_DELAY = 10_000;
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index b39d682f6a..3628150649 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -6,20 +6,32 @@ import { propagation, context } from "@opentelemetry/api";
export type ClickhouseClientType = ReturnType<typeof createClient>;
-export const clickhouseClient = (opts?: NodeClickHouseClientConfigOptions) => {
- const headers = opts?.http_headers ?? {};
+export const clickhouseClient = (
+ params: {
+ tags?: string[];
+ opts?: NodeClickHouseClientConfigOptions;
+ } = {},
+) => {
+ const headers = params.opts?.http_headers ?? {};
const activeSpan = getCurrentSpan();
if (activeSpan) {
propagation.inject(context.active(), headers);
}
+
+ let log_comment: string | null = null;
+ if (params.tags && params.tags.length) {
+ log_comment = params.tags.join(",");
+ }
+
return createClient({
- ...opts,
+ ...params.opts,
url: env.CLICKHOUSE_URL,
username: env.CLICKHOUSE_USER,
password: env.CLICKHOUSE_PASSWORD,
database: env.CLICKHOUSE_DB,
http_headers: headers,
clickhouse_settings: {
+ ...(log_comment ? { log_comment } : {}),
async_insert: 1,
wait_for_async_insert: 1, // if disabled, we won't get errors from clickhouse
},
diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.ts
index ecf540639e..689dbdb6f8 100644
--- a/packages/shared/src/server/repositories/clickhouse.ts
+++ b/packages/shared/src/server/repositories/clickhouse.ts
@@ -36,6 +36,7 @@ export async function upsertClickhouse<
table: "scores" | "traces" | "observations";
records: T[];
eventBodyMapper: (body: T) => Record<string, unknown>;
+ tags?: string[];
}): Promise<void> {
return await instrumentAsync({ name: "clickhouse-upsert" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
@@ -56,7 +57,9 @@ export async function upsertClickhouse<
// Write new file directly to ClickHouse. We don't use the ClickHouse writer here as we expect more limited traffic
// and are not worried that much about latency.
- await clickhouseClient().insert({
+ await clickhouseClient({
+ tags: opts.tags,
+ }).insert({
table: "event_log",
values: [
{
@@ -85,7 +88,7 @@ export async function upsertClickhouse<
}),
);
- const res = await clickhouseClient().insert({
+ const res = await clickhouseClient({ tags: opts.tags }).insert({
table: opts.table,
values: opts.records.map((record) => ({
...record,
@@ -124,6 +127,7 @@ export async function* queryClickhouseStream<T>(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
+ tags?: string[];
}): AsyncGenerator<T> {
const tracer = getTracer("clickhouse-query-stream");
const span = tracer.startSpan("clickhouse-query-stream");
@@ -135,7 +139,10 @@ export async function* queryClickhouseStream<T>(opts: {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient(opts.clickhouseConfigs).query({
+ const res = await clickhouseClient({
+ tags: opts.tags,
+ opts: opts.clickhouseConfigs,
+ }).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
@@ -182,12 +189,16 @@ export async function queryClickhouse<T>(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
+ tags?: string[];
}): Promise<T[]> {
return await instrumentAsync({ name: "clickhouse-query" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient(opts.clickhouseConfigs).query({
+ const res = await clickhouseClient({
+ tags: opts.tags,
+ opts: opts.clickhouseConfigs,
+ }).query({
query: opts.query,
format: "JSONEachRow",
query_params: opts.params,
@@ -221,15 +232,19 @@ export async function queryClickhouse<T>(opts: {
});
}
-export async function commandClickhouse<T>(opts: {
+export async function commandClickhouse(opts: {
query: string;
params?: Record<string, unknown> | undefined;
clickhouseConfigs?: NodeClickHouseClientConfigOptions;
+ tags?: string[];
}): Promise<void> {
return await instrumentAsync({ name: "clickhouse-command" }, async (span) => {
// https://opentelemetry.io/docs/specs/semconv/database/database-spans/
span.setAttribute("ch.query.text", opts.query);
- const res = await clickhouseClient(opts.clickhouseConfigs).command({
+ const res = await clickhouseClient({
+ tags: opts.tags,
+ opts: opts.clickhouseConfigs,
+ }).command({
query: opts.query,
query_params: opts.params,
});
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.ts
index 3c41a79d87..bd37d4c51e 100644
--- a/packages/shared/src/server/repositories/dashboards.ts
+++ b/packages/shared/src/server/repositories/dashboards.ts
@@ -39,6 +39,12 @@ export const getTotalTraces = async (
projectId,
...chFilter.params,
},
+ tags: [
+ "feature:dashboard",
+ "type:totalTraces",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
if (result.length === 0) {
@@ -83,6 +89,12 @@ export const getObservationsCostGroupedByName = async (
projectId,
...appliedFilter.params,
},
+ tags: [
+ "feature:dashboard",
+ "type:observationCostGroupedByName",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result;
@@ -137,6 +149,12 @@ export const getScoreAggregate = async (
? { tracesTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
+ tags: [
+ "feature:dashboard",
+ "type:scoreAggregate",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result;
@@ -175,6 +193,12 @@ export const groupTracesByTime = async (
...chFilter.params,
...orderByParams,
},
+ tags: [
+ "feature:dashboard",
+ "type:tracesByTime",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -238,6 +262,12 @@ export const getObservationUsageByTime = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
+ tags: [
+ "feature:dashboard",
+ "type:observationUsageByTime",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -300,6 +330,12 @@ export const getDistinctModels = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
+ tags: [
+ "feature:dashboard",
+ "type:distinctModels",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result;
@@ -356,6 +392,12 @@ export const getScoresAggregateOverTime = async (
...appliedFilter.params,
...orderByParams,
},
+ tags: [
+ "feature:dashboard",
+ "type:scoresAggregateOverTime",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -413,6 +455,12 @@ export const getModelUsageByUser = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }
: {}),
},
+ tags: [
+ "feature:dashboard",
+ "type:modelUsageByUser",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -448,6 +496,12 @@ export const getObservationLatencies = async (
const result = await queryClickhouse<{ quantiles: string[]; name: string }>({
query,
params: { projectId, ...appliedFilter.params },
+ tags: [
+ "feature:dashboard",
+ "type:observationLatencies",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -509,6 +563,12 @@ export const getTracesLatencies = async (
? { dateTimeFilterObservations: timestampFilter.value }
: {}),
},
+ tags: [
+ "feature:dashboard",
+ "type:tracesLatencies",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -558,6 +618,12 @@ export const getModelLatenciesOverTime = async (
}>({
query,
params: { projectId, ...appliedFilter.params, ...orderByParams },
+ tags: [
+ "feature:dashboard",
+ "type:modelLatenciesOverTime",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -611,6 +677,12 @@ export const getNumericScoreTimeSeries = async (
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
+ tags: [
+ "feature:dashboard",
+ "type:numericScoreTimeSeries",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -666,6 +738,12 @@ export const getCategoricalScoreTimeSeries = async (
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
+ tags: [
+ "feature:dashboard",
+ "type:categoricalScoreTimeSeries",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
@@ -721,6 +799,12 @@ export const getObservationsStatusTimeSeries = async (
...(chFilterRes ? chFilterRes.params : {}),
...orderByParams,
},
+ tags: [
+ "feature:dashboard",
+ "type:observationStatusTimeSeries",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return result.map((row) => ({
diff --git a/packages/shared/src/server/repositories/eventLog.ts b/packages/shared/src/server/repositories/eventLog.ts
index 478802b682..fe170f2c03 100644
--- a/packages/shared/src/server/repositories/eventLog.ts
+++ b/packages/shared/src/server/repositories/eventLog.ts
@@ -26,6 +26,7 @@ export const getEventLogByProjectAndEntityId = async (
entityType,
entityId,
},
+ tags: ["feature:eventLog", "kind:byId", `projectId:${projectId}`],
});
};
@@ -43,6 +44,7 @@ export const getEventLogByProjectId = (
params: {
projectId,
},
+ tags: ["feature:eventLog", "kind:list", `projectId:${projectId}`],
});
};
@@ -63,6 +65,7 @@ export const getEventLogByProjectIdBeforeDate = (
projectId,
beforeDate: convertDateToClickhouseDateTime(beforeDate),
},
+ tags: ["feature:eventLog", "kind:list", `projectId:${projectId}`],
});
};
@@ -81,6 +84,7 @@ export const deleteEventLogByProjectId = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: ["feature:eventLog", "kind:delete", `projectId:${projectId}`],
});
};
@@ -102,5 +106,6 @@ export const deleteEventLogByProjectIdBeforeDate = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: ["feature:eventLog", "kind:delete", `projectId:${projectId}`],
});
};
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 0ec580da02..04645bf09e 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -65,6 +65,12 @@ export const checkObservationExists = async (
? { startTime: convertDateToClickhouseDateTime(startTime) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:exists",
+ `projectId:${projectId}`,
+ ],
});
return rows.length > 0;
@@ -90,6 +96,12 @@ export const upsertObservation = async (
table: "observations",
records: [observation as ObservationRecordReadType],
eventBodyMapper: convertObservation,
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:upsert",
+ `projectId:${observation.project_id}`,
+ ],
});
};
@@ -144,6 +156,12 @@ export const getObservationsViewForTrace = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return records.map(convertObservationToView);
@@ -203,6 +221,12 @@ export const getObservationForTraceIdByName = async (
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return records.map(convertObservationToView);
@@ -362,6 +386,12 @@ const getObservationByIdInternal = async (
? { startTime: convertDateToClickhouseDateTime(startTime) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:byId",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -375,21 +405,6 @@ export type ObservationTableQuery = {
selectIOAndMetadata?: boolean;
};
-export type ObservationTableRecord = {
- id: string;
- projectId: string;
- traceId: string;
- observationCount: number;
- providedCostDetails: Record<string, number>;
- costDetails: Record<string, number>;
- usageDetails: Record<string, number>;
- providedUsageDetails: Record<string, number>;
- latencyMs: number;
- level: ObservationLevel;
- scoresAvg: Record<string, number>;
- scoresValues: Record<string, number>;
-};
-
export type ObservationsTableQueryResult = ObservationRecordReadType & {
latency?: string;
time_to_first_token?: string;
@@ -402,48 +417,9 @@ export const getObservationsTableCount = async (opts: ObservationTableQuery) =>
getObservationsTableInternal<TableCount>({
...opts,
select: "count",
+ tags: ["kind:count"],
});
-export type ObservationsTableRow = Omit<
- FullObservation,
- "modelId" | "inputPrice" | "outputPrice" | "totalPrice"
->;
-
-export const getObservationsTable = async (
- opts: ObservationTableQuery,
-): Promise<Array<ObservationsTableRow>> => {
- const observationRecords = await getObservationsTableInternal<
- Omit<
- ObservationsTableQueryResult,
- "trace_tags" | "trace_name" | "trace_user_id"
- >
- >({
- ...opts,
- select: "rows",
- });
-
- const traces = await getTracesByIds(
- observationRecords
- .map((o) => o.trace_id)
- .filter((o): o is string => Boolean(o)),
- opts.projectId,
- );
-
- return observationRecords.map((o) => {
- const trace = traces.find((t) => t.id === o.trace_id);
- return {
- ...convertObservationToView(o),
- latency: o.latency ? Number(o.latency) / 1000 : null,
- timeToFirstToken: o.time_to_first_token
- ? Number(o.time_to_first_token) / 1000
- : null,
- traceName: trace?.name ?? null,
- traceTags: trace?.tags ?? [],
- userId: trace?.userId ?? null,
- };
- });
-};
-
export const getObservationsTableWithModelData = async (
opts: ObservationTableQuery,
): Promise<FullObservations> => {
@@ -455,6 +431,7 @@ export const getObservationsTableWithModelData = async (
>({
...opts,
select: "rows",
+ tags: ["kind:list"],
});
const uniqueModels: string[] = Array.from(
@@ -511,7 +488,7 @@ export const getObservationsTableWithModelData = async (
};
const getObservationsTableInternal = async <T>(
- opts: ObservationTableQuery & { select: "count" | "rows" },
+ opts: ObservationTableQuery & { select: "count" | "rows"; tags: string[] },
): Promise<Array<T>> => {
const select =
opts.select === "count"
@@ -703,6 +680,12 @@ const getObservationsTableInternal = async <T>(
: {}),
...search.params,
},
+ tags: [
+ ...(opts.tags ?? []),
+ "feature:tracing",
+ "type:observation",
+ `projectId:${projectId}`,
+ ],
});
return res;
@@ -748,6 +731,12 @@ export const getObservationsGroupedByModel = async (
params: {
...appliedObservationsFilter.params,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return res.map((r) => ({ model: r.name }));
};
@@ -792,6 +781,12 @@ export const getObservationsGroupedByModelId = async (
params: {
...appliedObservationsFilter.params,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return res.map((r) => ({ modelId: r.modelId }));
};
@@ -836,6 +831,12 @@ export const getObservationsGroupedByName = async (
params: {
...appliedObservationsFilter.params,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return res;
};
@@ -881,6 +882,12 @@ export const getObservationsGroupedByPromptName = async (
params: {
...appliedObservationsFilter.params,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
const prompts = res.map((r) => r.id).filter((r): r is string => Boolean(r));
@@ -934,6 +941,12 @@ export const getCostForTraces = async (
traceIds,
timestamp: convertDateToClickhouseDateTime(timestamp),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return res.length > 0 ? Number(res[0].total_cost) : undefined;
};
@@ -956,6 +969,12 @@ export const deleteObservationsByTraceIds = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -972,6 +991,12 @@ export const deleteObservationsByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -993,6 +1018,12 @@ export const deleteObservationsOlderThanDays = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -1014,6 +1045,12 @@ export const getObservationsWithPromptName = async (
projectId,
promptNames,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((r) => ({
@@ -1076,6 +1113,12 @@ export const getObservationMetricsForPrompts = async (
projectId,
promptIds,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((r) => ({
@@ -1114,6 +1157,12 @@ export const getLatencyAndTotalCostForObservations = async (
projectId,
observationIds,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((r) => ({
@@ -1147,6 +1196,12 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (
projectId,
traceIds,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((r) => ({
@@ -1179,6 +1234,7 @@ export const getObservationCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
+ tags: ["feature:tracing", "type:observation", "kind:analytic"],
});
return rows.map((row) => ({
@@ -1208,6 +1264,14 @@ export const getObservationCountOfProjectsSinceCreationDate = async ({
projectIds,
start: convertDateToClickhouseDateTime(start),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ ...(projectIds.length > 0
+ ? projectIds.map((projectId) => `projectId:${projectId}`)
+ : []),
+ ],
});
return Number(rows[0]?.count ?? 0);
@@ -1232,6 +1296,12 @@ export const getTraceIdsForObservations = async (
projectId,
observationIds,
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -1285,6 +1355,12 @@ export const getGenerationsForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
+ tags: [
+ "feature:tracing",
+ "type:observation",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 8d7a2fd0e4..bd04181245 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -64,6 +64,12 @@ export const searchExistingAnnotationScore = async (
traceId,
observationId,
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map(convertToScore).shift();
};
@@ -91,6 +97,12 @@ export const getScoreById = async (
scoreId,
...(source !== undefined ? { source } : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:byId",
+ `projectId:${projectId}`,
+ ],
});
return rows.map(convertToScore).shift();
};
@@ -117,6 +129,12 @@ export const getScoresByIds = async (
scoreId,
...(source !== undefined ? { source } : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:byId",
+ `projectId:${projectId}`,
+ ],
});
return rows.map(convertToScore);
};
@@ -133,6 +151,12 @@ export const upsertScore = async (score: Partial<ScoreRecordReadType>) => {
table: "scores",
records: [score as ScoreRecordReadType],
eventBodyMapper: convertToScore,
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:upsert",
+ `projectId:${score.project_id}`,
+ ],
});
};
@@ -169,6 +193,12 @@ export const getScoresForTraces = async (props: GetScoresForTracesProps) => {
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map(convertToScore);
@@ -199,6 +229,12 @@ export const getScoresForObservations = async (
limit: limit,
offset: offset,
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map(convertToScore);
@@ -235,6 +271,12 @@ export const getScoresGroupedByNameSourceType = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -285,6 +327,12 @@ export const getScoresGroupedByName = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows;
@@ -301,6 +349,7 @@ export const getScoresUiCount = async (props: {
select: `
count(*) as count
`,
+ tags: ["kind:count"],
...props,
});
@@ -369,6 +418,7 @@ export const getScoresUiTable = async (props: {
t.name as trace_name,
t.tags as trace_tags
`,
+ tags: ["kind:analytic"],
...props,
});
@@ -402,6 +452,7 @@ export const getScoresUiGeneric = async <T>(props: {
orderBy: OrderByState;
limit?: number;
offset?: number;
+ tags?: string[];
}): Promise<T[]> => {
const { select, projectId, filter, orderBy, limit, offset } = props;
@@ -436,6 +487,12 @@ export const getScoresUiGeneric = async <T>(props: {
limit: limit,
offset: offset,
},
+ tags: [
+ ...(props.tags ?? []),
+ "feature:tracing",
+ "type:score",
+ `projectId:${projectId}`,
+ ],
});
return rows;
@@ -476,6 +533,12 @@ export const getScoreNames = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -496,6 +559,12 @@ export const deleteScore = async (projectId: string, scoreId: string) => {
projectId,
scoreId,
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -517,6 +586,12 @@ export const deleteScoresByTraceIds = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -533,6 +608,12 @@ export const deleteScoresByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -554,6 +635,12 @@ export const deleteScoresOlderThanDays = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -588,6 +675,12 @@ export const getNumericScoreHistogram = async (
limit,
...(chFilterRes ? chFilterRes.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -624,6 +717,12 @@ export const getAggregatedScoresForPrompts = async (
projectId,
promptIds,
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -655,6 +754,7 @@ export const getScoreCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
+ tags: ["feature:tracing", "type:score", "kind:analytic"],
});
return rows.map((row) => ({
@@ -693,6 +793,12 @@ export const getDistinctScoreNames = async (
}
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => row.name);
@@ -733,6 +839,12 @@ export const getScoresForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
+ tags: [
+ "feature:tracing",
+ "type:score",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 0619428e81..33d82840fd 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -100,6 +100,12 @@ export const checkTraceExists = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:exists",
+ `projectId:${projectId}`,
+ ],
});
return rows.length > 0;
@@ -117,6 +123,12 @@ export const upsertTrace = async (trace: Partial<TraceRecordReadType>) => {
table: "traces",
records: [trace as TraceRecordReadType],
eventBodyMapper: convertClickhouseToDomain,
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:upsert",
+ `projectId:${trace.project_id}`,
+ ],
});
};
@@ -140,6 +152,12 @@ export const getTracesByIds = async (
projectId,
timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:byId",
+ `projectId:${projectId}`,
+ ],
});
return records.map(convertClickhouseToDomain);
@@ -165,6 +183,12 @@ export const getTracesBySessionId = async (
projectId,
timestamp: timestamp ? convertDateToClickhouseDateTime(timestamp) : null,
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return records.map(convertClickhouseToDomain);
@@ -183,6 +207,12 @@ export const hasAnyTrace = async (projectId: string) => {
params: {
projectId,
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:exists",
+ `projectId:${projectId}`,
+ ],
});
return rows.length > 0 && Number(rows[0].count) > 0;
@@ -211,6 +241,7 @@ export const getTraceCountsByProjectInCreationInterval = async ({
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
},
+ tags: ["feature:tracing", "type:trace", "kind:analytic"],
});
return rows.map((row) => ({
@@ -243,6 +274,12 @@ export const getTraceById = async (
? { timestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:byId",
+ `projectId:${projectId}`,
+ ],
});
const res = records.map(convertClickhouseToDomain);
@@ -287,6 +324,12 @@ export const getTracesGroupedByName = async (
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows;
@@ -343,6 +386,12 @@ export const getTracesGroupedByUsers = async (
...(tracesFilterRes ? tracesFilterRes.params : {}),
...(searchQuery ? search.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows;
@@ -380,6 +429,12 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {
projectId: projectId,
...(filterRes ? filterRes.params : {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows;
@@ -414,6 +469,12 @@ export const getTracesIdentifierForSession = async (
projectId,
sessionId,
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:list",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -439,6 +500,12 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -460,6 +527,12 @@ export const deleteTracesOlderThanDays = async (
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -476,6 +549,12 @@ export const deleteTracesByProjectId = async (projectId: string) => {
clickhouseConfigs: {
request_timeout: 120_000, // 2 minutes
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:delete",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -510,6 +589,12 @@ export const getTotalUserCount = async (
...tracesFilterRes.params,
...search.params,
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
};
@@ -638,6 +723,12 @@ export const getUserMetrics = async (
}
: {}),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
return rows.map((row) => ({
@@ -698,6 +789,12 @@ export const getTracesForPostHog = async function* (
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
},
+ tags: [
+ "feature:tracing",
+ "type:trace",
+ "kind:analytic",
+ `projectId:${projectId}`,
+ ],
});
const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
@@ -742,6 +839,7 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {
params: {
traceIds,
},
+ tags: ["feature:tracing", "type:trace", "kind:list"],
});
return records.map((record) => ({
diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.ts
index 5cdec6a313..e531a5ded8 100644
--- a/packages/shared/src/server/services/sessions-ui-table-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts
@@ -49,6 +49,7 @@ export const getSessionsTableCount = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
+ tags: ["kind:count"],
});
return rows.length > 0 ? Number(rows[0].count) : 0;
@@ -68,6 +69,7 @@ export const getSessionsTable = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
+ tags: ["kind:list"],
});
return rows.map((row) => ({
@@ -90,6 +92,7 @@ export const getSessionsWithMetrics = async (props: {
orderBy: props.orderBy,
limit: props.limit,
page: props.page,
+ tags: ["kind:analytic"],
});
return rows.map((row) => ({
@@ -107,6 +110,7 @@ export type FetchSessionsTableProps = {
orderBy?: OrderByState;
limit?: number;
page?: number;
+ tags?: string[];
};
const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
@@ -313,6 +317,12 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
? { observationsStartTime: obsStartTimeValue }
: {}),
},
+ tags: [
+ ...(props.tags ?? []),
+ "feature:tracing",
+ "type:sessions-table",
+ `projectId:${projectId}`,
+ ],
});
return res;
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index 9fc1f954d6..f297853a38 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -160,6 +160,7 @@ export type FetchTracesTableProps = {
orderBy?: OrderByState;
limit?: number;
page?: number;
+ tags?: string[];
};
export const getTracesTableCount = async (props: {
@@ -172,6 +173,7 @@ export const getTracesTableCount = async (props: {
}) => {
const countRows = await getTracesTableGeneric<{ count: string }>({
select: "count",
+ tags: ["kind:count"],
...props,
});
@@ -193,6 +195,7 @@ export const getTracesTableMetrics = async (props: {
const countRows =
await getTracesTableGeneric<TracesTableMetricsClickhouseReturnType>({
select: "metrics",
+ tags: ["kind:analytic"],
...props,
});
@@ -209,6 +212,7 @@ export const getTracesTable = async (
) => {
const rows = await getTracesTableGeneric<TracesTableReturnType>({
select: "rows",
+ tags: ["kind:list"],
projectId,
filter,
searchQuery,
@@ -443,6 +447,12 @@ const getTracesTableGeneric = async <T>(props: FetchTracesTableProps) => {
...scoresFilterRes.params,
...search.params,
},
+ tags: [
+ ...(props.tags ?? []),
+ "feature:tracing",
+ "type:traces-table",
+ `projectId:${projectId}`,
+ ],
});
return res;
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index 25b28076a1..ba5028df18 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -162,7 +162,10 @@ export const insertPostgresDatasetRunsIntoClickhouse = async (
})),
);
- await clickhouseClient({ session_id: clickhouseSession }).insert({
+ await clickhouseClient({
+ tags: ["feature:dataset", `projectId:${projectId}`],
+ opts: { session_id: clickhouseSession },
+ }).insert({
table: tableName,
values: rows,
format: "JSONEachRow",
@@ -190,6 +193,7 @@ export const createTempTableInClickhouse = async (
query,
params: { tableName },
clickhouseConfigs: { session_id: clickhouseSession },
+ tags: ["feature:dataset"],
});
};
@@ -204,6 +208,7 @@ export const deleteTempTableInClickhouse = async (
query,
params: { tableName },
clickhouseConfigs: { session_id: sessionId },
+ tags: ["feature:dataset"],
});
};
@@ -270,6 +275,7 @@ const getScoresFromTempTable = async (
datasetId: input.datasetId,
},
clickhouseConfigs: { session_id: clickhouseSession },
+ tags: ["feature:dataset", `projectId:${input.projectId}`],
});
return rows.map((row) => ({ ...convertToScore(row), run_id: row.run_id }));
@@ -319,6 +325,7 @@ const getObservationLatencyAndCostForDataset = async (
datasetId: input.datasetId,
},
clickhouseConfigs: { session_id: clickhouseSession },
+ tags: ["feature:dataset", `projectId:${input.projectId}`],
});
return rows.map((row) => ({
@@ -368,6 +375,7 @@ const getTraceLatencyAndCostForDataset = async (
datasetId: input.datasetId,
},
clickhouseConfigs: { session_id: clickhouseSession },
+ tags: ["feature:dataset", `projectId:${input.projectId}`],
});
return rows.map((row) => ({
diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.ts
index e0d19bc8c0..ebadf522de 100644
--- a/worker/src/queues/ingestionQueue.ts
+++ b/worker/src/queues/ingestionQueue.ts
@@ -215,7 +215,12 @@ export const ingestionQueueProcessorBuilder = (
redis,
prisma,
clickhouseWriter,
- clickhouseClient(),
+ clickhouseClient({
+ tags: [
+ "feature:ingestion",
+ `projectId:${job.data.payload.authCheck.scope.projectId}`,
+ ],
+ }),
).mergeAndWrite(
getClickhouseEntityType(events[0].type),
job.data.payload.authCheck.scope.projectId,
diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.ts
index 301bf8d0e7..13d5a5f228 100644
--- a/worker/src/services/ClickhouseWriter/index.ts
+++ b/worker/src/services/ClickhouseWriter/index.ts
@@ -208,7 +208,10 @@ export class ClickhouseWriter {
}): Promise<void> {
const startTime = Date.now();
- await (ClickhouseWriter.client ?? clickhouseClient())
+ await (
+ ClickhouseWriter.client ??
+ clickhouseClient({ tags: ["feature:ingestion"] })
+ )
.insert({
table: params.table,
format: "JSONEachRow",