Skip to content

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

feat: detect clickhouse versions on start and set compat flags automagically. (#14187)

Valery Meleshkin7c523496a0b3
diff --git a/.env.dev.example b/.env.dev.example
index df573bd5c3..eab622d100 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -195,4 +195,6 @@ LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write
LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH=false
CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE="true"
-CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION=true
+# `auto` detects affected ClickHouse versions on startup. Set `true` to force
+# the workaround or `false` to force-disable it.
+CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION=auto
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 226a539fc9..2fe208b038 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -106,12 +106,12 @@ const EnvSchema = z.object({
CLICKHOUSE_UPDATE_PARALLEL_MODE: z
.enum(["sync", "async", "auto"])
.default("auto"),
- // Workaround for a 25.12 bug where lightweight updates/deletes interact
- // incorrectly with lazy materialization. Remove after ClickHouse 26.4, or
- // earlier if the fix is backported.
+ // Workaround for ClickHouse analyzer/lazy materialization bugs. In "auto",
+ // Langfuse detects the ClickHouse version on startup and applies known
+ // compatibility settings for affected version bands.
CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: z
- .enum(["true", "false"])
- .default("false"),
+ .enum(["auto", "true", "false"])
+ .default("auto"),
CLICKHOUSE_MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY: z.coerce
.number()
.default(32_000_000_000), // ~32GB
diff --git a/packages/shared/src/server/clickhouse/client.test.ts b/packages/shared/src/server/clickhouse/client.test.ts
new file mode 100644
index 0000000000..fcb812a5f3
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/client.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { type ClickHouseSettings } from "@clickhouse/client";
+
+const mocks = vi.hoisted(() => ({
+ createClient: vi.fn(),
+ close: vi.fn(async () => undefined),
+ env: {
+ CLICKHOUSE_URL: "http://localhost:8123",
+ CLICKHOUSE_READ_ONLY_URL: undefined,
+ CLICKHOUSE_EVENTS_READ_ONLY_URL: undefined,
+ CLICKHOUSE_USER: "default",
+ CLICKHOUSE_PASSWORD: "",
+ CLICKHOUSE_DB: "default",
+ CLICKHOUSE_KEEP_ALIVE_IDLE_SOCKET_TTL: 9000,
+ CLICKHOUSE_MAX_OPEN_CONNECTIONS: 25,
+ CLICKHOUSE_ASYNC_INSERT_MAX_DATA_SIZE: undefined,
+ CLICKHOUSE_ASYNC_INSERT_BUSY_TIMEOUT_MS: undefined,
+ CLICKHOUSE_ASYNC_INSERT_BUSY_TIMEOUT_MIN_MS: undefined,
+ CLICKHOUSE_LIGHTWEIGHT_DELETE_MODE: "alter_update",
+ CLICKHOUSE_UPDATE_PARALLEL_MODE: "auto",
+ CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "auto",
+ LANGFUSE_LOG_LEVEL: "error",
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: undefined,
+ },
+}));
+
+vi.mock("../../env", () => ({ env: mocks.env }));
+vi.mock("@clickhouse/client", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@clickhouse/client")>();
+
+ return {
+ ...actual,
+ createClient: mocks.createClient,
+ };
+});
+
+import { ClickHouseClientManager, clickhouseClient } from "./client";
+import { setClickHouseCompatibilityVersionForTests } from "./compatibility";
+
+describe("ClickHouseClientManager compatibility settings", () => {
+ beforeEach(async () => {
+ await ClickHouseClientManager.getInstance().closeAllConnections();
+
+ mocks.close.mockClear();
+ mocks.createClient.mockReset();
+ mocks.createClient.mockReturnValue({ close: mocks.close });
+ mocks.env.CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION = "auto";
+ setClickHouseCompatibilityVersionForTests(null);
+ });
+
+ it("applies resolved compatibility settings globally", () => {
+ setClickHouseCompatibilityVersionForTests("26.5.1.882");
+
+ clickhouseClient();
+
+ expect(mocks.createClient).toHaveBeenCalledTimes(1);
+ expect(
+ mocks.createClient.mock.calls[0][0].clickhouse_settings,
+ ).toMatchObject({
+ query_plan_optimize_lazy_materialization: 0,
+ });
+ });
+
+ it("lets explicit client settings override compatibility settings", () => {
+ setClickHouseCompatibilityVersionForTests("26.5.1.882");
+
+ clickhouseClient({
+ clickhouse_settings: {
+ query_plan_optimize_lazy_materialization: 1,
+ } as ClickHouseSettings,
+ });
+
+ expect(mocks.createClient).toHaveBeenCalledTimes(1);
+ expect(
+ mocks.createClient.mock.calls[0][0].clickhouse_settings
+ .query_plan_optimize_lazy_materialization,
+ ).toBe(1);
+ });
+
+ it("uses a new cached client key after compatibility settings change", () => {
+ clickhouseClient();
+ setClickHouseCompatibilityVersionForTests("26.5.1.882");
+ clickhouseClient();
+
+ expect(mocks.createClient).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index e7456758ff..25bad729ae 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -1,10 +1,11 @@
-import { createClient } from "@clickhouse/client";
+import { createClient, type ClickHouseSettings } from "@clickhouse/client";
import { env } from "../../env";
import { VERSION } from "../../constants/VERSION";
import { NodeClickHouseClientConfigOptions } from "@clickhouse/client/dist/config";
import { getCurrentSpan } from "../instrumentation";
import { propagation, context } from "@opentelemetry/api";
import { ClickHouseLogger, mapLogLevel } from "./clickhouse-logger";
+import { getClickHouseCompatibilitySettings } from "./compatibility";
export type ClickhouseClientType = ReturnType<typeof createClient>;
@@ -13,7 +14,7 @@ export type PreferredClickhouseService =
| "ReadOnly"
| "EventsReadOnly";
-type ServiceClickhouseSettings = {
+type ServiceClickhouseSettings = ClickHouseSettings & {
enable_full_text_index?: 1;
};
@@ -83,16 +84,25 @@ export class ClickHouseClientManager {
// Include any other relevant config options
};
- return { settings: keyParams, serviceClickhouseSettings };
+ return {
+ settings: keyParams,
+ serviceClickhouseSettings,
+ };
}
private getServiceClickhouseSettings(
preferredClickhouseService: PreferredClickhouseService,
): ServiceClickhouseSettings {
- return preferredClickhouseService === "EventsReadOnly" &&
+ const eventROSettings: ServiceClickhouseSettings =
+ preferredClickhouseService === "EventsReadOnly" &&
this.isEventsTableReadPathEnabled()
- ? { enable_full_text_index: 1 }
- : {};
+ ? { enable_full_text_index: 1 }
+ : {};
+
+ return {
+ ...getClickHouseCompatibilitySettings(),
+ ...eventROSettings,
+ };
}
private isEventsTableReadPathEnabled(): boolean {
@@ -192,12 +202,6 @@ export class ClickHouseClientManager {
update_parallel_mode: env.CLICKHOUSE_UPDATE_PARALLEL_MODE,
}
: {}),
- // Workaround for a 25.12 bug where lightweight updates/deletes
- // interact incorrectly with lazy materialization. Remove after
- // ClickHouse 26.4, or earlier if the fix is backported.
- ...(env.CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION === "true"
- ? { query_plan_optimize_lazy_materialization: 0 }
- : {}),
...cloudOptions,
...serviceClickhouseSettings,
...opts.clickhouse_settings,
diff --git a/packages/shared/src/server/clickhouse/compatibility.test.ts b/packages/shared/src/server/clickhouse/compatibility.test.ts
new file mode 100644
index 0000000000..a4b0f2291e
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/compatibility.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from "vitest";
+
+const envMock = vi.hoisted(() => ({
+ env: {
+ CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "auto",
+ },
+}));
+
+vi.mock("../../env", () => envMock);
+vi.mock("../logger", () => ({
+ logger: {
+ info: vi.fn(),
+ warn: vi.fn(),
+ },
+}));
+
+import {
+ isClickHouseVersionInBand,
+ parseClickHouseVersion,
+ resolveClickHouseCompatibility,
+} from "./compatibility";
+
+describe("ClickHouse compatibility version parsing", () => {
+ it("parses ClickHouse versions with build components", () => {
+ expect(parseClickHouseVersion("26.5.1.882")).toMatchObject({
+ major: 26,
+ minor: 5,
+ patch: 1,
+ tuple: [26, 5, 1],
+ });
+ });
+
+ it("parses ClickHouse versions with dotted vendor suffixes", () => {
+ expect(parseClickHouseVersion("25.4.1.1.altinitystable")).toMatchObject({
+ major: 25,
+ minor: 4,
+ patch: 1,
+ tuple: [25, 4, 1],
+ });
+ });
+
+ it("matches inclusive lower bounds", () => {
+ const band = { minInclusive: "25.4.0" };
+
+ expect(isClickHouseVersionInBand("25.3.99", band)).toBe(false);
+ expect(isClickHouseVersionInBand("25.4.0", band)).toBe(true);
+ expect(isClickHouseVersionInBand("25.4.1.1234", band)).toBe(true);
+ expect(isClickHouseVersionInBand("25.4.1.1.altinitystable", band)).toBe(
+ true,
+ );
+ expect(isClickHouseVersionInBand("26.5.1.882", band)).toBe(true);
+ });
+
+ it("matches exclusive upper bounds", () => {
+ const band = { minInclusive: "25.4.0", maxExclusive: "26.4.0" };
+
+ expect(isClickHouseVersionInBand("26.3.99", band)).toBe(true);
+ expect(isClickHouseVersionInBand("26.4.0", band)).toBe(false);
+ });
+});
+
+describe("resolveClickHouseCompatibility", () => {
+ it("applies lazy materialization workaround in auto mode for affected versions", () => {
+ expect(
+ resolveClickHouseCompatibility({
+ version: "26.5.1.882",
+ overrides: { CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "auto" },
+ }).settings,
+ ).toEqual({ query_plan_optimize_lazy_materialization: 0 });
+ });
+
+ it("does not apply lazy materialization workaround in auto mode before the affected band", () => {
+ expect(
+ resolveClickHouseCompatibility({
+ version: "25.3.99",
+ overrides: { CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "auto" },
+ }).settings,
+ ).toEqual({});
+ });
+
+ it("allows forcing lazy materialization workaround on", () => {
+ expect(
+ resolveClickHouseCompatibility({
+ version: null,
+ overrides: { CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "true" },
+ }).settings,
+ ).toEqual({ query_plan_optimize_lazy_materialization: 0 });
+ });
+
+ it("allows forcing lazy materialization workaround off", () => {
+ expect(
+ resolveClickHouseCompatibility({
+ version: "26.5.1.882",
+ overrides: { CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION: "false" },
+ }).settings,
+ ).toEqual({});
+ });
+});
diff --git a/packages/shared/src/server/clickhouse/compatibility.ts b/packages/shared/src/server/clickhouse/compatibility.ts
new file mode 100644
index 0000000000..911311bf7c
--- /dev/null
+++ b/packages/shared/src/server/clickhouse/compatibility.ts
@@ -0,0 +1,215 @@
+import { createClient, type ClickHouseSettings } from "@clickhouse/client";
+import type { NodeClickHouseClientConfigOptions } from "@clickhouse/client/dist/config";
+
+import { VERSION } from "../../constants/VERSION";
+import { env } from "../../env";
+import { logger } from "../logger";
+import {
+ compareParsedVersions,
+ parseVersionString,
+ type ParsedVersion,
+} from "../utils/compareVersions";
+import { ClickHouseLogger, mapLogLevel } from "./clickhouse-logger";
+
+export type ClickHouseVersion = ParsedVersion;
+
+export type ClickHouseVersionBand = {
+ minInclusive: string;
+ maxExclusive?: string;
+};
+
+type ClickHouseCompatibilityEnvKey = "CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION";
+
+type ClickHouseCompatibilityEnvValue = "auto" | "true" | "false";
+
+type ClickHouseCompatibilityRule = {
+ id: string;
+ setting: string;
+ value: ClickHouseSettings[string];
+ reason: string;
+ versionBands: ClickHouseVersionBand[];
+ overrideEnvKey: ClickHouseCompatibilityEnvKey;
+};
+
+type ResolveClickHouseCompatibilityParams = {
+ version?: string | null;
+ overrides?: Partial<
+ Record<ClickHouseCompatibilityEnvKey, ClickHouseCompatibilityEnvValue>
+ >;
+};
+
+type ResolvedClickHouseCompatibility = {
+ settings: ClickHouseSettings;
+ appliedRules: ClickHouseCompatibilityRule[];
+};
+
+const CLICKHOUSE_COMPATIBILITY_RULES: ClickHouseCompatibilityRule[] = [
+ {
+ id: "disable-lazy-materialization",
+ setting: "query_plan_optimize_lazy_materialization",
+ value: 0,
+ reason:
+ "Work around ClickHouse analyzer failures that can surface as `Not found column and(...)` on compound predicates.",
+ versionBands: [{ minInclusive: "25.4.0" }],
+ overrideEnvKey: "CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION",
+ },
+];
+
+let detectedClickHouseVersion: string | null = null;
+let initializationPromise: Promise<void> | null = null;
+
+export const parseClickHouseVersion = (
+ rawVersion: string,
+): ClickHouseVersion | null => parseVersionString(rawVersion);
+
+const parseVersionBound = (version: string): ClickHouseVersion => {
+ const parsed = parseClickHouseVersion(version);
+ if (!parsed) {
+ throw new Error(
+ `Invalid ClickHouse compatibility version bound: ${version}`,
+ );
+ }
+ return parsed;
+};
+
+export const isClickHouseVersionInBand = (
+ version: string | ClickHouseVersion,
+ band: ClickHouseVersionBand,
+): boolean => {
+ const parsedVersion =
+ typeof version === "string" ? parseClickHouseVersion(version) : version;
+ if (!parsedVersion) return false;
+
+ const min = parseVersionBound(band.minInclusive);
+ if (compareParsedVersions(parsedVersion, min) < 0) {
+ return false;
+ }
+
+ if (band.maxExclusive) {
+ const max = parseVersionBound(band.maxExclusive);
+ return compareParsedVersions(parsedVersion, max) < 0;
+ }
+
+ return true;
+};
+
+export const resolveClickHouseCompatibility = ({
+ version,
+ overrides,
+}: ResolveClickHouseCompatibilityParams = {}): ResolvedClickHouseCompatibility => {
+ const parsedVersion = version ? parseClickHouseVersion(version) : null;
+ const settings: ClickHouseSettings = {};
+ const appliedRules: ClickHouseCompatibilityRule[] = [];
+
+ for (const rule of CLICKHOUSE_COMPATIBILITY_RULES) {
+ const override =
+ overrides?.[rule.overrideEnvKey] ?? env[rule.overrideEnvKey] ?? "auto";
+
+ if (override === "false") continue;
+
+ const shouldApply =
+ override === "true" ||
+ (override === "auto" &&
+ parsedVersion &&
+ rule.versionBands.some((band) =>
+ isClickHouseVersionInBand(parsedVersion, band),
+ ));
+
+ if (shouldApply) {
+ settings[rule.setting] = rule.value;
+ appliedRules.push(rule);
+ }
+ }
+
+ return { settings, appliedRules };
+};
+
+export const getClickHouseCompatibilitySettings = (): ClickHouseSettings =>
+ resolveClickHouseCompatibility({ version: detectedClickHouseVersion })
+ .settings;
+
+export const initializeClickhouseCompatibility = async (): Promise<void> => {
+ if (initializationPromise) return initializationPromise;
+
+ initializationPromise = (async () => {
+ try {
+ detectedClickHouseVersion = await fetchClickHouseVersion();
+ const resolved = resolveClickHouseCompatibility({
+ version: detectedClickHouseVersion,
+ });
+
+ if (resolved.appliedRules.length > 0) {
+ logger.info("Applying ClickHouse compatibility settings", {
+ clickhouseVersion: detectedClickHouseVersion,
+ settings: resolved.settings,
+ rules: resolved.appliedRules.map((rule) => ({
+ id: rule.id,
+ setting: rule.setting,
+ reason: rule.reason,
+ })),
+ });
+ } else {
+ logger.info("No ClickHouse compatibility settings required", {
+ clickhouseVersion: detectedClickHouseVersion,
+ });
+ }
+ } catch (error) {
+ logger.warn(
+ "Failed to detect ClickHouse version; continuing without automatic compatibility settings",
+ {
+ error: error instanceof Error ? error.message : String(error),
+ },
+ );
+ }
+ })();
+
+ return initializationPromise;
+};
+
+const fetchClickHouseVersion = async (): Promise<string> => {
+ const client = createClient(getClickHouseVersionClientConfig());
+
+ try {
+ const result = await client.query({
+ query: "SELECT version() AS version",
+ format: "JSONEachRow",
+ });
+ const rows = await result.json<{ version: string }>();
+ const version = rows[0]?.version;
+
+ if (!version) {
+ throw new Error("ClickHouse version query returned no version");
+ }
+
+ if (!parseClickHouseVersion(version)) {
+ throw new Error(`ClickHouse returned an unsupported version: ${version}`);
+ }
+
+ return version;
+ } finally {
+ await client.close();
+ }
+};
+
+const getClickHouseVersionClientConfig =
+ (): NodeClickHouseClientConfigOptions => {
+ return {
+ url: env.CLICKHOUSE_URL,
+ username: env.CLICKHOUSE_USER,
+ password: env.CLICKHOUSE_PASSWORD,
+ database: env.CLICKHOUSE_DB,
+ application: `langfuse/${VERSION.replace("v", "")}`,
+ request_timeout: 10_000,
+ log: {
+ LoggerClass: ClickHouseLogger,
+ level: mapLogLevel(env.LANGFUSE_LOG_LEVEL ?? "info"),
+ },
+ };
+ };
+
+export const setClickHouseCompatibilityVersionForTests = (
+ version: string | null,
+): void => {
+ detectedClickHouseVersion = version;
+ initializationPromise = null;
+};
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 2bc918ff5e..a3b95c9a0b 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -49,6 +49,10 @@ export * from "./utils/billingCycleHelpers";
export * from "./utils/compareVersions";
export * from "./otel/utils";
export * from "./clickhouse/client";
+export {
+ getClickHouseCompatibilitySettings,
+ initializeClickhouseCompatibility,
+} from "./clickhouse/compatibility";
export * from "./clickhouse/schemaUtils";
export * from "./clickhouse/schema";
export * from "./clickhouse/queryTracking";
diff --git a/packages/shared/src/server/utils/compareVersions.test.ts b/packages/shared/src/server/utils/compareVersions.test.ts
new file mode 100644
index 0000000000..9447646372
--- /dev/null
+++ b/packages/shared/src/server/utils/compareVersions.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ compareParsedVersions,
+ compareVersions,
+ parseVersionString,
+} from "./compareVersions";
+
+describe("parseVersionString", () => {
+ it("parses the first three numeric version components", () => {
+ expect(parseVersionString("26.5.1.882")).toMatchObject({
+ major: 26,
+ minor: 5,
+ patch: 1,
+ tuple: [26, 5, 1],
+ });
+ });
+
+ it("parses dotted vendor suffixes", () => {
+ expect(parseVersionString("21.8.10.1.altinitystable")).toMatchObject({
+ major: 21,
+ minor: 8,
+ patch: 10,
+ tuple: [21, 8, 10],
+ });
+ });
+});
+
+describe("compareParsedVersions", () => {
+ it("compares parsed versions by major, minor, and patch", () => {
+ const older = parseVersionString("25.3.99");
+ const newer = parseVersionString("25.4.0");
+
+ if (!older || !newer) {
+ throw new Error("Expected versions to parse");
+ }
+
+ expect(compareParsedVersions(older, newer)).toBe(-1);
+ });
+});
+
+describe("compareVersions", () => {
+ it("keeps semantic version update classification behavior", () => {
+ expect(compareVersions("v1.2.3", "v1.3.0")).toBe("minor");
+ expect(compareVersions("v1.2.3-rc.1", "v1.2.3")).toBe("patch");
+ expect(compareVersions("v1.2.3", "v1.2.3")).toBeNull();
+ });
+});
diff --git a/packages/shared/src/server/utils/compareVersions.ts b/packages/shared/src/server/utils/compareVersions.ts
index 9c7b917e80..8b1c0e8faa 100644
--- a/packages/shared/src/server/utils/compareVersions.ts
+++ b/packages/shared/src/server/utils/compareVersions.ts
@@ -2,6 +2,51 @@ import { z } from "zod";
export const versionSchema = z.string().regex(/^v?\d+\.\d+\.\d+(?:[-+].+)?$/); // e.g. v1.2.3, 1.2.3, v1.2.3-rc.1, v1.2.3+build.123
+type VersionTuple = readonly [number, number, number];
+
+export type ParsedVersion = {
+ raw: string;
+ major: number;
+ minor: number;
+ patch: number;
+ tuple: VersionTuple;
+ isPreRelease: boolean;
+};
+
+export const parseVersionString = (
+ rawVersion: string,
+): ParsedVersion | null => {
+ const match = rawVersion.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[.+-].+)?$/);
+ if (!match) return null;
+
+ const major = Number(match[1]);
+ const minor = Number(match[2]);
+ const patch = Number(match[3]);
+
+ if (![major, minor, patch].every(Number.isSafeInteger)) return null;
+
+ return {
+ raw: rawVersion,
+ major,
+ minor,
+ patch,
+ tuple: [major, minor, patch],
+ isPreRelease: /[-+]/.test(rawVersion),
+ };
+};
+
+export const compareParsedVersions = (
+ left: ParsedVersion,
+ right: ParsedVersion,
+): number => {
+ for (let i = 0; i < left.tuple.length; i++) {
+ if (left.tuple[i] > right.tuple[i]) return 1;
+ if (left.tuple[i] < right.tuple[i]) return -1;
+ }
+
+ return 0;
+};
+
/**
* Compare two semantic versions.
* @param current - Current version (e.g., "v1.2.3")
@@ -15,44 +60,33 @@ export const compareVersions = (
const currentValidated = versionSchema.parse(current);
const latestValidated = versionSchema.parse(latest);
- const parseVersion = (version: string) => {
- if (version.startsWith("v")) {
- version = version.slice(1);
- }
- // Split into version and pre-release parts
- const [versionPart, ...rest] = version.split(/[-+]/);
- const numbers = versionPart.split(".").map(Number);
- return {
- numbers,
- isPreRelease: rest.length > 0,
- };
- };
+ const currentParsed = parseVersionString(currentValidated);
+ const latestParsed = parseVersionString(latestValidated);
- const current_parsed = parseVersion(currentValidated);
- const latest_parsed = parseVersion(latestValidated);
-
- const [currentMajor, currentMinor, currentPatch] = current_parsed.numbers;
- const [latestMajor, latestMinor, latestPatch] = latest_parsed.numbers;
+ if (!currentParsed || !latestParsed) {
+ throw new Error("Invalid semantic version");
+ }
// If current is a pre-release (RC) and latest is a full release of the same version,
// consider it as needing a patch update
if (
- current_parsed.isPreRelease &&
- !latest_parsed.isPreRelease &&
- currentMajor === latestMajor &&
- currentMinor === latestMinor &&
- currentPatch === latestPatch
+ currentParsed.isPreRelease &&
+ !latestParsed.isPreRelease &&
+ compareParsedVersions(currentParsed, latestParsed) === 0
) {
return "patch";
}
- if (latestMajor > currentMajor) return "major";
- if (latestMajor === currentMajor && latestMinor > currentMinor)
+ if (latestParsed.major > currentParsed.major) return "major";
+ if (
+ latestParsed.major === currentParsed.major &&
+ latestParsed.minor > currentParsed.minor
+ )
return "minor";
if (
- latestMajor === currentMajor &&
- latestMinor === currentMinor &&
- latestPatch > currentPatch
+ latestParsed.major === currentParsed.major &&
+ latestParsed.minor === currentParsed.minor &&
+ latestParsed.patch > currentParsed.patch
)
return "patch";
diff --git a/web/src/initialize.ts b/web/src/initialize.ts
index 1052d9c503..224996d522 100644
--- a/web/src/initialize.ts
+++ b/web/src/initialize.ts
@@ -5,7 +5,12 @@ import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKey
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
import { CloudConfigSchema } from "@langfuse/shared";
-import { logger } from "@langfuse/shared/src/server";
+import {
+ initializeClickhouseCompatibility,
+ logger,
+} from "@langfuse/shared/src/server";
+
+await initializeClickhouseCompatibility();
// Warn if LANGFUSE_INIT_* variables are set but LANGFUSE_INIT_ORG_ID is missing
if (!env.LANGFUSE_INIT_ORG_ID) {
diff --git a/worker/src/app.ts b/worker/src/app.ts
index 4858e1506b..a859a6b831 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -1,5 +1,3 @@
-import "./initialize";
-
import express from "express";
import cors from "cors";
import * as middlewares from "./middlewares";
diff --git a/worker/src/index.ts b/worker/src/index.ts
index 1ec275fe1b..ca080e6603 100644
--- a/worker/src/index.ts
+++ b/worker/src/index.ts
@@ -1,8 +1,27 @@
import "./instrumentation"; // instrumenting the application
-import app from "./app";
+import type { Server } from "http";
+import { initializeWorker } from "./initialize";
import { env } from "./env";
import { logger } from "@langfuse/shared/src/server";
-export const server = app.listen(env.PORT, env.HOSTNAME, () => {
- logger.info(`Listening: http://${env.HOSTNAME}:${env.PORT}`);
+export let server: Server | undefined;
+
+const startWorker = async (): Promise<void> => {
+ await initializeWorker();
+
+ // worker is CommonJS under NodeNext, so dynamic import wraps the module namespace in default.
+ const {
+ default: { default: app },
+ } = await import("./app.js");
+
+ server = app.listen(env.PORT, env.HOSTNAME, () => {
+ logger.info(`Listening: http://${env.HOSTNAME}:${env.PORT}`);
+ });
+};
+
+startWorker().catch((error) => {
+ logger.error("Failed to start worker", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ process.exit(1);
});
diff --git a/worker/src/initialize.ts b/worker/src/initialize.ts
index 0ef19fd0d7..32d3ce1f39 100644
--- a/worker/src/initialize.ts
+++ b/worker/src/initialize.ts
@@ -1,7 +1,14 @@
import { upsertDefaultModelPrices } from "./scripts/upsertDefaultModelPrices";
import { upsertManagedEvaluators } from "./scripts/upsertManagedEvaluators";
import { upsertLangfuseDashboards } from "./scripts/upsertLangfuseDashboards";
+import { initializeClickhouseCompatibility } from "@langfuse/shared/src/server";
-upsertDefaultModelPrices();
-upsertManagedEvaluators();
-upsertLangfuseDashboards();
+export const initializeWorker = async (): Promise<void> => {
+ await initializeClickhouseCompatibility();
+
+ await Promise.all([
+ upsertDefaultModelPrices(),
+ upsertManagedEvaluators(),
+ upsertLangfuseDashboards(),
+ ]);
+};
diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.ts
index d42326e32c..5d25acff6d 100644
--- a/worker/src/utils/shutdown.ts
+++ b/worker/src/utils/shutdown.ts
@@ -26,7 +26,7 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {
setSigtermReceived();
// Stop accepting new connections
- server.close();
+ server?.close();
logger.info("Server has been closed.");
// Stop batch project cleaners