🪢 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
feat(clickhouse)!: standardize query log comments (#14493)
Max Deichmanncee64dad9f3d
diff --git a/packages/shared/src/features/query/server/queryExecutor.ts b/packages/shared/src/features/query/server/queryExecutor.tsindex 2931425022..1fc538f3e2 100644--- a/packages/shared/src/features/query/server/queryExecutor.ts+++ b/packages/shared/src/features/query/server/queryExecutor.ts@@ -12,7 +12,7 @@ export type PreparedQuery = {compiledQuery: string;parameters: Record<string, unknown>;preferredClickhouseService: PreferredClickhouseService | undefined;- tags: Record<string, string>;+ tags: { projectId: string };clickhouseSettings: Record<string, string>;usesTraceTable: boolean;fromTimestamp: string;@@ -53,12 +53,7 @@ export async function prepareExecuteQuery(opts: {? ("EventsReadOnly" as const): undefined;- const tags = {- feature: "custom-queries",- type: query.view,- kind: "analytic",- projectId,- };+ const tags = { projectId };const clickhouseSettings: Record<string, string> = {date_time_output_format: "iso",@@ -119,10 +114,7 @@ export async function executeQuery(query: prepared.compiledQuery,params: prepared.parameters,fromTimestamp: prepared.fromTimestamp,- tags: {- ...prepared.tags,- operation_name: "executeQuery",- },+ tags: prepared.tags,},fn: async (input) => {return queryClickhouse<Record<string, unknown>>({diff --git a/packages/shared/src/server/clickhouse/queryTags.test.ts b/packages/shared/src/server/clickhouse/queryTags.test.tsnew file mode 100644index 0000000000..fa13bf4df1--- /dev/null+++ b/packages/shared/src/server/clickhouse/queryTags.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { buildClickHouseLogComment } from "./queryTags";++describe("ClickHouse query tags", () => {+ it("builds v1 log comments from entrypoint context", () => {+ const logComment = buildClickHouseLogComment({+ surface: "publicapi",+ route:+ "GET /api/public/traces/123e4567-e89b-12d3-a456-426614174000?select=full",+ projectId: "project-1",+ });++ expect(JSON.parse(logComment)).toEqual({+ tag_schema_version: "1",+ surface: "publicapi",+ route:+ "GET /api/public/traces/123e4567-e89b-12d3-a456-426614174000?select=full",+ projectId: "project-1",+ });+ });++ it("uses unknown surface and omits route when request context is missing", () => {+ const logComment = buildClickHouseLogComment();++ expect(JSON.parse(logComment)).toEqual({+ tag_schema_version: "1",+ surface: "unknown",+ });+ });++ it("omits optional route and project id when absent", () => {+ const logComment = buildClickHouseLogComment({+ surface: "publicapi",+ });++ expect(JSON.parse(logComment)).toEqual({+ tag_schema_version: "1",+ surface: "publicapi",+ });+ });+});diff --git a/packages/shared/src/server/clickhouse/queryTags.ts b/packages/shared/src/server/clickhouse/queryTags.tsnew file mode 100644index 0000000000..cac6e6c24a--- /dev/null+++ b/packages/shared/src/server/clickhouse/queryTags.ts@@ -0,0 +1,69 @@+import { context, propagation } from "@opentelemetry/api";++export const CLICKHOUSE_QUERY_TAG_SCHEMA_VERSION = "1" as const;+const UNKNOWN_CLICKHOUSE_QUERY_TAG_VALUE = "unknown" as const;++export const clickHouseQuerySurfaces = [+ "trpc",+ "worker",+ "publicapi",+ "mcp",+] as const;++export type ClickHouseQuerySurface = (typeof clickHouseQuerySurfaces)[number];++export type ClickHouseQueryTags = {+ surface?: ClickHouseQuerySurface | (string & {});+ route?: string;+ projectId?: string;+};++export type NormalizedClickHouseQueryTags = {+ tag_schema_version: typeof CLICKHOUSE_QUERY_TAG_SCHEMA_VERSION;+ surface: ClickHouseQuerySurface | typeof UNKNOWN_CLICKHOUSE_QUERY_TAG_VALUE;+ route?: string;+ projectId?: string;+};++export const CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS = {+ surface: "langfuse.clickhouse.surface",+ route: "langfuse.clickhouse.route",+ projectId: "langfuse.project.id",+} as const;++const surfaceSet = new Set<string>(clickHouseQuerySurfaces);++const isClickHouseQuerySurface = (+ value: unknown,+): value is ClickHouseQuerySurface =>+ typeof value === "string" && surfaceSet.has(value);++export function normalizeClickHouseQueryTags(+ tags?: ClickHouseQueryTags,+): NormalizedClickHouseQueryTags {+ const baggage = propagation.getBaggage(context.active());+ const providedTags = tags as ClickHouseQueryTags | undefined;+ const surface =+ providedTags?.surface ??+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.surface)?.value;+ const route =+ providedTags?.route ??+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.route)?.value;+ const projectId =+ providedTags?.projectId ??+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.projectId)?.value;+ const normalizedRoute = typeof route === "string" ? route.trim() : "";++ return {+ tag_schema_version: CLICKHOUSE_QUERY_TAG_SCHEMA_VERSION,+ surface: isClickHouseQuerySurface(surface)+ ? surface+ : UNKNOWN_CLICKHOUSE_QUERY_TAG_VALUE,+ ...(normalizedRoute ? { route: normalizedRoute } : {}),+ ...(projectId ? { projectId } : {}),+ };+}++export function buildClickHouseLogComment(tags?: ClickHouseQueryTags): string {+ return JSON.stringify(normalizeClickHouseQueryTags(tags));+}diff --git a/packages/shared/src/server/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.tsindex 8a5fcb4269..b62e1c13e6 100644--- a/packages/shared/src/server/clickhouse/queryTracking.ts+++ b/packages/shared/src/server/clickhouse/queryTracking.ts@@ -37,15 +37,7 @@ function systemTableRef(* Polls ClickHouse to determine the status of a query by its query_id.* First checks system.processes for running queries, then system.query_log for completed/failed.*/-export async function pollQueryStatus(- queryId: string,- tags?: Record<string, string>,-): Promise<QueryStatus> {- const tagsWithDefaults = {- feature: "query-tracking",- operation: "pollQueryStatus",- ...tags,- };+export async function pollQueryStatus(queryId: string): Promise<QueryStatus> {// First check if still running in system.processesconst running = await queryClickhouse<{ query_id: string }>({query: `@@ -61,7 +53,6 @@ export async function pollQueryStatus(clickhouseSettings: {skip_unavailable_shards: 1,},- tags: tagsWithDefaults,});if (running.length > 0) {@@ -86,7 +77,6 @@ export async function pollQueryStatus(clickhouseSettings: {skip_unavailable_shards: 1,},- tags: tagsWithDefaults,});if (result.length === 0) {@@ -133,10 +123,6 @@ export async function getQueryError(clickhouseSettings: {skip_unavailable_shards: 1,},- tags: {- feature: "query-tracking",- operation: "getQueryError",- },});return result[0]?.exception_message;diff --git a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts b/packages/shared/src/server/data-deletion/ingestionFileDeletion.tsindex 7006739800..f8ba581500 100644--- a/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts+++ b/packages/shared/src/server/data-deletion/ingestionFileDeletion.ts@@ -8,6 +8,7 @@ import { BlobStorageFileRefRecordReadType } from "../repositories/definitions";import { logger } from "../logger";import { env } from "../../env";import { clickhouseClient } from "../clickhouse/client";+import { buildClickHouseLogComment } from "../clickhouse/queryTags";import { getS3EventStorageClient } from "../s3";export const deleteIngestionEventsFromS3AndClickhouseForScores = async (p: {@@ -74,7 +75,9 @@ async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(p: {);// soft delete the blob storage references in clickhouse- await softDeleteInClickhouse(blobStorageRefs);+ await softDeleteInClickhouse(blobStorageRefs, {+ projectId,+ });batch++;logger.info(`Deleted batch ${batch} of size ${blobStorageRefs.length} for ${projectId} of deleting s3 refs`,@@ -86,7 +89,9 @@ async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(p: {await eventStorageClient.deleteFiles(blobStorageRefs.map((r) => r.bucket_path),);- await softDeleteInClickhouse(blobStorageRefs);+ await softDeleteInClickhouse(blobStorageRefs, {+ projectId,+ });logger.info(`Deleted last batch ${batch} of size ${blobStorageRefs.length} for ${projectId} of deleting s3 refs`,);@@ -94,7 +99,14 @@ async function removeIngestionEventsFromS3AndDeleteClickhouseRefs(p: {async function softDeleteInClickhouse(blobStorageRefs: BlobStorageFileRefRecordReadType[],+ p: {+ projectId: string;+ },) {+ if (blobStorageRefs.length === 0) {+ return;+ }+await clickhouseClient().insert({table: "blob_storage_file_log",values: blobStorageRefs.map((e) => ({@@ -104,5 +116,10 @@ async function softDeleteInClickhouse(updated_at: new Date().getTime(),})),format: "JSONEachRow",+ clickhouse_settings: {+ log_comment: buildClickHouseLogComment({+ projectId: p.projectId,+ }),+ },});}diff --git a/packages/shared/src/server/headerPropagation.ts b/packages/shared/src/server/headerPropagation.tsindex b2070b3d0e..2c663f8694 100644--- a/packages/shared/src/server/headerPropagation.ts+++ b/packages/shared/src/server/headerPropagation.ts@@ -1,12 +1,20 @@import * as opentelemetry from "@opentelemetry/api";import type { IncomingHttpHeaders } from "http";import { env } from "../env";+import {+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS,+ type ClickHouseQuerySurface,+} from "./clickhouse/queryTags";export type LangfuseContextProps = {headers?: IncomingHttpHeaders;userId?: string;projectId?: string;apiKeyId?: string;+ clickhouse?: {+ surface: ClickHouseQuerySurface;+ route?: string;+ };};/**@@ -60,6 +68,16 @@ export const contextWithLangfuseProps = (value: props.apiKeyId,});}+ if (props.clickhouse) {+ baggage = baggage.setEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.surface, {+ value: props.clickhouse.surface,+ });+ if (props.clickhouse.route?.trim()) {+ baggage = baggage.setEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.route, {+ value: props.clickhouse.route,+ });+ }+ }return opentelemetry.propagation.setBaggage(ctx, baggage);};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 50777a5279..65aa23232c 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -59,6 +59,7 @@ export {export * from "./clickhouse/schemaUtils";export * from "./clickhouse/schema";export * from "./clickhouse/queryTracking";+export * from "./clickhouse/queryTags";export * from "./repositories/definitions";export * from "../utils/IORepresentation/chatML/types";export * from "../server/ingestion/types";diff --git a/packages/shared/src/server/repositories/blobStorageLog.ts b/packages/shared/src/server/repositories/blobStorageLog.tsindex 2c7779f8c6..d06bee2fe1 100644--- a/packages/shared/src/server/repositories/blobStorageLog.ts+++ b/packages/shared/src/server/repositories/blobStorageLog.ts@@ -26,11 +26,7 @@ export const getBlobStorageByProjectAndEntityId = async (entityType,entityId,},- tags: {- feature: "eventLog",- kind: "byID",- projectId,- },+ tags: { projectId },});};@@ -48,11 +44,7 @@ export const getBlobStorageByProjectId = (params: {projectId,},- tags: {- feature: "eventLog",- kind: "list",- projectId,- },+ tags: { projectId },});};@@ -73,11 +65,7 @@ export const getBlobStorageByProjectIdBeforeDate = (projectId,beforeDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "eventLog",- kind: "list",- projectId,- },+ tags: { projectId },});};@@ -104,11 +92,7 @@ export const getBlobStorageByProjectIdAndEntityIds = (clickhouseConfigs: {request_timeout: 120_000, // 2 minutes},- tags: {- feature: "eventLog",- kind: "list",- projectId,- },+ tags: { projectId },});};@@ -170,11 +154,7 @@ export const getBlobStorageByProjectIdAndTraceIds = (clickhouseConfigs: {request_timeout: 120_000, // 2 minutes},- tags: {- feature: "eventLog",- kind: "list",- projectId,- },+ tags: { projectId },});};@@ -209,10 +189,6 @@ export const insertIntoS3RefsTableFromEventLog = async (limit,offset,},- tags: {- feature: "backgroundMigration",- kind: "list",- },});};diff --git a/packages/shared/src/server/repositories/clickhouse.ts b/packages/shared/src/server/repositories/clickhouse.tsindex 31414857d9..7546eda1b5 100644--- a/packages/shared/src/server/repositories/clickhouse.ts+++ b/packages/shared/src/server/repositories/clickhouse.ts@@ -12,13 +12,7 @@ import { getTracer, instrumentAsync } from "../instrumentation";import { randomUUID } from "crypto";import { getClickhouseEntityType } from "../clickhouse/schemaUtils";import { NodeClickHouseClientConfigOptions } from "@clickhouse/client/dist/config";-import {- type Span,- context,- isSpanContextValid,- SpanKind,- trace,-} from "@opentelemetry/api";+import { type Span, context, SpanKind, trace } from "@opentelemetry/api";import { backOff } from "exponential-backoff";import {StorageService,@@ -31,6 +25,12 @@ import {type DataFormat,} from "@clickhouse/client";import { RESOURCE_LIMIT_ERROR_MESSAGE } from "../../errors/errorMessages";+import {+ buildClickHouseLogComment,+ normalizeClickHouseQueryTags,+ type ClickHouseQueryTags,+ type NormalizedClickHouseQueryTags,+} from "../clickhouse/queryTags";/*** Custom error class for ClickHouse resource-related errors@@ -59,12 +59,12 @@ export class ClickHouseResourceError extends Error {static ERROR_ADVICE_MESSAGE = RESOURCE_LIMIT_ERROR_MESSAGE;public readonly errorType: ErrorType;- public readonly tags?: Record<string, string>;+ public readonly tags?: NormalizedClickHouseQueryTags;constructor(errType: ErrorType,originalError: Error,- tags?: Record<string, string>,+ tags?: NormalizedClickHouseQueryTags,) {super(originalError.message, { cause: originalError });this.name = "ClickHouseResourceError";@@ -78,7 +78,7 @@ export class ClickHouseResourceError extends Error {static wrapIfResourceError(originalError: Error,- tags?: Record<string, string>,+ tags?: NormalizedClickHouseQueryTags,): Error {const errorMessage = originalError.message || "";@@ -141,7 +141,7 @@ export async function upsertClickhouse<table: "scores" | "traces" | "observations" | "traces_null";records: T[];eventBodyMapper: (body: T) => Record<string, unknown>;- tags?: Record<string, string>;+ tags?: ClickHouseQueryTags;}): Promise<void> {return await instrumentAsync({ name: "clickhouse-upsert", spanKind: SpanKind.CLIENT },@@ -189,7 +189,7 @@ export async function upsertClickhouse<],format: "JSONEachRow",clickhouse_settings: {- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),+ log_comment: buildClickHouseLogComment(opts.tags),},});}@@ -215,7 +215,7 @@ export async function upsertClickhouse<})),format: "JSONEachRow",clickhouse_settings: {- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),+ log_comment: buildClickHouseLogComment(opts.tags),},});// same logic as for prisma. we want to see queries in development@@ -250,6 +250,7 @@ export async function* queryClickhouseStream<T>(opts: ClickhouseQueryOpts,): AsyncGenerator<T> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const tracer = getTracer("clickhouse-query-stream");const span = tracer.startSpan("clickhouse-query-stream", {kind: SpanKind.CLIENT,@@ -267,7 +268,7 @@ export async function* queryClickhouseStream<T>(.catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(error as Error,- opts.tags,+ normalizedTags,);});@@ -284,11 +285,15 @@ export async function* queryClickhouseStream<T>(const enriched = enrichWithQueryId(error, queryId);throw enriched === error? error- : new ClickHouseResourceError(error.errorType, enriched, error.tags);+ : new ClickHouseResourceError(+ error.errorType,+ enriched,+ normalizedTags,+ );}throw ClickHouseResourceError.wrapIfResourceError(enrichWithQueryId(error as Error, queryId),- opts.tags,+ normalizedTags,);} finally {span.end();@@ -316,6 +321,7 @@ export async function* queryClickhouseStreamRawText(opts: ClickhouseQueryOpts,): AsyncGenerator<string> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const tracer = getTracer("clickhouse-query-stream-raw-text");const span = tracer.startSpan("clickhouse-query-stream-raw-text", {kind: SpanKind.CLIENT,@@ -333,7 +339,7 @@ export async function* queryClickhouseStreamRawText(.catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(error as Error,- opts.tags,+ normalizedTags,);});@@ -350,11 +356,15 @@ export async function* queryClickhouseStreamRawText(const enriched = enrichWithQueryId(error, queryId);throw enriched === error? error- : new ClickHouseResourceError(error.errorType, enriched, error.tags);+ : new ClickHouseResourceError(+ error.errorType,+ enriched,+ normalizedTags,+ );}throw ClickHouseResourceError.wrapIfResourceError(enrichWithQueryId(error as Error, queryId),- opts.tags,+ normalizedTags,);} finally {span.end();@@ -396,6 +406,7 @@ export async function queryClickhouseExecRaw(opts: ClickhouseQueryOpts & { format: string },): Promise<ClickhouseExecRawResult> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const tracer = getTracer("clickhouse-query-exec-raw");const span = tracer.startSpan("clickhouse-query-exec-raw", {kind: SpanKind.CLIENT,@@ -417,19 +428,22 @@ export async function queryClickhouseExecRaw(query_params: opts.params,clickhouse_settings: {...opts.clickhouseSettings,- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),+ log_comment: JSON.stringify(normalizedTags),},}),).catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(enrichWithQueryId(error as Error, queryId),- opts.tags,+ normalizedTags,);});queryId = res.query_id;span.setAttribute("ch.queryId", queryId);+ for (const [key, value] of Object.entries(normalizedTags)) {+ span.setAttribute(`ch.tag.${key}`, value);+ }recordSummaryOnSpan(span, res.response_headers);if (env.NODE_ENV === "development") {@@ -446,7 +460,7 @@ export async function queryClickhouseExecRaw(wrapError: (error) =>ClickHouseResourceError.wrapIfResourceError(enrichWithQueryId(error, queryId),- opts.tags,+ normalizedTags,),}),);@@ -474,7 +488,7 @@ export async function queryClickhouseExecRaw(if (error instanceof ClickHouseResourceError) throw error;throw ClickHouseResourceError.wrapIfResourceError(enrichWithQueryId(error as Error, queryId),- opts.tags,+ normalizedTags,);}}@@ -529,7 +543,7 @@ export type ClickhouseQueryOpts = {query: string;params?: Record<string, unknown>;clickhouseConfigs?: NodeClickHouseClientConfigOptions;- tags?: Record<string, string>;+ tags?: ClickHouseQueryTags;preferredClickhouseService?: PreferredClickhouseService;clickhouseSettings?: ClickHouseSettings;allowLegacyEventsRead?: boolean;@@ -563,28 +577,17 @@ function setSpanQueryAttributes(span: Span, query: string): void {span.setAttribute("db.operation.name", "SELECT");}-export function tagsWithTraceId(- tags: Record<string, string> | undefined,-): Record<string, string> {- const ctx = trace.getActiveSpan()?.spanContext();- if (!ctx || !isSpanContextValid(ctx)) return tags ?? {};- // Use a distinct, OTel-specific key so this never collides with a- // caller-supplied `traceId` tag (e.g. the Langfuse business trace ID used- // for query_log JOINs in dataset-run-items). A single log_comment row can- // then carry both identifiers.- return { ...tags, otel_trace_id: ctx.traceId };-}-async function sendClickhouseQuery<F extends DataFormat>(opts: {query: string;params?: Record<string, unknown>;clickhouseConfigs?: NodeClickHouseClientConfigOptions;- tags?: Record<string, string>;+ tags?: ClickHouseQueryTags;preferredClickhouseService?: PreferredClickhouseService;clickhouseSettings?: ClickHouseSettings;format: F;span: Span;}) {+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const res = await clickhouseClient(opts.clickhouseConfigs,opts.preferredClickhouseService,@@ -594,7 +597,7 @@ async function sendClickhouseQuery<F extends DataFormat>(opts: {query_params: opts.params,clickhouse_settings: {...opts.clickhouseSettings,- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),+ log_comment: JSON.stringify(normalizedTags),},});@@ -603,6 +606,9 @@ async function sendClickhouseQuery<F extends DataFormat>(opts: {}opts.span.setAttribute("ch.queryId", res.query_id);+ for (const [key, value] of Object.entries(normalizedTags)) {+ opts.span.setAttribute(`ch.tag.${key}`, value);+ }recordSummaryOnSpan(opts.span, res.response_headers);return res;@@ -634,6 +640,7 @@ export async function queryClickhouse<T>(opts: ClickhouseQueryOpts,): Promise<T[]> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);return await instrumentAsync({ name: "clickhouse-query", spanKind: SpanKind.CLIENT },async (span) => {@@ -663,7 +670,7 @@ export async function queryClickhouse<T>({error: error.message,attemptNumber,- tags: opts.tags,+ tags: normalizedTags,},);span.addEvent("clickhouse-query-retry", {@@ -675,7 +682,7 @@ export async function queryClickhouse<T>(`ClickHouse query failed with non-retryable error: ${error.message}`,{error: error.message,- tags: opts.tags,+ tags: normalizedTags,},);}@@ -688,7 +695,7 @@ export async function queryClickhouse<T>().catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(error as Error,- opts.tags,+ normalizedTags,);});},@@ -699,6 +706,7 @@ export async function* queryClickhouseWithProgress<T>(opts: ClickhouseQueryOpts,): AsyncGenerator<RowOrProgress<T>> {if (!opts.allowLegacyEventsRead) assertNoLegacyEventsRead(opts.query);+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const tracer = getTracer("clickhouse-query-progress");const span = tracer.startSpan("clickhouse-query-progress", {@@ -724,7 +732,7 @@ export async function* queryClickhouseWithProgress<T>(.catch((error) => {throw ClickHouseResourceError.wrapIfResourceError(error as Error,- opts.tags,+ normalizedTags,);});@@ -737,7 +745,7 @@ export async function* queryClickhouseWithProgress<T>(if (error instanceof ClickHouseResourceError) throw error;throw ClickHouseResourceError.wrapIfResourceError(error as Error,- opts.tags,+ normalizedTags,);} finally {span.end();@@ -748,7 +756,8 @@ export async function commandClickhouse(opts: {query: string;params?: Record<string, unknown> | undefined;clickhouseConfigs?: NodeClickHouseClientConfigOptions;- tags?: Record<string, string>;+ tags?: ClickHouseQueryTags;+ queryId?: string;clickhouseSettings?: ClickHouseSettings;abortSignal?: AbortSignal;session_id?: string;@@ -761,18 +770,17 @@ export async function commandClickhouse(opts: {span.setAttribute("db.system", "clickhouse");span.setAttribute("db.query.text", opts.query);span.setAttribute("db.operation.name", "COMMAND");+ const normalizedTags = normalizeClickHouseQueryTags(opts.tags);const res = await clickhouseClient(opts.clickhouseConfigs).command({query: opts.query,query_params: opts.params,...(opts.session_id ? { session_id: opts.session_id } : {}),- ...(opts.tags?.queryId- ? { query_id: opts.tags.queryId as string }- : {}),+ ...(opts.queryId ? { query_id: opts.queryId } : {}),...(opts.abortSignal ? { abort_signal: opts.abortSignal } : {}),clickhouse_settings: {...opts.clickhouseSettings,- log_comment: JSON.stringify(tagsWithTraceId(opts.tags)),+ log_comment: JSON.stringify(normalizedTags),},});// same logic as for prisma. we want to see queries in development@@ -781,6 +789,9 @@ export async function commandClickhouse(opts: {}span.setAttribute("ch.queryId", res.query_id);+ for (const [key, value] of Object.entries(normalizedTags)) {+ span.setAttribute(`ch.tag.${key}`, value);+ }// add summary headers to the span. Helps to tune performanceconst summaryHeader = res.response_headers["x-clickhouse-summary"];diff --git a/packages/shared/src/server/repositories/daily-metrics.ts b/packages/shared/src/server/repositories/daily-metrics.tsindex f7405f128f..53f757cdd5 100644--- a/packages/shared/src/server/repositories/daily-metrics.ts+++ b/packages/shared/src/server/repositories/daily-metrics.ts@@ -104,13 +104,7 @@ export const generateDailyMetrics = async ({}: {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "daily_metrics",- projectId,- operation_name: "generateDailyMetrics",- },+ tags: { projectId },timestamp,},fn: async (input: {@@ -182,13 +176,7 @@ export const getDailyMetricsCount = async ({projectId,input: {params: { ...appliedFilter.params, projectId },- tags: {- feature: "tracing",- type: "trace",- kind: "daily_metrics_count",- projectId,- operation_name: "getDailyMetricsCount",- },+ tags: { projectId },timestamp,},fn: async (input: {diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.tsindex 1027499dc1..db624cb237 100644--- a/packages/shared/src/server/repositories/dashboards.ts+++ b/packages/shared/src/server/repositories/dashboards.ts@@ -90,12 +90,7 @@ export const getScoreAggregate = async (? { tracesTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }: {}),},- tags: {- feature: "dashboard",- type: "scoreAggregate",- kind: "analytic",- projectId,- },+ tags: { projectId },});return result;@@ -173,12 +168,7 @@ export const getObservationCostByTypeByTime = async (? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }: {}),},- tags: {- feature: "dashboard",- type: "observationCostByTypeByTime",- kind: "analytic",- projectId,- },+ tags: { projectId },});const types = result.flatMap((row) => {@@ -271,12 +261,7 @@ export const getObservationUsageByTypeByTime = async (? { traceTimestamp: convertDateToClickhouseDateTime(timeFilter.value) }: {}),},- tags: {- feature: "dashboard",- type: "observationUsageByTime",- kind: "analytic",- projectId,- },+ tags: { projectId },});const types = result.flatMap((row) => {diff --git a/packages/shared/src/server/repositories/dataset-items.ts b/packages/shared/src/server/repositories/dataset-items.tsindex 82312a7354..442fdde5d4 100644--- a/packages/shared/src/server/repositories/dataset-items.ts+++ b/packages/shared/src/server/repositories/dataset-items.ts@@ -1876,10 +1876,6 @@ export async function getDatasetVersionForRun(params: {datasetId: params.datasetId,runId: params.runId,},- tags: {- feature: "datasets",- operation: "getDatasetVersionForRun",- },});const maxCreatedAt = maxCreatedAtResult[0]?.max_created_at ?? null;diff --git a/packages/shared/src/server/repositories/dataset-run-items.ts b/packages/shared/src/server/repositories/dataset-run-items.tsindex 9e25413fe4..85895a677c 100644--- a/packages/shared/src/server/repositories/dataset-run-items.ts+++ b/packages/shared/src/server/repositories/dataset-run-items.ts@@ -229,9 +229,7 @@ const getProjectDatasetIdDefaultFilter = (};const getDatasetRunsTableInternal = async <T>(- opts: DatasetRunsMetricsTableQuery & {- tags: Record<string, string>;- },+ opts: DatasetRunsMetricsTableQuery & {},): Promise<Array<T>> => {const { projectId, datasetId, runIds, filter, orderBy, limit, offset } = opts;let select = "";@@ -493,13 +491,7 @@ const getDatasetRunsTableInternal = async <T>(...appliedFilter.params,...(limit !== undefined && offset !== undefined ? { limit, offset } : {}),},- tags: {- ...(opts.tags ?? {}),- feature: "datasets",- type: "dataset-run-items",- projectId,- datasetId,- },+ tags: { projectId },});return res;@@ -512,7 +504,6 @@ export const getDatasetRunsTableMetricsCh = async (const rows = await getDatasetRunsTableInternal<DatasetRunsMetricsRecordType>({...opts,select: "metrics",- tags: { kind: "list" },});return rows.map(convertDatasetRunsMetricsRecord);@@ -524,7 +515,6 @@ export const getDatasetRunsTableRowsCh = async (const rows = await getDatasetRunsTableInternal<DatasetRunsRowsRecordType>({...opts,select: "rows",- tags: { kind: "list" },});return rows.map(convertDatasetRunsRowsRecord);@@ -536,7 +526,6 @@ export const getDatasetRunsTableCountCh = async (const rows = await getDatasetRunsTableInternal<{ count: string }>({...opts,select: "count",- tags: { kind: "list" },});return Number(rows[0]?.count);@@ -545,7 +534,6 @@ export const getDatasetRunsTableCountCh = async (type GetDatasetRunItemsTableOpts<IncludeIO extends boolean> =DatasetRunItemsTableQuery & {select: "count" | "rows";- tags: Record<string, string>;includeIO?: IncludeIO;};@@ -722,12 +710,7 @@ const getQualifyingDatasetItems = async <T>(opts: {}, {}),...(limit !== undefined && offset !== undefined ? { limit, offset } : {}),},- tags: {- feature: "datasets",- type: "dataset-run-items",- projectId,- datasetId,- },+ tags: { projectId },});return res;@@ -909,13 +892,7 @@ const getDatasetRunItemsTableInternal = async <...(datasetId ? { datasetId } : {}),projectId,},- tags: {- ...(opts.tags ?? {}),- feature: "datasets",- type: "dataset-run-items",- projectId,- ...(datasetId ? { datasetId } : {}),- },+ tags: { projectId },clickhouseConfigs: opts.clickhouseConfigs,});@@ -928,7 +905,6 @@ export const getDatasetRunItemsCh = async (const rows = await getDatasetRunItemsTableInternal<DatasetRunItemRecord>({...opts,select: "rows",- tags: { kind: "list" },});return rows.map((row) => convertDatasetRunItemClickhouseToDomain(row));@@ -940,7 +916,6 @@ export const getDatasetRunItemsByDatasetIdCh = async (const rows = await getDatasetRunItemsTableInternal<DatasetRunItemRecord>({...opts,select: "rows",- tags: { kind: "list" },});return rows.map((row) => convertDatasetRunItemClickhouseToDomain(row));@@ -1001,7 +976,6 @@ export const getDatasetRunItemsWithoutIOByItemIds = async (...rest,filter,select: "rows",- tags: { kind: "list" },});// Step 2: Convert to domain@@ -1057,12 +1031,7 @@ export const getDatasetItemIdsByTraceIdCh = async (params: {...appliedFilter.params,},- tags: {- feature: "datasets",- type: "dataset-run-items",- projectId,- traceId,- },+ tags: { projectId },});return res.map((runItem) => {@@ -1080,7 +1049,6 @@ export const getDatasetRunItemsCountCh = async (const rows = await getDatasetRunItemsTableInternal<{ count: string }>({...opts,select: "count",- tags: { kind: "list" },});return Number(rows[0]?.count);@@ -1092,7 +1060,6 @@ export const getDatasetRunItemsCountByDatasetIdCh = async (const rows = await getDatasetRunItemsTableInternal<{ count: string }>({...opts,select: "count",- tags: { kind: "list" },});return Number(rows[0]?.count);@@ -1111,12 +1078,7 @@ export const hasAnyDatasetRunItem = async (const rows = await queryClickhouse<{ 1: number }>({query,params: { projectId },- tags: {- feature: "datasets",- type: "dataset-run-items",- kind: "hasAny",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -1140,12 +1102,7 @@ export const deleteDatasetRunItemsByProjectId = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "datasets",- type: "dataset-run-items",- kind: "delete",- projectId,- },+ tags: { projectId },});return true;@@ -1173,12 +1130,7 @@ export const deleteDatasetRunItemsByDatasetId = async ({clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "datasets",- type: "dataset-run-items",- kind: "delete",- projectId,- },+ tags: { projectId },});};@@ -1208,12 +1160,7 @@ export const deleteDatasetRunItemsByDatasetRunIds = async ({clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "datasets",- type: "dataset-run-items",- kind: "delete",- projectId,- },+ tags: { projectId },});};@@ -1240,12 +1187,6 @@ export const getDatasetRunItemCountsByProjectInCreationInterval = async ({start: convertDateToClickhouseDateTime(start),end: convertDateToClickhouseDateTime(end),},- tags: {- feature: "datasets",- type: "dataset-run-items",- kind: "analytic",- operation_name: "getDatasetRunItemCountsByProjectInCreationInterval",- },});return rows.map((row) => ({diff --git a/packages/shared/src/server/repositories/environments.ts b/packages/shared/src/server/repositories/environments.tsindex 5217292e05..829d838384 100644--- a/packages/shared/src/server/repositories/environments.ts+++ b/packages/shared/src/server/repositories/environments.ts@@ -40,12 +40,7 @@ export const getEnvironmentsForProject = async (fromTimestamp,dataTypes: LISTABLE_SCORE_TYPES,},- tags: {- feature: "tracing",- type: "environment",- kind: "byId",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});// Always add default environment to listdiff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 3598ae53c8..ebb4d4800e 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -446,7 +446,6 @@ export const getObservationsForTraceFromEventsTable = async (params: {select: "rows",selectIOAndMetadata,selectToolData,- tags: { kind: "byTraceId" },},);@@ -471,7 +470,6 @@ export const getObservationsCountFromEventsTable = async (}>({...opts,select: "count",- tags: { kind: "count" },});return Number(count[0].count);@@ -485,7 +483,6 @@ export const getObservationsWithModelDataFromEventsTable = async ({...opts,select: "rows",- tags: { kind: "list" },},);@@ -504,7 +501,6 @@ async function getObservationsFromEventsTableInternal<T>(opts: ObservationTableQuery & {select: "count" | "rows";selectToolData?: boolean;- tags: Record<string, string>;},): Promise<Array<T>> {const {@@ -667,14 +663,7 @@ async function getObservationsFromEventsTableInternal<T>(projectId,input: {params,- tags: {- ...(opts.tags ?? {}),- feature: "tracing",- type: "events",- projectId,- kind: opts.select,- operation_name: "getObservationsTableInternal",- },+ tags: { projectId },},fn: async (input) => {return queryClickhouse<T>({@@ -873,12 +862,7 @@ export const getEventsStreamForEval = async (props: {http_receive_timeout: 300,},},- tags: {- feature: "batch-eval",- type: "event",- kind: "eval",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -945,12 +929,7 @@ async function getObservationByIdFromEventsTableInternal({return await queryClickhouse<EventsObservationRecordReadType>({query,params,- tags: {- feature: "tracing",- type: "events",- kind: "byId",- projectId,- },+ tags: { projectId },preferredClickhouseService,});}@@ -968,7 +947,6 @@ export const getTraceByIdFromEventsTable = async ({timestamp,fromTimestamp,renderingProps = DEFAULT_RENDERING_PROPS,- clickhouseFeatureTag = "tracing",preferredClickhouseService,excludeInputOutput = false,excludeMetadata = false,@@ -978,7 +956,6 @@ export const getTraceByIdFromEventsTable = async ({timestamp?: Date;fromTimestamp?: Date;renderingProps?: RenderingProps;- clickhouseFeatureTag?: string;preferredClickhouseService?: PreferredClickhouseService;/** When true, sets input/output columns to empty in the query to reduce database load */excludeInputOutput?: boolean;@@ -1053,13 +1030,7 @@ export const getTraceByIdFromEventsTable = async ({projectId,input: {params,- tags: {- feature: clickhouseFeatureTag,- type: "trace",- kind: "byId",- projectId,- operation_name: "getTraceByIdFromEventsTable",- },+ tags: { projectId },},fn: async (input) => {return queryClickhouse<TraceRecordReadType>({@@ -1378,13 +1349,7 @@ async function getObservationsRowsFromBuilder<T>(projectId,input: {params,- tags: {- feature: "tracing",- type: "events",- kind: "publicApiRows",- projectId,- ...extraTags,- },+ tags: { projectId, ...extraTags },},fn: async (input) => {return await queryClickhouse<T>({@@ -1418,12 +1383,7 @@ async function getObservationsCountFromEventsTableForPublicApiInternal(projectId,input: {params,- tags: {- feature: "tracing",- type: "events",- kind: "publicApiCount",- projectId,- },+ tags: { projectId },},fn: async (input) => {return await queryClickhouse<{ count: string }>({@@ -1753,12 +1713,7 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(projectId,input: {params,- tags: {- feature: "tracing",- type: "traces",- kind: opts.select === "count" ? "publicApiCount" : "publicApiRows",- projectId,- },+ tags: { projectId },},fn: async (input) => {return await queryClickhouse<T>({@@ -1872,7 +1827,7 @@ export const updateEvents = async (? `UPDATE ${table} SET ${setClauses.join(", ")} ${whereClause}`: `ALTER TABLE ${table} UPDATE ${setClauses.join(", ")} ${whereClause}`,params,- tags: { type: table, kind: "update", projectId },+ tags: { projectId },});await Promise.all([@@ -1902,12 +1857,7 @@ const queryEventsFilterOptionRows = async (return queryClickhouse<EventFilterOptionRow>({query: queryWithParams.query,params: queryWithParams.params,- tags: {- feature: "tracing",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});};@@ -2084,12 +2034,7 @@ export const getEventsNumericStatsByFilterColumn = async (}>({query,params,- tags: {- feature: "tracing",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});const range = res[0];@@ -2147,12 +2092,7 @@ export const deleteEventsByTraceIds = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "events",- kind: "delete-preflight",- projectId,- },+ tags: { projectId },});const count = Number(preflight[0]?.cnt ?? 0);@@ -2182,12 +2122,7 @@ export const deleteEventsByTraceIds = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: table,- kind: "delete",- projectId,- },+ tags: { projectId },});// Delete from all tables in parallel@@ -2208,12 +2143,7 @@ export const hasAnyEvent = async (projectId: string) => {const rows = await queryClickhouse<{ 1: number }>({query,params: { projectId },- tags: {- feature: "tracing",- type: "events",- kind: "hasAny",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -2238,7 +2168,7 @@ export const deleteEventsByProjectId = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: { feature: "tracing", type: table, kind: "delete", projectId },+ tags: { projectId },clickhouseSettings: { send_logs_level: "trace" as const },});@@ -2281,12 +2211,7 @@ export async function getAgentGraphDataFromEventsTable(params: {projectId,input: {params: { projectId, traceId, chMinStartTime, chMaxStartTime },- tags: {- feature: "tracing",- type: "events",- kind: "agentGraphData",- projectId,- },+ tags: { projectId },},fn: async (input) => {return queryClickhouse({@@ -2317,12 +2242,7 @@ export const hasAnyEventOlderThan = async (projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "tracing",- type: "events",- kind: "hasAnyOlderThan",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -2354,7 +2274,7 @@ export const deleteEventsOlderThanDays = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: { feature: "tracing", type: table, kind: "delete", projectId },+ tags: { projectId },});await Promise.all([@@ -2444,12 +2364,7 @@ export const getObservationsBatchIOFromEventsTable = async <minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},- tags: {- feature: "tracing",- type: "events",- kind: "batchIO",- projectId: opts.projectId,- },+ tags: { projectId: opts.projectId },preferredClickhouseService: "EventsReadOnly",});@@ -2505,12 +2420,7 @@ export const getObservationsTraceIdsFromEventsTable = async (opts: {}>({query,params: queryParams,- tags: {- feature: "tracing",- type: "events",- kind: "getObservationsTraceIdsFromEventsTable",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -2572,12 +2482,7 @@ export const getUsersFromEventsTable = async (return queryClickhouse<{ user: string; count: string }>({query,params,- tags: {- feature: "users",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});};@@ -2617,12 +2522,7 @@ export const getUsersCountFromEventsTable = async (...appliedEventsFilter.params,...(searchQuery ? { searchQuery: `%${searchQuery}%` } : {}),},- tags: {- feature: "users",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});};@@ -2700,12 +2600,7 @@ export const getUserMetricsFromEventsTable = async (}>({query,params: statsParams,- tags: {- feature: "users",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -2744,12 +2639,7 @@ export const hasAnyUserFromEventsTable = async (const rows = await queryClickhouse<{ 1: number }>({query,params: { projectId },- tags: {- feature: "users",- type: "events",- kind: "hasAny",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -2814,12 +2704,7 @@ const buildEventsForBlobStorageExportQuery = (return {query,params,- tags: {- feature: "blobstorage",- type: "event",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},@@ -2930,12 +2815,7 @@ export const getEventsForAnalyticsIntegrations = async function* (const records = queryClickhouseStream<Record<string, unknown>>({query,params,- tags: {- feature: "analytics-integration",- type: "event",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},@@ -3003,12 +2883,7 @@ export const hasAnySessionFromEventsTable = async (return queryClickhouse<{ 1: number }>({query,params: input.params,- tags: {- feature: "sessions",- type: "events",- kind: "hasAny",- projectId,- },+ tags: { projectId },});},});@@ -3039,11 +2914,7 @@ export const getTraceMetadataByIdsFromEvents = async (props: {projectId: props.projectId,input: {params,- tags: {- feature: "tracing",- type: "trace-metadata",- projectId: props.projectId,- },+ tags: { projectId: props.projectId },},fn: async (input) =>queryClickhouse<{@@ -3096,12 +2967,7 @@ export const getAvgCostByEvaluatorIds = async (}>({query,params,- tags: {- feature: "evals",- type: "events",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -3134,11 +3000,7 @@ export const getSessionMetricsFromEvents = async (props: {projectId: props.projectId,input: {params,- tags: {- feature: "tracing",- type: "session-metrics-direct",- projectId: props.projectId,- },+ tags: { projectId: props.projectId },},fn: async (input) =>queryClickhouse<SessionEventsMetricsRow>({@@ -3254,11 +3116,7 @@ export async function getLatestSdkVersionInfoFromEvents(params: {}>({query,params: queryParams,- tags: {- feature: "sdk-metadata-detection",- kind: "sdkMetadata",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -3341,13 +3199,7 @@ export const getTracesIdentifierForSessionFromEvents = async (projectId,input: {params,- tags: {- feature: "tracing",- type: "trace",- kind: "list",- projectId,- operation_name: "getTracesIdentifierForSessionFromEvents",- },+ tags: { projectId },},fn: async (input) => {return await queryClickhouse<{diff --git a/packages/shared/src/server/repositories/experiments.ts b/packages/shared/src/server/repositories/experiments.tsindex 0d1e7d2160..8e72b7cc6f 100644--- a/packages/shared/src/server/repositories/experiments.ts+++ b/packages/shared/src/server/repositories/experiments.ts@@ -130,7 +130,6 @@ export const getExperimentsCountFromEvents = async (props: {orderBy: props.orderBy,limit: props.limit,page: props.page,- tags: { kind: "count" },});return rows.length > 0 ? Number(rows[0].count) : 0;@@ -151,7 +150,6 @@ export const getExperimentsFromEvents = async (props: {orderBy: props.orderBy,limit: props.limit,page: props.page,- tags: { kind: "list" },});return rows.map((row) => ({@@ -189,12 +187,7 @@ export const getExperimentMetricsFromEvents = async (props: {projectId: props.projectId,input: {params,- tags: {- feature: "experiments",- type: "experiments-table",- projectId: props.projectId,- operation_name: "getExperimentMetricsFromEvents",- },+ tags: { projectId: props.projectId },},fn: async (input) => {return queryClickhouse<ExperimentMetricsReturnType>({@@ -352,13 +345,7 @@ const getExperimentsFromEventsGeneric = async <T>(projectId,input: {params: finalParams,- tags: {- ...(props.tags ?? {}),- feature: "experiments",- type: "experiments-table",- projectId,- operation_name: `getExperimentsFromEventsGeneric-${select}`,- },+ tags: { ...(props.tags ?? {}), projectId },},fn: async (input) => {return queryClickhouse<T>({@@ -467,11 +454,7 @@ export const getExperimentItemsCountFromEvents = async (const rows = await queryClickhouse<{ count: string }>({query,params,- tags: {- feature: "experiments",- type: "experiment-items-count",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -678,23 +661,13 @@ const getExperimentItemScoreOptionsByLevel = async ({queryClickhouse<ScoreFilterOptionsRow>({query: traceQuery.query,params: traceQuery.params,- tags: {- feature: "experiments",- type: "filter-options",- kind: "trace-scores",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",}),queryClickhouse<ScoreFilterOptionsRow>({query: obsQuery.query,params: obsQuery.params,- tags: {- feature: "experiments",- type: "filter-options",- kind: "observation-scores",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",}),]);@@ -756,23 +729,13 @@ const getExperimentScoreOptionsByLevel = async ({queryClickhouse<ScoreFilterOptionsRow>({query: obsQuery.query,params: obsQuery.params,- tags: {- feature: "experiments",- type: "filter-options",- kind: "observation-scores",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",}),queryClickhouse<ScoreFilterOptionsRow>({query: runQuery.query,params: runQuery.params,- tags: {- feature: "experiments",- type: "filter-options",- kind: "run-scores",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",}),]);@@ -1058,11 +1021,7 @@ export const getExperimentItemsFromEvents = async (const itemIdsResult = await queryClickhouse<{ item_id: string }>({query: itemIdsQuery,params: itemIdsParams,- tags: {- feature: "experiments",- type: "experiment-items-filter",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -1103,11 +1062,7 @@ export const getExperimentItemsFromEvents = async (const rows = await queryClickhouse<ExperimentItemEventsDataReturnType>({query: dataQuery,params: dataParams,- tags: {- feature: "experiments",- type: "experiment-items-data",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -1211,11 +1166,7 @@ export const getExperimentItemsBatchIO = async (props: {...params,truncateLength: IO_TRUNCATE_LENGTH,},- tags: {- feature: "experiments",- type: "experiment-items-batch-io",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -1294,12 +1245,7 @@ export const getExperimentNamesFromEvents = async (props: {}>({query,params,- tags: {- feature: "tracing",- type: "events",- kind: "analytic",- projectId: props.projectId,- },+ tags: { projectId: props.projectId },preferredClickhouseService: "EventsReadOnly",});diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 1f73bc3a42..8ea5a3edf7 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -97,12 +97,7 @@ export const checkObservationExists = async (? { startTime: convertDateToClickhouseDateTime(startTime) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "exists",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -128,12 +123,7 @@ export const upsertObservation = async (table: "observations",records: [observation as ObservationRecordReadType],eventBodyMapper: convertObservation,- tags: {- feature: "tracing",- type: "observation",- kind: "upsert",- projectId: observation.project_id ?? "",- },+ tags: { projectId: observation.project_id ?? "" },});};@@ -207,12 +197,7 @@ export const getObservationsForTrace = async <IncludeIO extends boolean>(? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "list",- projectId,- },+ tags: { projectId },preferredClickhouseService,});@@ -329,12 +314,7 @@ export const getObservationForTraceIdByName = async ({? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "list",- projectId,- },+ tags: { projectId },});return records.map((record) => convertObservation(record));@@ -530,12 +510,7 @@ const getObservationByIdInternal = async ({: {}),...(traceId ? { traceId } : {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "byId",- projectId,- },+ tags: { projectId },preferredClickhouseService,});};@@ -572,7 +547,6 @@ export const getObservationsTableCount = async (}>({...opts,select: "count",- tags: { kind: "count" },});return Number(count[0].count);@@ -589,7 +563,6 @@ export const getObservationsTableWithModelData = async (>({...opts,select: "rows",- tags: { kind: "list" },});const uniqueModels: string[] = Array.from(@@ -648,7 +621,6 @@ export const getObservationsTableWithModelData = async (const getObservationsTableInternal = async <T>(opts: ObservationTableQuery & {select: "count" | "rows";- tags: Record<string, string>;},): Promise<Array<T>> => {const select =@@ -866,14 +838,7 @@ const getObservationsTableInternal = async <T>(: {}),...search.params,},- tags: {- ...(opts.tags ?? {}),- feature: "tracing",- type: "observation",- projectId,- kind: opts.select,- operation_name: "getObservationsTableInternal",- },+ tags: { projectId },},fn: async (input) => {return queryClickhouse<T>({@@ -927,12 +892,7 @@ export const getObservationsGroupedByModel = async (params: {...appliedObservationsFilter.params,},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});return res.map((r) => ({ model: r.name }));@@ -979,12 +939,7 @@ export const getObservationsGroupedByModelId = async (params: {...appliedObservationsFilter.params,},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});return res.map((r) => ({ modelId: r.modelId }));@@ -1033,12 +988,7 @@ export const getObservationsGroupedByName = async (...appliedObservationsFilter.params,...(type ? { type } : {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});return res;@@ -1083,12 +1033,7 @@ export const getObservationsGroupedByToolName = async (params: {...appliedObservationsFilter.params,},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});return res;@@ -1133,12 +1078,7 @@ export const getObservationsGroupedByCalledToolName = async (params: {...appliedObservationsFilter.params,},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});return res;@@ -1186,12 +1126,7 @@ export const getObservationsGroupedByPromptName = async (params: {...appliedObservationsFilter.params,},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});@@ -1246,12 +1181,7 @@ export const getCostForTraces = async (traceIds,timestamp: convertDateToClickhouseDateTime(timestamp),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return res.length > 0 ? Number(res[0].total_cost) : undefined;};@@ -1277,12 +1207,7 @@ export const deleteObservationsByTraceIds = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "observation",- kind: "delete-preflight",- projectId,- },+ tags: { projectId },});const count = Number(preflight[0]?.cnt ?? 0);@@ -1310,12 +1235,7 @@ export const deleteObservationsByTraceIds = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "observation",- kind: "delete",- projectId,- },+ tags: { projectId },});};@@ -1330,12 +1250,7 @@ export const hasAnyObservation = async (projectId: string) => {const rows = await queryClickhouse<{ 1: number }>({query,params: { projectId },- tags: {- feature: "tracing",- type: "observation",- kind: "hasAny",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -1353,12 +1268,7 @@ export const deleteObservationsByProjectId = async (DELETE FROM observationsWHERE project_id = {projectId: String};`;- const tags = {- feature: "tracing",- type: "observation",- kind: "delete",- projectId,- };+ const tags = { projectId };await commandClickhouse({query,@@ -1390,12 +1300,7 @@ export const hasAnyObservationOlderThan = async (projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "tracing",- type: "observation",- kind: "hasAnyOlderThan",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -1424,12 +1329,7 @@ export const deleteObservationsOlderThanDays = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "observation",- kind: "delete",- projectId,- },+ tags: { projectId },});return true;@@ -1465,12 +1365,7 @@ export const getObservationsWithPromptName = async (? convertDateToClickhouseDateTime(toTimestamp): undefined,},- tags: {- feature: "tracing",- type: "observation",- kind: "list",- projectId,- },+ tags: { projectId },});return rows.map((r) => ({@@ -1545,12 +1440,7 @@ export const getObservationMetricsForPrompts = async (? { toTimestamp: convertDateToClickhouseDateTime(toTimestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return rows.map((r) => ({@@ -1594,12 +1484,7 @@ export const getLatencyAndTotalCostForObservations = async (? { timestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return rows.map((r) => ({@@ -1638,12 +1523,7 @@ export const getLatencyAndTotalCostForObservationsByTraces = async (? { timestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return rows.map((r) => ({@@ -1709,12 +1589,7 @@ export const getObservationsGroupedByTraceId = async (? { timestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return new Map(groupedObservations.map((g) => [g.trace_id, g.observations]));@@ -1746,11 +1621,6 @@ export const getObservationCountsByProjectInCreationInterval = async ({clickhouseConfigs: {request_timeout: 120000, // 2 minutes timeout},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- },});return rows.map((row) => ({@@ -1780,11 +1650,6 @@ export const getObservationCountOfProjectsSinceCreationDate = async ({projectIds,start: convertDateToClickhouseDateTime(start),},- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- },});return Number(rows[0]?.count ?? 0);@@ -1809,12 +1674,7 @@ export const getTraceIdsForObservations = async (projectId,observationIds,},- tags: {- feature: "tracing",- type: "observation",- kind: "list",- projectId,- },+ tags: { projectId },});return rows.map((row) => ({@@ -1876,12 +1736,7 @@ const buildObservationsForBlobStorageExportQuery = (minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},- tags: {- feature: "blobstorage",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},@@ -2013,12 +1868,7 @@ export const getGenerationsForAnalyticsIntegrations = async function* (minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},- tags: {- feature: "posthog",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,...(options.useGraceHash@@ -2117,11 +1967,6 @@ export const getObservationCountsByProjectAndDay = async ({endDate: convertDateToClickhouseDateTime(endDate),},clickhouseConfigs: { request_timeout: 120_000 },- tags: {- feature: "tracing",- type: "observation",- kind: "analytic",- },});return rows.map((row) => ({@@ -2165,12 +2010,7 @@ export const getCostByEvaluatorIds = async (projectId,evaluatorIds,},- tags: {- feature: "evals",- type: "observation",- kind: "analytic",- projectId,- },+ tags: { projectId },});return rows.map((row) => ({@@ -2258,12 +2098,7 @@ export const generateObservationsForPublicApi = async ({limit: pagination.limit,offset: (pagination.page - 1) * pagination.limit,},- tags: {- feature: "tracing",- type: "observation",- projectId,- operation_name: "generateObservationsForPublicApi",- },+ tags: { projectId },},fn: async (input) => {const result = await queryClickhouse<ObservationRecordReadType>({@@ -2301,12 +2136,7 @@ export const getObservationsCountForPublicApi = async ({projectId,input: {params: { ...appliedFilter.params, projectId },- tags: {- feature: "tracing",- type: "observation",- projectId,- operation_name: "getObservationsCountForPublicApi",- },+ tags: { projectId },},fn: async (input) => {const records = await queryClickhouse<{ count: string }>({diff --git a/packages/shared/src/server/repositories/scores-utils.ts b/packages/shared/src/server/repositories/scores-utils.tsindex 2663015374..1d377676f7 100644--- a/packages/shared/src/server/repositories/scores-utils.ts+++ b/packages/shared/src/server/repositories/scores-utils.ts@@ -49,13 +49,7 @@ export const _handleGetScoreById = async ({? { scoreDataTypes: scoreDataTypes.map((d) => d.toString()) }: {}),},- tags: {- feature: "tracing",- type: "score",- kind: "byId",- projectId,- ...(apiVersion ? { api_version: apiVersion } : {}),- },+ tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },preferredClickhouseService,});return rows.map((row) => convertClickhouseScoreToDomain(row)).shift();@@ -99,12 +93,7 @@ export const _handleGetScoresByIds = async ({...(dataTypes ? { dataTypes: dataTypes.map((d) => d.toString()) } : {}),...(source !== undefined ? { source } : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "byId",- projectId,- },+ tags: { projectId },});return rows.map((row) => convertClickhouseScoreToDomain(row));};diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 1d53662e7f..9fd1567838 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -120,12 +120,7 @@ export const searchExistingAnnotationScore = async (sessionId,dataType,},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },});return rows.map((row) => convertClickhouseScoreToDomain(row)).shift();};@@ -173,12 +168,7 @@ export const upsertScore = async (score: Partial<ScoreRecordReadType>) => {table: "scores",records: [score as ScoreRecordReadType],eventBodyMapper: convertClickhouseScoreToDomain,- tags: {- feature: "tracing",- type: "score",- kind: "upsert",- projectId: score.project_id ?? "",- },+ tags: { projectId: score.project_id ?? "" },});};@@ -277,12 +267,7 @@ export const getScoresForSessions = async <offset,dataTypes: LISTABLE_SCORE_TYPES,},- tags: {- feature: "sessions",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },clickhouseConfigs,});@@ -331,12 +316,7 @@ export const getScoresForExperiments = async <limit,offset,},- tags: {- feature: "sessions",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },clickhouseConfigs,});@@ -404,12 +384,7 @@ export const getTraceScoresForDatasetRuns = async (datasetRunIds,dataTypes: AGGREGATABLE_SCORE_TYPES,},- tags: {- feature: "dataset-run-items",- type: "trace-scores",- kind: "list",- projectId,- },+ tags: { projectId },});const includeMetadataPayload = false;@@ -491,12 +466,7 @@ export const getScoresForExperimentItems = async (...eventsSubquery.params,dataTypes: AGGREGATABLE_SCORE_TYPES,},- tags: {- feature: "experiments",- type: "trace-scores",- kind: "list",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -576,12 +546,7 @@ const getScoresForTracesInternal = async <? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }: {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },clickhouseConfigs,preferredClickhouseService,});@@ -715,12 +680,7 @@ export const getScoresForObservations = async <? { minTimestamp: convertDateToClickhouseDateTime(minTimestamp) }: {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },clickhouseConfigs,});@@ -856,12 +816,7 @@ export const getScoresGroupedByNameSourceType = async ({...(eventsFilterRes ? eventsFilterRes.params : {}),...eventsCTEParams,},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },preferredClickhouseService: hasEventsFilters? "EventsReadOnly": "ReadOnly",@@ -913,12 +868,7 @@ export const getNumericScoresGroupedByName = async (projectId: projectId,...(filterRes ? filterRes.params : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});@@ -963,12 +913,7 @@ export const getCategoricalScoresGroupedByName = async (projectId: projectId,...(filterRes ? filterRes.params : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },preferredClickhouseService: "ReadOnly",});@@ -1036,7 +981,6 @@ export const getScoresUiCount = async (props: {const rows = await getScoresUiGeneric<{ count: string }>({select: "count",excludeMetadata: true,- tags: { kind: "count" },...props,});@@ -1103,7 +1047,6 @@ export async function getScoresUiTable<has_metadata: IncludeHasMetadata extends true ? 0 | 1 : never;}>({select: "rows",- tags: { kind: "analytic" },excludeMetadata,includeHasMetadataFlag,clickhouseConfigs,@@ -1233,14 +1176,7 @@ const getScoresUiGeneric = async <T>(props: {limit: limit,offset: offset,},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "score",- projectId,- select: props.select,- operation_name: "getScoresUiGeneric",- },+ tags: { ...(props.tags ?? {}), projectId },},fn: async (input) => {return queryClickhouse<T>({@@ -1439,14 +1375,7 @@ const getScoresUiGenericFromEvents = async <T>(props: {limit,offset,},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "score",- projectId,- select: props.select,- operation_name: "getScoresUiGenericFromEvents",- },+ tags: { ...(props.tags ?? {}), projectId },},fn: async (input) => {return queryClickhouse<T>({@@ -1472,7 +1401,6 @@ export const getScoresUiCountFromEvents = async (props: {const rows = await getScoresUiGenericFromEvents<{ count: string }>({select: "count",excludeMetadata: true,- tags: { kind: "count" },...props,});@@ -1523,7 +1451,6 @@ export async function getScoresUiTableFromEvents(props: {has_metadata: 0 | 1;}>({select: "rows",- tags: { kind: "analytic" },excludeMetadata,includeHasMetadataFlag: true,clickhouseConfigs,@@ -1584,12 +1511,7 @@ export const getScoreNames = async (...(timestampFilterRes ? timestampFilterRes.params : {}),dataTypes: LISTABLE_SCORE_TYPES,},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },});return rows.map((row) => ({@@ -1637,12 +1559,7 @@ export const getScoreStringValues = async (projectId: projectId,...(timestampFilterRes ? timestampFilterRes.params : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },});return rows.map((row) => ({@@ -1666,12 +1583,7 @@ export const deleteScores = async (projectId: string, scoreIds: string[]) => {clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "score",- kind: "delete",- projectId,- },+ tags: { projectId },});};@@ -1693,12 +1605,7 @@ export const deleteScoresByTraceIds = async (clickhouseConfigs: {request_timeout: 120_000, // 2 minutes},- tags: {- feature: "tracing",- type: "score",- kind: "delete",- projectId,- },+ tags: { projectId },});};@@ -1714,12 +1621,7 @@ export const deleteScoresByProjectId = async (DELETE FROM scoresWHERE project_id = {projectId: String};`;- const tags = {- feature: "tracing",- type: "score",- kind: "delete",- projectId,- };+ const tags = { projectId };await commandClickhouse({query,@@ -1751,12 +1653,7 @@ export const hasAnyScoreOlderThan = async (projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "tracing",- type: "score",- kind: "hasAnyOlderThan",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -1785,12 +1682,7 @@ export const deleteScoresOlderThanDays = async (clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: {- feature: "tracing",- type: "score",- kind: "delete",- projectId,- },+ tags: { projectId },});return true;@@ -1829,13 +1721,7 @@ export const getNumericScoreHistogram = async (limit,...(chFilterRes ? chFilterRes.params : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "analytic",- projectId,- operation_name: "getNumericScoreHistogram",- },+ tags: { projectId },},fn: async (input) => {return queryClickhouse<{ value: number }>({@@ -1902,12 +1788,7 @@ export const getAggregatedScoresForPrompts = async (? { toTimestamp: convertDateToClickhouseDateTime(toTimestamp) }: {}),},- tags: {- feature: "tracing",- type: "score",- kind: "analytic",- projectId,- },+ tags: { projectId },});return rows.map((row) => ({@@ -1945,11 +1826,6 @@ export const getScoreCountsByProjectInCreationInterval = async ({clickhouseConfigs: {request_timeout: 120000, // 2 minutes timeout},- tags: {- feature: "tracing",- type: "score",- kind: "analytic",- },});return rows.map((row) => ({@@ -1979,11 +1855,6 @@ export const getScoreCountOfProjectsSinceCreationDate = async ({projectIds,start: convertDateToClickhouseDateTime(start),},- tags: {- feature: "tracing",- type: "score",- kind: "analytic",- },});return Number(rows[0]?.count ?? 0);@@ -2028,12 +1899,7 @@ export const getDistinctScoreNames = async (p: {}: {}),},- tags: {- feature: "tracing",- type: "score",- kind: "list",- projectId,- },+ tags: { projectId },clickhouseConfigs,});@@ -2080,12 +1946,7 @@ const buildScoresForBlobStorageExportQuery = (maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),dataTypes: LISTABLE_SCORE_TYPES,},- tags: {- feature: "blobstorage",- type: "score",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},@@ -2191,12 +2052,7 @@ export const getScoresForAnalyticsIntegrations = async function* (maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),dataTypes: LISTABLE_SCORE_TYPES,},- tags: {- feature: "posthog",- type: "score",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,...(options.useGraceHash@@ -2267,12 +2123,7 @@ export const hasAnyScore = async (projectId: string) => {params: {projectId,},- tags: {- feature: "tracing",- type: "score",- kind: "hasAny",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -2301,12 +2152,7 @@ export const getScoreMetadataById = async (id,...(source !== undefined ? { source } : {}),},- tags: {- feature: "tracing",- type: "score",- kind: "getScoreMetadataById",- projectId,- },+ tags: { projectId },});return rows@@ -2369,11 +2215,6 @@ export const getScoreCountsByProjectAndDay = async ({dataTypes: LISTABLE_SCORE_TYPES,},clickhouseConfigs: { request_timeout: 120_000 },- tags: {- feature: "tracing",- type: "score",- kind: "analytic",- },});return rows.map((row) => ({@@ -2537,15 +2378,7 @@ export const _handleGenerateScoresForPublicApi = async ({}: {}),},- tags: {- feature: "scoring",- type: "score",- projectId,- scoreScope,- operation_name: "_handleGenerateScoresForPublicApi",- includeTrace: includeTrace.toString(),- ...(apiVersion ? { api_version: apiVersion } : {}),- },+ tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },},fn: async (input) => {const records = await queryClickhouse<@@ -2586,7 +2419,6 @@ export const _handleGetScoresCountForPublicApi = async ({scoresFilter,tracesFilter,scoreScope,- includeTrace,needsTraceJoin,apiVersion,}: {@@ -2639,15 +2471,7 @@ export const _handleGetScoresCountForPublicApi = async ({...appliedTracesFilter.params,projectId,},- tags: {- feature: "scoring",- type: "score",- projectId,- scoreScope,- operation_name: "_handleGetScoresCountForPublicApi",- includeTrace: includeTrace.toString(),- ...(apiVersion ? { api_version: apiVersion } : {}),- },+ tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },},fn: async (input) => {const records = await queryClickhouse<{ count: string }>({@@ -3034,13 +2858,7 @@ export async function listScoresV3ForPublicApi(}),...filterParams,},- tags: {- feature: "scoring",- type: "score",- projectId: params.projectId,- operation_name: "listScoresV3ForPublicApi",- api_version: "v3",- },+ tags: { projectId: params.projectId },},fn: async (input) => {const records = await queryClickhouse<ScoreRecordReadType>({diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 4b13a001f6..87685ec389 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -157,13 +157,7 @@ export const checkTraceExistsAndGetTimestamp = async ({? { exactTimestamp: convertDateToClickhouseDateTime(exactTimestamp) }: {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "exists",- projectId,- operation_name: "checkTraceExistsAndGetTimestamp",- },+ tags: { projectId },timestamp: timestamp ?? exactTimestamp,},fn: async (input) => {@@ -194,7 +188,6 @@ export const checkTraceExistsAndGetTimestamp = async ({}>({query,params: input.params,- tags: input.tags,});return {@@ -221,12 +214,7 @@ 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 ?? "",- },+ tags: { projectId: trace.project_id ?? "" },});};@@ -247,13 +235,7 @@ export const getTracesByIds = async (? convertDateToClickhouseDateTime(timestamp): null,},- tags: {- feature: "tracing",- type: "trace",- kind: "byId",- projectId,- operation_name: "getTracesByIds",- },+ tags: { projectId },clickhouseConfigs,},fn: (input) => {@@ -296,13 +278,7 @@ export const getTracesBySessionId = async (? convertDateToClickhouseDateTime(timestamp): null,},- tags: {- feature: "tracing",- type: "trace",- kind: "list",- projectId,- operation_name: "getTracesBySessionId",- },+ tags: { projectId },timestamp,},fn: (input) => {@@ -360,13 +336,7 @@ export const hasAnyTrace = async (projectId: string) => {projectId,input: {projectId,- tags: {- feature: "tracing",- type: "trace",- kind: "hasAny",- projectId,- operation_name: "hasAnyTrace",- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -426,12 +396,6 @@ export const getTraceCountsByProjectInCreationInterval = async ({start: convertDateToClickhouseDateTime(start),end: convertDateToClickhouseDateTime(end),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- operation_name: "getTraceCountsByProjectInCreationInterval",- },timestamp: start,},fn: async (input) => {@@ -452,7 +416,6 @@ export const getTraceCountsByProjectInCreationInterval = async ({clickhouseConfigs: {request_timeout: 120000, // 2 minutes timeout},- tags: input.tags,},);@@ -479,12 +442,6 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({projectIds,start: convertDateToClickhouseDateTime(start),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- operation_name: "getTraceCountOfProjectsSinceCreationDate",- },timestamp: start,},fn: async (input) => {@@ -499,7 +456,6 @@ export const getTraceCountOfProjectsSinceCreationDate = async ({const rows = await queryClickhouse<{ count: string }>({query,params: input.params,- tags: input.tags,});return Number(rows[0]?.count ?? 0);@@ -522,7 +478,6 @@ export const getTraceByIdFromTracesTable = async ({timestamp,fromTimestamp,renderingProps = DEFAULT_RENDERING_PROPS,- clickhouseFeatureTag = "tracing",preferredClickhouseService,excludeInputOutput = false,excludeMetadata = false,@@ -532,7 +487,6 @@ export const getTraceByIdFromTracesTable = async ({timestamp?: Date;fromTimestamp?: Date;renderingProps?: RenderingProps;- clickhouseFeatureTag?: string;preferredClickhouseService?: PreferredClickhouseService;/** When true, sets input/output columns to empty in the query to reduce database load */excludeInputOutput?: boolean;@@ -553,13 +507,7 @@ export const getTraceByIdFromTracesTable = async ({? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }: {}),},- tags: {- feature: clickhouseFeatureTag,- type: "trace",- kind: "byId",- projectId,- operation_name: "getTraceById",- },+ tags: { projectId },},fn: (input) => {const inputColumn = excludeInputOutput@@ -650,13 +598,7 @@ export const getTracesGroupedByName = async (projectId,...(timestampFilterRes ? timestampFilterRes.params : {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getTracesGroupedByName",- },+ tags: { projectId },},fn: async (input) => {// We mainly use queries like this to retrieve filter options.@@ -725,13 +667,7 @@ export const getTracesGroupedBySessionId = async (...(tracesFilterRes ? tracesFilterRes.params : {}),...(searchQuery ? search.params : {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getTracesGroupedBySessionId",- },+ tags: { projectId },},fn: async (input) => {// We mainly use queries like this to retrieve filter options.@@ -802,13 +738,7 @@ export const getTracesGroupedByUsers = async (...(tracesFilterRes ? tracesFilterRes.params : {}),...(searchQuery ? search.params : {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getTracesGroupedByUsers",- },+ tags: { projectId },},fn: async (input) => {// We mainly use queries like this to retrieve filter options.@@ -867,13 +797,7 @@ export const getTracesGroupedByTags = async (props: GroupedTracesQueryProp) => {projectId,...(filterRes ? filterRes.params : {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getTracesGroupedByTags",- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -918,13 +842,7 @@ export const getTracesIdentifierForSessionFromTracesTable = async (projectId,sessionId,},- tags: {- feature: "tracing",- type: "trace",- kind: "list",- projectId,- operation_name: "getTracesIdentifierForSession",- },+ tags: { projectId },},fn: (input) => {const query = `@@ -951,7 +869,6 @@ export const getTracesIdentifierForSessionFromTracesTable = async (}>({query,params: input.params,- tags: input.tags,});},});@@ -974,12 +891,7 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {projectId,traceIds,},- tags: {- feature: "tracing",- type: "trace",- kind: "delete",- projectId,- },+ tags: { projectId },},fn: async (input) => {// Pre-flight query with time bounds computed@@ -1000,7 +912,7 @@ export const deleteTraces = async (projectId: string, traceIds: string[]) => {clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,},- tags: { ...input.tags, kind: "delete-preflight" },+ tags: { ...input.tags },});const count = Number(preflight[0]?.cnt ?? 0);@@ -1051,12 +963,7 @@ export const hasAnyTraceOlderThan = async (projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "tracing",- type: "trace",- kind: "hasAnyOlderThan",- projectId,- },+ tags: { projectId },});return rows.length > 0;@@ -1079,12 +986,7 @@ export const deleteTracesOlderThanDays = async (projectId,cutoffDate: convertDateToClickhouseDateTime(beforeDate),},- tags: {- feature: "tracing",- type: "trace",- kind: "delete",- projectId,- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -1121,12 +1023,7 @@ export const deleteTracesByProjectId = async (params: {projectId,},- tags: {- feature: "tracing",- type: "trace",- kind: "delete",- projectId,- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -1154,13 +1051,7 @@ export const hasAnyUser = async (projectId: string) => {projectId,input: {projectId,- tags: {- feature: "tracing",- type: "user",- kind: "hasAny",- projectId,- operation_name: "hasAnyUser",- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -1216,13 +1107,7 @@ export const getTotalUserCount = async (...tracesFilterRes.params,...search.params,},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getTotalUserCount",- },+ tags: { projectId },},fn: async (input) => {const query = `@@ -1353,13 +1238,7 @@ export const getUserMetrics = async (}: {}),},- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- projectId,- operation_name: "getUserMetrics",- },+ tags: { projectId },},fn: async (input) => {const rows = await queryClickhouse<{@@ -1436,12 +1315,7 @@ const buildTracesForBlobStorageExportQuery = (minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},- tags: {- feature: "blobstorage",- type: "trace",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,},@@ -1529,12 +1403,7 @@ export const getTracesForAnalyticsIntegrations = async function* (minTimestamp: convertDateToClickhouseDateTime(minTimestamp),maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),},- tags: {- feature: "posthog",- type: "trace",- kind: "analytic",- projectId,- },+ tags: { projectId },clickhouseConfigs: {request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,...(options.useGraceHash@@ -1590,12 +1459,6 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {params: {traceIds,},- tags: {- feature: "tracing",- type: "trace",- kind: "list",- operation_name: "getTracesByIdsForAnyProject",- },},fn: async (input) => {const query = `@@ -1610,7 +1473,6 @@ export const getTracesByIdsForAnyProject = async (traceIds: string[]) => {}>({query,params: input.params,- tags: input.tags,});return records.map((record) => ({@@ -1716,11 +1578,6 @@ export const getTraceCountsByProjectAndDay = async ({endDate: convertDateToClickhouseDateTime(endDate),},clickhouseConfigs: { request_timeout: 120_000 },- tags: {- feature: "tracing",- type: "trace",- kind: "analytic",- },});return rows.map((row) => ({@@ -2147,13 +2004,7 @@ export const generateTracesForPublicApi = async ({projectId,input: {params,- tags: {- feature: "tracing",- type: "trace",- kind: "public-api",- projectId,- operation_name: "getTracesForPublicApi",- },+ tags: { projectId },fromTimestamp: fromTimeFilter?.value ?? undefined,preferredClickhouseService: "ReadOnly",},@@ -2242,13 +2093,7 @@ export const getTracesCountForPublicApi = async ({projectId,input: {params,- tags: {- feature: "tracing",- type: "trace",- kind: "count",- projectId,- operation_name: "getTracesCountForPublicApi",- },+ tags: { projectId },timestamp,},fn: async (input) => {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 5676204814..2c2a83ac69 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@@ -78,12 +78,7 @@ export const getSessionTracesFromEvents = async (props: {projectId: props.projectId,sessionId: props.sessionId,},- tags: {- feature: "tracing",- type: "sessions-traces",- projectId: props.projectId,- operation_name: "getSessionTracesFromEvents",- },+ tags: { projectId: props.projectId },},fn: async (input) => {return queryClickhouse<{@@ -124,7 +119,6 @@ export const getSessionsTableCountFromEvents = async (props: {orderBy: props.orderBy,limit: props.limit,page: props.page,- tags: { kind: "count" },});return rows.length > 0 ? Number(rows[0].count) : 0;@@ -145,7 +139,6 @@ export const getSessionsTableFromEvents = async (props: {orderBy: props.orderBy,limit: props.limit,page: props.page,- tags: { kind: "list" },});return rows.map((row) => ({@@ -175,7 +168,6 @@ export const getSessionsWithMetricsFromEvents = async (props: {limit: props.limit,page: props.page,clickhouseConfigs: props.clickhouseConfigs,- tags: { kind: "analytic_events" },},);@@ -326,13 +318,7 @@ const getSessionsTableFromEventsGeneric = async <T>(...params,projectId,},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "sessions-table",- projectId,- operation_name: `getSessionsTableFromEventsGeneric-${select}`,- },+ tags: { ...(props.tags ?? {}), projectId },},fn: async (input) => {return queryClickhouse<T>({diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.tsindex 0f931e7a91..1ea45d2128 100644--- a/packages/shared/src/server/services/sessions-ui-table-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts@@ -56,7 +56,6 @@ 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;@@ -76,7 +75,6 @@ export const getSessionsTable = async (props: {orderBy: props.orderBy,limit: props.limit,page: props.page,- tags: { kind: "list" },});return rows.map((row) => ({@@ -101,7 +99,6 @@ export const getSessionsWithMetrics = async (props: {limit: props.limit,page: props.page,clickhouseConfigs: props.clickhouseConfigs,- tags: { kind: "analytic" },});return rows.map((row) => ({@@ -395,13 +392,7 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {}: {}),},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "sessions-table",- projectId,- operation_name: `getSessionsTableGeneric-${select}`,- },+ tags: { ...(props.tags ?? {}), projectId },},fn: async (input) => {return queryClickhouse<T>({diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex b811faf398..bb7670a7a2 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -479,13 +479,7 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {...scoresFilterRes.params,...search.params,},- tags: {- ...(props.tags ?? {}),- feature: "tracing",- type: "traces-table",- projectId,- operation_name: "getTracesTableGeneric",- },+ tags: { ...(props.tags ?? {}), projectId },clickhouseConfigs,});@@ -505,7 +499,6 @@ export const getTracesTableCount = async (props: {}) => {const countRows = await getTracesTableGeneric({select: "count",- tags: { kind: "count" },...props,});@@ -527,7 +520,6 @@ export const getTracesTableMetrics = async (props: {}): Promise<Array<Omit<TracesMetricsUiReturnType, "scores">>> => {const countRows = await getTracesTableGeneric({select: "metrics",- tags: { kind: "analytic" },...props,});@@ -556,7 +548,6 @@ export const getTracesTable = async (p: {} = p;const rows = await getTracesTableGeneric({select: "rows",- tags: { kind: "list" },projectId,filter,searchQuery,@@ -592,7 +583,6 @@ export const getTraceIdentifiers = async (props: {} = props;const identifiers = await getTracesTableGeneric({select: "identifiers",- tags: { kind: "list" },projectId,filter,searchQuery,diff --git a/web/src/__tests__/server/build-trace-export.servertest.ts b/web/src/__tests__/server/build-trace-export.servertest.tsindex 453ac0ac8f..6e44f4b49a 100644--- a/web/src/__tests__/server/build-trace-export.servertest.ts+++ b/web/src/__tests__/server/build-trace-export.servertest.ts@@ -200,7 +200,6 @@ describe("buildTraceExport", () => {truncated: true,shouldJsonParse: false,},- clickhouseFeatureTag: "tracing-download",});expect(mockGetObservationsCountFromEventsTable).toHaveBeenCalledWith({projectId,diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.tsindex a22e3a1cea..2c32c6f819 100644--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts@@ -61,11 +61,6 @@ const matchingIds = async (opts: {`,params: search.params,preferredClickhouseService: "EventsReadOnly",- tags: {- feature: "clickhouse-search-condition-test",- type: "events",- kind: "test",- },});return rows.map((row) => row.id);@@ -191,11 +186,6 @@ describe("clickhouseSearchCondition", () => {...search.params,},preferredClickhouseService: "EventsReadOnly",- tags: {- feature: "clickhouse-search-condition-test",- type: "events",- kind: "test",- },}),).resolves.toEqual([{ count: 0 }]);});@@ -284,11 +274,6 @@ describe("clickhouseSearchCondition", () => {escapedSpanId,},preferredClickhouseService: "EventsReadOnly",- tags: {- feature: "clickhouse-search-condition-test",- type: "events",- kind: "test",- },});expect(stored).toHaveLength(2);diff --git a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.tsindex d253817421..7f4a2e40c4 100644--- a/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts+++ b/web/src/__tests__/server/code-eval-test-run-trpc.servertest.ts@@ -216,12 +216,7 @@ maybe("evals.testRunCodeEval", () => {const scoreCount = await queryClickhouse<{ count: string }>({query: `SELECT count() as count FROM scores WHERE project_id = {projectId: String}`,params: { projectId: project.id },- tags: {- feature: "evals",- type: "scores",- kind: "testRunCodeEvalNoScores",- projectId: project.id,- },+ tags: { projectId: project.id },});expect(Number(scoreCount[0]?.count ?? 0)).toBe(0);@@ -534,12 +529,7 @@ maybe("evals.testRunCodeEval", () => {}>({query: `SELECT environment, metadata['code_eval_source_code'] as sourceCode FROM traces WHERE project_id = {projectId: String} AND id = {traceId: String} LIMIT 1`,params: { projectId: project.id, traceId: executionTraceId },- tags: {- feature: "evals",- type: "traces",- kind: "testRunCodeEvalTrace",- projectId: project.id,- },+ tags: { projectId: project.id },});return rows[0];};diff --git a/web/src/__tests__/server/fts-rewrites.servertest.ts b/web/src/__tests__/server/fts-rewrites.servertest.tsindex 014e4d87e5..0d3f778d92 100644--- a/web/src/__tests__/server/fts-rewrites.servertest.ts+++ b/web/src/__tests__/server/fts-rewrites.servertest.ts@@ -89,11 +89,6 @@ const matchingIds = async (filter: FilterResult) => {`,params: filter.params,preferredClickhouseService: "EventsReadOnly",- tags: {- feature: "fts-rewrites-test",- type: "events",- kind: "test",- },});return rows.map((row) => row.id);diff --git a/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts b/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.tsindex e4690da802..060bac321a 100644--- a/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts+++ b/web/src/__tests__/server/repositories/clickhouse-resource-errors.servertest.ts@@ -16,7 +16,11 @@ describe("ClickHouse Resource Error Handling", () => {res = await queryClickhouse<any>({query: `SELECT throwIf(number >= 2, 'memory limit exceeded: would use 10.23 GiB') AS v FROM system.numbers LIMIT 2000`,clickhouseSettings: { max_block_size: `${blockSize}` },- tags: { test: "marker" },+ tags: {+ surface: "trpc",+ route: "test.resource-error",+ projectId: "project-1",+ },});fail("Should have thrown an error, observed instead " +@@ -25,7 +29,12 @@ describe("ClickHouse Resource Error Handling", () => {} catch (error: any) {expect(error).toBeInstanceOf(ClickHouseResourceError);expect(error.errorType).toBe("MEMORY_LIMIT");- expect(error.tags?.test).toBe("marker");+ expect(error.tags).toEqual({+ tag_schema_version: "1",+ surface: "trpc",+ route: "test.resource-error",+ projectId: "project-1",+ });}});});diff --git a/web/src/__tests__/server/traces-trpc-events-only.servertest.ts b/web/src/__tests__/server/traces-trpc-events-only.servertest.tsindex 68c15e2d82..cf1588c82f 100644--- a/web/src/__tests__/server/traces-trpc-events-only.servertest.ts+++ b/web/src/__tests__/server/traces-trpc-events-only.servertest.ts@@ -124,7 +124,6 @@ maybe("traces trpc (events_only write mode)", () => {const legacyTrace = await getTraceByIdFromTracesTable({traceId,projectId,- clickhouseFeatureTag: "tracing-test",});expect(legacyTrace).toBeUndefined();@@ -185,7 +184,6 @@ maybe("traces trpc (events_only write mode)", () => {const legacyTrace = await getTraceByIdFromTracesTable({traceId,projectId,- clickhouseFeatureTag: "tracing-test",});expect(legacyTrace).toBeUndefined();diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.tsindex 671c2ca654..1d31fa124e 100644--- a/web/src/__tests__/server/traces-trpc.servertest.ts+++ b/web/src/__tests__/server/traces-trpc.servertest.ts@@ -749,7 +749,6 @@ describe("traces trpc", () => {const cleanTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,- clickhouseFeatureTag: "tracing-test",});expect(cleanTrace).toBeDefined();@@ -770,7 +769,6 @@ describe("traces trpc", () => {const updatedTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,- clickhouseFeatureTag: "tracing-test",});expect(updatedTrace).toBeDefined();@@ -830,7 +828,6 @@ describe("traces trpc", () => {const cleanTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,- clickhouseFeatureTag: "tracing-test",});expect(cleanTrace).toBeDefined();@@ -851,7 +848,6 @@ describe("traces trpc", () => {const updatedTrace = await getTraceByIdFromTracesTable({traceId: trace.id,projectId,- clickhouseFeatureTag: "tracing-test",});expect(updatedTrace).toBeDefined();diff --git a/web/src/__tests__/server/unit/langfuse-context-propagation.servertest.ts b/web/src/__tests__/server/unit/langfuse-context-propagation.servertest.tsindex 9eb9c53e59..23786a66be 100644--- a/web/src/__tests__/server/unit/langfuse-context-propagation.servertest.ts+++ b/web/src/__tests__/server/unit/langfuse-context-propagation.servertest.ts@@ -57,4 +57,26 @@ describe("Langfuse context propagation", () => {expect(baggage?.getEntry("langfuse.api_key.id")?.value).toBe("api-key-1");});});++ it("adds clickhouse request metadata to context baggage", () => {+ opentelemetry.context.with(opentelemetry.ROOT_CONTEXT, () => {+ const ctx = contextWithLangfuseProps({+ projectId: "project-1",+ clickhouse: {+ surface: "publicapi",+ route: "GET /api/public/traces",+ },+ });++ const baggage = opentelemetry.propagation.getBaggage(ctx);++ expect(baggage?.getEntry("langfuse.project.id")?.value).toBe("project-1");+ expect(baggage?.getEntry("langfuse.clickhouse.surface")?.value).toBe(+ "publicapi",+ );+ expect(baggage?.getEntry("langfuse.clickhouse.route")?.value).toBe(+ "GET /api/public/traces",+ );+ });+ });});diff --git a/web/src/__tests__/server/withMiddlewares.servertest.ts b/web/src/__tests__/server/withMiddlewares.servertest.tsindex 3a03de377f..69a3bfc658 100644--- a/web/src/__tests__/server/withMiddlewares.servertest.ts+++ b/web/src/__tests__/server/withMiddlewares.servertest.ts@@ -223,7 +223,11 @@ describe("withMiddlewares error handling", () => {const resourceError = new ClickHouseResourceError("MEMORY_LIMIT",originalError,- { type: "events", kind: "publicApiRows" },+ {+ tag_schema_version: "1",+ surface: "publicapi",+ route: "GET /api/public/test",+ },);const handler = withMiddlewares({@@ -247,7 +251,11 @@ describe("withMiddlewares error handling", () => {"ClickHouse resource limit exceeded",expect.objectContaining({errorType: "MEMORY_LIMIT",- tags: { type: "events", kind: "publicApiRows" },+ tags: {+ tag_schema_version: "1",+ surface: "publicapi",+ route: "GET /api/public/test",+ },}),);});diff --git a/web/src/features/mcp/server/mcpServer.ts b/web/src/features/mcp/server/mcpServer.tsindex ce593e0388..118282eb13 100644--- a/web/src/features/mcp/server/mcpServer.ts+++ b/web/src/features/mcp/server/mcpServer.ts@@ -19,7 +19,8 @@ import {} from "@modelcontextprotocol/sdk/types.js";import type { ServerContext } from "../types";import { toolRegistry } from "./registry";-import { logger } from "@langfuse/shared/src/server";+import { contextWithLangfuseProps, logger } from "@langfuse/shared/src/server";+import { context as otelContext } from "@opentelemetry/api";const MCP_SERVER_NAME = "langfuse";@@ -92,7 +93,17 @@ export function createMcpServer(context: ServerContext): Server {// Execute handler with context// Handler performs validation and error handling via defineTool wrapper- const result = await registeredTool.handler(args, context);+ const clickHouseCtx = contextWithLangfuseProps({+ projectId: context.projectId,+ apiKeyId: context.apiKeyId,+ clickhouse: {+ surface: "mcp",+ route: name,+ },+ });+ const result = await otelContext.with(clickHouseCtx, () =>+ registeredTool.handler(args, context),+ );return {content: [diff --git a/web/src/features/public-api/server/clickHouseRequestTags.ts b/web/src/features/public-api/server/clickHouseRequestTags.tsnew file mode 100644index 0000000000..12262fc4d3--- /dev/null+++ b/web/src/features/public-api/server/clickHouseRequestTags.ts@@ -0,0 +1,15 @@+import { type NextApiRequest } from "next";++export const clickHouseRouteForRequest = (req: NextApiRequest) => {+ const method = req.method ?? "UNKNOWN";+ const rawUrl = req.url ?? "";++ try {+ const pathname = rawUrl+ ? new URL(rawUrl, "http://langfuse.local").pathname+ : "";+ return `${method} ${pathname}`;+ } catch {+ return `${method} ${rawUrl}`;+ }+};diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 08d47fb5d8..61ef557e35 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -25,6 +25,7 @@ import {unstablePublicEvalsErrorContract,type PublicApiErrorContract,} from "@/src/features/public-api/server/unstable-public-api-error-contract";+import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";/** Access levels that can be accepted by project-scoped API routes. */type RouteAccessLevel = Exclude<ApiAccessLevel, "organization">;@@ -433,6 +434,10 @@ export const createAuthedProjectAPIRoute = <headers: req.headers,projectId: auth.scope.projectId,apiKeyId: auth.scope.apiKeyId,+ clickhouse: {+ surface: "publicapi",+ route: clickHouseRouteForRequest(req),+ },});return opentelemetry.context.with(ctx, async () => {const response = await routeConfig.fn({diff --git a/web/src/features/public-api/server/health-service.ts b/web/src/features/public-api/server/health-service.tsindex a163807b5d..31f9ec0a7b 100644--- a/web/src/features/public-api/server/health-service.ts+++ b/web/src/features/public-api/server/health-service.ts@@ -67,10 +67,6 @@ export const runHealthCheck = async ({LIMIT 1`,params,- tags: {- feature: "health-check",- type: "event",- },}),});@@ -98,10 +94,6 @@ export const runHealthCheck = async ({LIMIT 1`,params,- tags: {- feature: "health-check",- type: "trace",- },}),});@@ -116,10 +108,6 @@ export const runHealthCheck = async ({params: {now: clickhouseNow,},- tags: {- feature: "health-check",- type: "observation",- },});if (traces.length === 0 || observations.length === 0) {diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.tsindex 4b70c5829f..4d769a410d 100644--- a/web/src/features/public-api/server/withMiddlewares.ts+++ b/web/src/features/public-api/server/withMiddlewares.ts@@ -22,6 +22,7 @@ import {unstablePublicEvalsErrorContract,type PublicApiErrorContract,} from "@/src/features/public-api/server/unstable-public-api-error-contract";+import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";// Exported to silence @typescript-eslint/no-unused-vars v8 warning// (used for type extraction via typeof, which is a legitimate pattern)@@ -87,6 +88,10 @@ export function withMiddlewares(return async (req: NextApiRequest, res: NextApiResponse) => {const ctx = contextWithLangfuseProps({headers: req.headers,+ clickhouse: {+ surface: "publicapi",+ route: clickHouseRouteForRequest(req),+ },});return opentelemetry.context.with(ctx, async () => {diff --git a/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts b/web/src/features/score-analytics/server/scoreAnalyticsRouter.tsindex ed11626191..89139d6f2c 100644--- a/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts+++ b/web/src/features/score-analytics/server/scoreAnalyticsRouter.ts@@ -354,12 +354,7 @@ export const scoreAnalyticsRouter = createTRPCRouter({toTimestamp: convertDateToClickhouseDateTime(toTimestamp),nBins,},- tags: {- feature: "scores",- type: "analytics",- kind: "comparison",- projectId,- },+ tags: { projectId },clickhouseSettings: {// Enable short-circuit evaluation to prevent correlation errors// This ensures if() conditions are evaluated before function callsdiff --git a/web/src/features/traces/server/buildTraceExport.ts b/web/src/features/traces/server/buildTraceExport.tsindex 9ba64edd81..453a5eeb7a 100644--- a/web/src/features/traces/server/buildTraceExport.ts+++ b/web/src/features/traces/server/buildTraceExport.ts@@ -106,7 +106,6 @@ async function getAuthorizedTrace(params: {truncated: true,shouldJsonParse: false,},- clickhouseFeatureTag: "tracing-download",});if (!clickhouseTrace) {diff --git a/web/src/features/web-callouts/server/targetValidation.ts b/web/src/features/web-callouts/server/targetValidation.tsindex 94de00e5a0..d3d8e43fcb 100644--- a/web/src/features/web-callouts/server/targetValidation.ts+++ b/web/src/features/web-callouts/server/targetValidation.ts@@ -163,7 +163,6 @@ const tryGetTrace = async ({projectId,excludeInputOutput: true,excludeMetadata: true,- clickhouseFeatureTag: "web-callouts",});} catch (error) {logger.warn("Failed to validate web callout trace via traces table", {@@ -190,7 +189,6 @@ const tryGetTraceFromEvents = async ({truncated: true,shouldJsonParse: false,},- clickhouseFeatureTag: "web-callouts",});} catch (error) {logger.warn("Failed to validate web callout trace via events table", {diff --git a/web/src/pages/api/public/health.ts b/web/src/pages/api/public/health.tsindex 6ca2a84ea5..ec199159bf 100644--- a/web/src/pages/api/public/health.ts+++ b/web/src/pages/api/public/health.ts@@ -1,8 +1,14 @@import { VERSION } from "@/src/constants";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";import { runHealthCheck } from "@/src/features/public-api/server/health-service";import { telemetry } from "@/src/features/telemetry";-import { logger, traceException } from "@langfuse/shared/src/server";+import {+ contextWithLangfuseProps,+ logger,+ traceException,+} from "@langfuse/shared/src/server";+import * as opentelemetry from "@opentelemetry/api";import { type NextApiRequest, type NextApiResponse } from "next";export default async function handler(@@ -12,10 +18,20 @@ export default async function handler(try {await runMiddleware(req, res, cors);await telemetry();- const result = await runHealthCheck({- failIfNoRecentEvents: req.query.failIfNoRecentEvents === "true",- failIfDatabaseUnavailable: req.query.failIfDatabaseUnavailable === "true",+ const ctx = contextWithLangfuseProps({+ headers: req.headers,+ clickhouse: {+ surface: "publicapi",+ route: clickHouseRouteForRequest(req),+ },});+ const result = await opentelemetry.context.with(ctx, () =>+ runHealthCheck({+ failIfNoRecentEvents: req.query.failIfNoRecentEvents === "true",+ failIfDatabaseUnavailable:+ req.query.failIfDatabaseUnavailable === "true",+ }),+ );return res.status(result.isHealthy ? 200 : 503).json({status: result.status,diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex c84639b31a..771d36a98a 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -11,6 +11,7 @@ import {markProjectIngestFailure,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";+import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";import { jsonSchema } from "@langfuse/shared";import { isPrismaException } from "@/src/utils/exceptions";import {@@ -104,6 +105,10 @@ export default async function handler(headers: req.headers,projectId,apiKeyId: authCheck.scope.apiKeyId,+ clickhouse: {+ surface: "publicapi",+ route: clickHouseRouteForRequest(req),+ },});// Execute the rest of the handler within the contextreturn opentelemetry.context.with(ctx, async () => {diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 3707d13ba8..1210ca11df 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -63,7 +63,6 @@ export default withMiddlewares(const trace = await getTraceById({traceId,projectId: auth.scope.projectId,- clickhouseFeatureTag: "tracing-public-api",preferredClickhouseService: "ReadOnly",excludeInputOutput: !includeIO,excludeMetadata: !includeIO,diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex b6da94361a..7da2117f36 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -508,7 +508,6 @@ export const scoresRouter = createTRPCRouter({const clickhouseTrace = await getTraceById({traceId: inflatedParams.traceId,projectId: input.projectId,- clickhouseFeatureTag: "annotations-trpc",});if (!clickhouseTrace) {@@ -678,7 +677,6 @@ export const scoresRouter = createTRPCRouter({const clickhouseTrace = await getTraceById({traceId: inflatedParams.traceId,projectId: input.projectId,- clickhouseFeatureTag: "annotations-trpc",});if (!clickhouseTrace) {@@ -937,7 +935,6 @@ export const scoresRouter = createTRPCRouter({const clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,- clickhouseFeatureTag: "annotations-trpc",});if (!clickhouseTrace) {diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 90d5e87274..fb812f1ee8 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -517,7 +517,6 @@ export const traceRouter = createTRPCRouter({const clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,- clickhouseFeatureTag: "tracing-trpc",});if (clickhouseTrace) {trace = clickhouseTrace;@@ -576,7 +575,6 @@ export const traceRouter = createTRPCRouter({const clickhouseTrace = await getTraceById({traceId: input.traceId,projectId: input.projectId,- clickhouseFeatureTag: "tracing-trpc",});if (!clickhouseTrace) {logger.error(diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 189246eab6..940d694892 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -223,6 +223,10 @@ const withOtelInstrumentation = t.middleware(async (opts) => {headers: opts.ctx.headers,userId: opts.ctx.session?.user?.id,projectId: (actualInput as Record<string, string>)?.projectId,+ clickhouse: {+ surface: "trpc",+ route: opts.path,+ },});// Execute the next middleware/procedure with our context@@ -505,7 +509,6 @@ const enforceTraceAccess = t.middleware(async (opts) => {truncated: verbosity === "truncated",shouldJsonParse: false, // we do not want to parse the input/output for tRPC},- clickhouseFeatureTag: "tracing-trpc",});if (!clickhouseTrace) {diff --git a/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts b/worker/src/__tests__/clickhouseExecRawParquet.integration.test.tsindex 8c5b3f5f4c..fe8d3b96a0 100644--- a/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts+++ b/worker/src/__tests__/clickhouseExecRawParquet.integration.test.ts@@ -27,7 +27,6 @@ describe("queryClickhouseExecRaw — FORMAT Parquet", () => {query: "SELECT number AS n FROM numbers(1000)",format: "Parquet",clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,- tags: { feature: "test", kind: "analytic" },});const buffer = await collect(stream);@@ -53,7 +52,6 @@ describe("queryClickhouseExecRaw — FORMAT Parquet", () => {...BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,output_format_parquet_row_group_size: "256",},- tags: { feature: "test", kind: "analytic" },});return collect(stream);};diff --git a/worker/src/__tests__/workerManager.test.ts b/worker/src/__tests__/workerManager.test.tsnew file mode 100644index 0000000000..182f11b777--- /dev/null+++ b/worker/src/__tests__/workerManager.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import { WorkerManager } from "../queues/workerManager";++const extractProjectId = (data: unknown): string | undefined =>+ (+ WorkerManager as unknown as {+ extractProjectId(job: { data: unknown }): string | undefined;+ }+ ).extractProjectId({ data });++describe("WorkerManager", () => {+ describe("extractProjectId", () => {+ it("extracts project ids from queue payloads", () => {+ expect(+ extractProjectId({+ payload: { projectId: "project-from-payload" },+ }),+ ).toBe("project-from-payload");+ });++ it("extracts ingestion project ids from payload auth scope", () => {+ expect(+ extractProjectId({+ payload: {+ authCheck: {+ scope: { projectId: "project-from-auth-scope" },+ },+ },+ }),+ ).toBe("project-from-auth-scope");+ });++ it("ignores non-contract top-level project ids", () => {+ expect(+ extractProjectId({+ projectId: "top-level-project",+ }),+ ).toBeUndefined();+ });++ it("ignores non-contract top-level auth scope project ids", () => {+ expect(+ extractProjectId({+ authCheck: {+ scope: { projectId: "top-level-auth-project" },+ },+ }),+ ).toBeUndefined();+ });+ });+});diff --git a/worker/src/features/batch-data-retention-cleaner/index.ts b/worker/src/features/batch-data-retention-cleaner/index.tsindex bd9b341b38..592444843f 100644--- a/worker/src/features/batch-data-retention-cleaner/index.ts+++ b/worker/src/features/batch-data-retention-cleaner/index.ts@@ -335,11 +335,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {}>({query,params,- tags: {- feature: "batch-data-retention-cleaner",- table: this.tableName,- operation: "count-chunk",- },});// Build maps from the result@@ -390,11 +385,6 @@ export class BatchDataRetentionCleaner extends PeriodicExclusiveRunner {request_timeout:env.LANGFUSE_BATCH_DATA_RETENTION_CLEANER_DELETE_TIMEOUT_MS,},- tags: {- feature: "batch-data-retention-cleaner",- table: this.tableName,- operation: "delete",- },});}}diff --git a/worker/src/features/batch-project-blob-cleaner/index.ts b/worker/src/features/batch-project-blob-cleaner/index.tsindex 082ff338f5..5faa7573a4 100644--- a/worker/src/features/batch-project-blob-cleaner/index.ts+++ b/worker/src/features/batch-project-blob-cleaner/index.ts@@ -156,10 +156,6 @@ export class BatchProjectBlobCleaner extends PeriodicExclusiveRunner {GROUP BY project_id`,params: { projectIds },- tags: {- feature: "batch-project-blob-cleaner",- operation: "count",- },});const counts = new Map<string, number>();diff --git a/worker/src/features/batch-project-cleaner/index.ts b/worker/src/features/batch-project-cleaner/index.tsindex 266fe550f6..7fc3033179 100644--- a/worker/src/features/batch-project-cleaner/index.ts+++ b/worker/src/features/batch-project-cleaner/index.ts@@ -213,11 +213,6 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {const results = await queryClickhouse<ProjectCount>({query,params: { projectIds },- tags: {- feature: "batch-project-cleaner",- table: this.tableName,- operation: "count",- },});const counts = new Map<string, number>();@@ -244,11 +239,6 @@ export class BatchProjectCleaner extends PeriodicExclusiveRunner {clickhouseConfigs: {request_timeout: env.LANGFUSE_BATCH_PROJECT_CLEANER_DELETE_TIMEOUT_MS,},- tags: {- feature: "batch-project-cleaner",- table: this.tableName,- operation: "delete",- },});}}diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex 14e092a4bb..0e9ddfdf69 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -221,12 +221,7 @@ export const getEventsStream = async (props: {query,params: queryParams,clickhouseConfigs,- tags: {- feature: "batch-export",- type: "event",- kind: "export",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -448,12 +443,7 @@ export const getEventsStreamForDataset = async (props: {http_receive_timeout: 300,},},- tags: {- feature: "batch-add-to-dataset",- type: "event",- kind: "dataset",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});@@ -555,12 +545,7 @@ export const getEventsStreamForAnnotationQueue = async (props: {http_receive_timeout: 300,},},- tags: {- feature: "batch-add-to-annotation-queue",- type: "event",- kind: "annotation",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.tsindex 03833f1823..221e651f51 100644--- a/worker/src/features/database-read-stream/observation-stream.ts+++ b/worker/src/features/database-read-stream/observation-stream.ts@@ -274,12 +274,7 @@ export const getObservationStream = async (...search.params,},clickhouseConfigs,- tags: {- feature: "batch-export",- type: "observation",- kind: "export",- projectId,- },+ tags: { projectId },});// Helper function to process a single observation row@@ -554,12 +549,7 @@ const getObservationStreamFromEvents = async (query,params: queryParams,clickhouseConfigs,- tags: {- feature: "batch-export",- type: "observation",- kind: "export",- projectId,- },+ tags: { projectId },preferredClickhouseService: "EventsReadOnly",});diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.tsindex 248871897f..388415301f 100644--- a/worker/src/features/database-read-stream/trace-stream.ts+++ b/worker/src/features/database-read-stream/trace-stream.ts@@ -220,12 +220,7 @@ export const getTraceStream = async (props: {...search.params,},clickhouseConfigs,- tags: {- feature: "batch-export",- type: "trace",- kind: "export",- projectId,- },+ tags: { projectId },});// Helper function to process a single trace rowdiff --git a/worker/src/features/deleted-mask-cleaner/index.ts b/worker/src/features/deleted-mask-cleaner/index.tsindex 00dde6ecd6..dcac5b9d06 100644--- a/worker/src/features/deleted-mask-cleaner/index.ts+++ b/worker/src/features/deleted-mask-cleaner/index.ts@@ -131,10 +131,6 @@ export class DeletedMaskCleaner extends PeriodicExclusiveRunner {database: env.CLICKHOUSE_DB,tables: Array.from(DELETED_MASK_CLEANER_TABLES),},- tags: {- feature: "deleted-mask-cleaner",- operation: "get-candidates",- },});return rows;@@ -156,10 +152,6 @@ export class DeletedMaskCleaner extends PeriodicExclusiveRunner {database: env.CLICKHOUSE_DB,tables,},- tags: {- feature: "deleted-mask-cleaner",- operation: "get-mutation-counts",- },});}@@ -199,12 +191,6 @@ export class DeletedMaskCleaner extends PeriodicExclusiveRunner {mutations_sync: "0",},abortSignal: abortController.signal,- tags: {- feature: "deleted-mask-cleaner",- table: candidate.table,- partition: candidate.partition_to_clean,- operation: "apply-deleted-mask",- },});recordIncrement(`${METRIC_PREFIX}.commands_submitted`, 1, {diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex 5511f1c9cc..5909ef37dc 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -269,7 +269,6 @@ export const createEvalJobs = async ({: "timestamp" in event? new Date(event.timestamp): new Date(jobTimestamp),- clickhouseFeatureTag: "eval-create",excludeInputOutput: true,excludeMetadata: false, // Metadata needed for in-memory filter evaluation});@@ -1265,7 +1264,6 @@ export async function extractVariablesFromTracingData({traceId,projectId,timestamp: traceTimestamp,- clickhouseFeatureTag: "eval-execution",});traceCache.set(traceCacheKey, trace ?? null);}diff --git a/worker/src/features/eventPropagation/handleEventPropagationJob.ts b/worker/src/features/eventPropagation/handleEventPropagationJob.tsindex 50ccfda607..818f2a8914 100644--- a/worker/src/features/eventPropagation/handleEventPropagationJob.ts+++ b/worker/src/features/eventPropagation/handleEventPropagationJob.ts@@ -96,10 +96,6 @@ export const handleEventPropagationJob = async (ORDER BY partition ASC`,params: lastProcessedPartition ? { lastProcessedPartition } : undefined,- tags: {- feature: "ingestion",- operation_name: "getNextPartition",- },});recordGauge(@@ -294,11 +290,6 @@ export const handleEventPropagationJob = async (WHERE obs._partition_value = tuple('${partitionToProcess}')${excludeProjectIdsInClause ? `AND obs.project_id ${excludeProjectIdsInClause}` : ""}`,- tags: {- feature: "ingestion",- partition: partitionToProcess,- operation_name: "propagateObservationsToEvents",- },clickhouseConfigs: {request_timeout: 600000, // 10 minutes timeout},diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex ef3d6e87b3..1af7348361 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -155,10 +155,6 @@ export async function getDatasetRunItemsSinceLastRun(clickhouseConfigs: {request_timeout: 120000, // 2 minutes timeout},- tags: {- feature: "experiment-backfill",- operation_name: "getDatasetRunItemsSinceLastRun",- },});logger.info(@@ -247,10 +243,6 @@ export async function getRelevantObservations(clickhouseConfigs: {request_timeout: 60_000,},- tags: {- feature: "experiment-backfill",- operation_name: "getRelevantObservations",- },});}@@ -328,10 +320,6 @@ export async function getRelevantTraces(clickhouseConfigs: {request_timeout: 60_000,},- tags: {- feature: "experiment-backfill",- operation_name: "getRelevantTraces",- },});}diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.tsindex c5853327e3..f23073da65 100644--- a/worker/src/features/experiments/experimentServiceClickhouse.ts+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts@@ -59,12 +59,7 @@ async function getExistingRunItemDatasetItemIds(runId,datasetId,},- tags: {- feature: "dataset-run-item",- type: "read",- kind: "list",- projectId,- },+ tags: { projectId },});return new Set(rows.map((row) => row.id));diff --git a/worker/src/queues/workerManager.ts b/worker/src/queues/workerManager.tsindex 1cc0564ace..6b79806a11 100644--- a/worker/src/queues/workerManager.ts+++ b/worker/src/queues/workerManager.ts@@ -1,6 +1,8 @@import { Job, Processor, Worker, WorkerOptions } from "bullmq";+import { context as otelContext } from "@opentelemetry/api";import {convertQueueNameToMetricName,+ contextWithLangfuseProps,createBullMQWorkerOptionsWithRedis,logger,QueueName,@@ -20,6 +22,24 @@ import {export class WorkerManager {private static workers: { [key: string]: Worker } = {};+ private static extractProjectId(job: Job): string | undefined {+ const data = job.data as {+ payload?: {+ projectId?: unknown;+ authCheck?: { scope?: { projectId?: unknown } };+ };+ };++ const candidates = [+ data.payload?.projectId,+ data.payload?.authCheck?.scope?.projectId,+ ];++ return candidates.find((candidate): candidate is string => {+ return typeof candidate === "string" && candidate.length > 0;+ });+ }+private static resolveMetricInfo(queueName: QueueName): {baseMetric: string;shardTag: { shard: string } | undefined;@@ -64,7 +84,15 @@ export class WorkerManager {...shardTag,});- const result = await processor(job);+ const clickHouseCtx = contextWithLangfuseProps({+ projectId: WorkerManager.extractProjectId(job),+ clickhouse: {+ surface: "worker",+ },+ });+ const result = await otelContext.with(clickHouseCtx, () =>+ processor(job),+ );const queue = resolveQueueInstance(queueName);// Sample queue depth gauges for sharded queues to reduce metric volume.diff --git a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.tsindex c9539894bc..fd18e6108a 100644--- a/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts+++ b/worker/src/services/ClickhouseWriter/ClickhouseWriter.unit.test.ts@@ -115,6 +115,33 @@ describe("ClickhouseWriter", () => {expect(mockInsert).toHaveBeenCalledTimes(1);});+ it("should mark writer insert log comments as multi-project", async () => {+ const mockInsert = vi+ .spyOn(clickhouseClientMock, "insert")+ .mockResolvedValue();++ writer.addToQueue(TableName.Traces, {+ id: "1",+ name: "test",+ project_id: "project-1",+ } as any);+ writer.addToQueue(TableName.Traces, {+ id: "2",+ name: "test",+ project_id: "project-1",+ } as any);++ await vi.advanceTimersByTimeAsync(writer.writeInterval);++ const logComment = JSON.parse(+ mockInsert.mock.calls[0][0].clickhouse_settings.log_comment,+ );+ expect(logComment).toMatchObject({+ surface: "worker",+ projectId: "MULTI_PROJECT",+ });+ });+it("should handle errors and retry", async () => {const mockInsert = vi.spyOn(clickhouseClientMock, "insert")diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex ad0732fe94..6c4599e235 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -13,7 +13,7 @@ import {TraceNullRecordInsertType,DatasetRunItemRecordInsertType,EventRecordInsertType,- tagsWithTraceId,+ buildClickHouseLogComment,} from "@langfuse/shared/src/server";import { Decimal } from "decimal.js";@@ -29,6 +29,7 @@ import { backOff } from "exponential-backoff";const DECIMAL_64_12_LIMIT = new Decimal("1e6");const DECIMAL_64_12_MAX_NUM = 999_999.999_999;const DECIMAL_64_12_MIN_NUM = -DECIMAL_64_12_MAX_NUM;+const MULTI_PROJECT_LOG_COMMENT_PROJECT_ID = "MULTI_PROJECT";export class ClickhouseWriter {private static instance: ClickhouseWriter | null = null;@@ -578,16 +579,10 @@ export class ClickhouseWriter {format: "JSONEachRow",values: params.records,clickhouse_settings: {- log_comment: JSON.stringify(- tagsWithTraceId({- feature: "ingestion",- type: params.table,- operation_name: "writeToClickhouse",- ...(params.records.length > 0 && params.records[0].project_id- ? { projectId: params.records[0].project_id }- : {}),- }),- ),+ log_comment: buildClickHouseLogComment({+ surface: "worker",+ projectId: MULTI_PROJECT_LOG_COMMENT_PROJECT_ID,+ }),},}).catch((err) => {diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 1f11880ee4..387128c344 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -49,7 +49,7 @@ import {getDatasetItemById,normalizeToolsForObservation,hasNoEvalConfigsCache,- tagsWithTraceId,+ buildClickHouseLogComment,} from "@langfuse/shared/src/server";import { tokenCountAsync } from "../../features/tokenisation/async-usage";@@ -1436,12 +1436,9 @@ export class IngestionService {format: "JSONEachRow",query_params: { projectId, entityId, ...additionalFilters.params },clickhouse_settings: {- log_comment: JSON.stringify(- tagsWithTraceId({- feature: "ingestion",- projectId,- }),- ),+ log_comment: buildClickHouseLogComment({+ projectId,+ }),},});