🪢 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
perf: initialize clickhouse skip read map on startup (#8039)
Steffen Schmitz4d5c288d1e22
diff --git a/worker/src/app.ts b/worker/src/app.tsindex 45ef89c2f6..bb5f45f37d 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -33,6 +33,8 @@ import {import { env } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";import { BackgroundMigrationManager } from "./backgroundMigrations/backgroundMigrationManager";+import { prisma } from "@langfuse/shared/src/db";+import { ClickhouseReadSkipCache } from "./utils/clickhouseReadSkipCache";import { experimentCreateQueueProcessor } from "./queues/experimentQueue";import { traceDeleteProcessor } from "./queues/traceDelete";import { projectDeleteProcessor } from "./queues/projectDelete";@@ -79,6 +81,13 @@ if (env.LANGFUSE_ENABLE_BACKGROUND_MIGRATIONS === "true") {});}+// Initialize ClickhouseReadSkipCache on container start+ClickhouseReadSkipCache.getInstance(prisma)+ .initialize()+ .catch((err) => {+ logger.error("Error initializing ClickhouseReadSkipCache", err);+ });+if (env.QUEUE_CONSUMER_TRACE_UPSERT_QUEUE_IS_ENABLED === "true") {WorkerManager.register(QueueName.TraceUpsert,diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex ab7b83557b..9035193300 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -1,13 +1,7 @@import { Cluster, Redis } from "ioredis";import { v4 } from "uuid";import { Prisma } from "@prisma/client";-import {- LangfuseNotFoundError,- Model,- Price,- PrismaClient,- Prompt,-} from "@langfuse/shared";+import { Model, Price, PrismaClient, Prompt } from "@langfuse/shared";import {ClickhouseClientType,convertDateToClickhouseDateTime,@@ -56,6 +50,7 @@ import { randomUUID } from "crypto";import { env } from "../../env";import { findModel } from "../modelMatch";import { SpanKind } from "@opentelemetry/api";+import { ClickhouseReadSkipCache } from "../../utils/clickhouseReadSkipCache";type InsertRecord =| TraceRecordInsertType@@ -938,57 +933,6 @@ export class IngestionService {};}- private skipClickhouseReadProjectsCache = new Map<string, boolean>();-- private async shouldSkipClickHouseRead(- projectId: string,- minProjectCreateDate: string | undefined = undefined,- ): Promise<boolean> {- if (- env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_PROJECT_IDS &&- env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_PROJECT_IDS.split(- ",",- ).includes(projectId)- ) {- return true;- }-- if (- !env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE &&- !minProjectCreateDate- ) {- return false;- }-- if (this.skipClickhouseReadProjectsCache.has(projectId)) {- return this.skipClickhouseReadProjectsCache.get(projectId) ?? false;- }-- const project = await this.prisma.project.findFirst({- where: {- id: projectId,- deletedAt: null,- },- select: {- id: true,- createdAt: true,- },- });-- if (!project) {- throw new LangfuseNotFoundError(`Project ${projectId} not found`);- }-- const cutoffDate = new Date(- env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE ??- minProjectCreateDate ??- new Date(), // Fallback to today. Should never apply.- );- const result = project.createdAt >= cutoffDate;- this.skipClickhouseReadProjectsCache.set(projectId, result);- return result;- }-// eslint-disable-next-line no-unused-varsprivate async getClickhouseRecord(params: {projectId: string;@@ -1029,7 +973,11 @@ export class IngestionService {params: Record<string, unknown>;};}) {- if (await this.shouldSkipClickHouseRead(params.projectId)) {+ if (+ await ClickhouseReadSkipCache.getInstance(+ this.prisma,+ ).shouldSkipClickHouseRead(params.projectId)+ ) {recordIncrement("langfuse.ingestion.clickhouse_read_for_update", 1, {skipped: "true",table: params.table,diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex be433ae74d..f67cc01cc8 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -1960,22 +1960,6 @@ describe("Ingestion end-to-end tests", () => {expect(trace.user_id).toBe("user-1");});- it("should skip clickhouse read for recently created projects", async () => {- const projectId = randomUUID();- await prisma.project.create({- data: {- id: projectId,- name: randomUUID(),- orgId: "seed-org-id",- },- });- const shouldSkip = await ingestionService.shouldSkipClickHouseRead(- projectId,- "2024-01-01", // Use some date in the past- );- expect(shouldSkip).toBe(true);- });-[{inputs: [{ a: "a" }, { b: "b" }],diff --git a/worker/src/utils/clickhouseReadSkipCache.ts b/worker/src/utils/clickhouseReadSkipCache.tsnew file mode 100644index 0000000000..ddbeac2373--- /dev/null+++ b/worker/src/utils/clickhouseReadSkipCache.ts@@ -0,0 +1,173 @@+import { PrismaClient, LangfuseNotFoundError } from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";+import { env } from "../env";++export class ClickhouseReadSkipCache {+ private static instance: ClickhouseReadSkipCache | null = null;+ private projectSkipMap = new Map<string, boolean>();+ private initialized = false;+ private initializing = false;+ private initPromise: Promise<void> | null = null;+ private prisma: PrismaClient;++ private constructor(prisma: PrismaClient) {+ this.prisma = prisma;+ }++ public static getInstance(prisma?: PrismaClient): ClickhouseReadSkipCache {+ if (!ClickhouseReadSkipCache.instance) {+ if (!prisma) {+ throw new Error("PrismaClient is required for first initialization");+ }+ ClickhouseReadSkipCache.instance = new ClickhouseReadSkipCache(prisma);+ }+ return ClickhouseReadSkipCache.instance;+ }++ public async initialize(): Promise<void> {+ if (this.initialized) {+ return;+ }++ if (this.initializing) {+ if (this.initPromise) {+ await this.initPromise;+ }+ return;+ }++ this.initializing = true;+ this.initPromise = this.performInitialization();++ try {+ await this.initPromise;+ this.initialized = true;+ } catch (error) {+ this.initializing = false;+ this.initPromise = null;+ throw error;+ }+ }++ private async performInitialization(): Promise<void> {+ if (!env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE) {+ logger.info(+ "No min project create date set, ClickhouseReadSkipCache will not pre-populate",+ );+ return;+ }++ const cutoffDate = new Date(+ env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE,+ );++ logger.info(+ `Initializing ClickhouseReadSkipCache with cutoff date: ${cutoffDate.toISOString()}`,+ );++ try {+ const projects = await this.prisma.project.findMany({+ where: {+ deletedAt: null,+ },+ select: {+ id: true,+ createdAt: true,+ },+ });++ let skipCount = 0;+ let noSkipCount = 0;++ for (const project of projects) {+ const shouldSkip = project.createdAt >= cutoffDate;+ this.projectSkipMap.set(project.id, shouldSkip);++ if (shouldSkip) {+ skipCount++;+ } else {+ noSkipCount++;+ }+ }++ logger.debug(+ `ClickhouseReadSkipCache initialized with ${projects.length} projects (${skipCount} will skip, ${noSkipCount} will not skip)`,+ );+ } catch (error) {+ logger.error("Failed to initialize ClickhouseReadSkipCache", error);+ throw error;+ }+ }++ public async shouldSkipClickHouseRead(+ projectId: string,+ minProjectCreateDate?: string,+ ): Promise<boolean> {+ // Check explicit project ID list first+ if (+ env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_PROJECT_IDS &&+ env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_PROJECT_IDS.split(+ ",",+ ).includes(projectId)+ ) {+ return true;+ }++ // If no cutoff date configuration, don't skip+ if (+ !env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE &&+ !minProjectCreateDate+ ) {+ return false;+ }++ // Ensure the cache is initialized+ if (!this.initialized) {+ await this.initialize();+ }++ // Check if we have the project in our cache+ if (this.projectSkipMap.has(projectId)) {+ return this.projectSkipMap.get(projectId) ?? false;+ }++ // If not in cache, we need to fetch the project+ logger.debug(`Project ${projectId} not in cache, fetching from database`);++ try {+ const project = await this.prisma.project.findFirst({+ where: {+ id: projectId,+ deletedAt: null,+ },+ select: {+ id: true,+ createdAt: true,+ },+ });++ if (!project) {+ throw new LangfuseNotFoundError(`Project ${projectId} not found`);+ }++ const cutoffDate = new Date(+ env.LANGFUSE_SKIP_INGESTION_CLICKHOUSE_READ_MIN_PROJECT_CREATE_DATE ??+ minProjectCreateDate ??+ new Date(), // Fallback to today. Should never apply.+ );++ const shouldSkip = project.createdAt >= cutoffDate;++ // Cache the result for future use+ this.projectSkipMap.set(projectId, shouldSkip);++ return shouldSkip;+ } catch (error) {+ logger.error(+ `Failed to fetch project ${projectId} for ClickHouse skip check`,+ error,+ );+ throw error;+ }+ }+}