Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(billing): CHB provider resolver, plan resolution (#15459)

Steffen Schmitz39236b9457b5
diff --git a/.env.dev.example b/.env.dev.example
index 81daa9ebf2..325da7028e 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -235,3 +235,7 @@ CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE="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
+
+# ClickHouse Billing (CHB) integration (Langfuse Cloud only). First-time
+# upgrades on/after this UTC date (YYYY-MM-DD) route to CHB; unset = off.
+# LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE=
diff --git a/.env.prod.example b/.env.prod.example
index 84730034e3..d842a23ef4 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -376,3 +376,7 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# LANGFUSE_INIT_ORG_CLOUD_PLAN=
### END Langfuse CI Config
+
+# ClickHouse Billing (CHB) integration (Langfuse Cloud only). First-time
+# upgrades on/after this UTC date (YYYY-MM-DD) route to CHB; unset = off.
+# LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE=
diff --git a/packages/shared/src/features/entitlements/plans.ts b/packages/shared/src/features/entitlements/plans.ts
index 6dbd3d70e2..99d8dc6720 100644
--- a/packages/shared/src/features/entitlements/plans.ts
+++ b/packages/shared/src/features/entitlements/plans.ts
@@ -29,3 +29,28 @@ export const isSelfHostedPlan = (plan?: Plan) =>
export const isPlan = (value: string): value is Plan =>
plans.includes(value as Plan);
+
+/**
+ * ClickHouse Billing (CHB) identifies plans by code. These are the lowercased
+ * paid tiers of `cloudConfigPlans` β€” there is deliberately no code for the free
+ * tier, because a free org simply carries no CHB bundle.
+ *
+ * Lives here rather than next to the Stripe catalogue in web because
+ * `cloudConfigSchema` validates stored plan codes against it, and shared cannot
+ * import from web.
+ */
+export const chbPlanCodes = ["core", "pro", "team", "enterprise"] as const;
+
+export type ChbPlanCode = (typeof chbPlanCodes)[number];
+
+/**
+ * Total mapping from CHB plan code to Langfuse plan. Total on purpose: callers
+ * get an exhaustive lookup with no unmapped-code branch to handle, and adding a
+ * code without a plan is a compile error.
+ */
+export const chbPlanCodeToPlan = {
+ core: "cloud:core",
+ pro: "cloud:pro",
+ team: "cloud:team",
+ enterprise: "cloud:enterprise",
+} as const satisfies Record<ChbPlanCode, Plan>;
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 3468148ace..fd7a3e7b10 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -5,6 +5,7 @@ export * from "./interfaces/filters";
export * from "./interfaces/orderBy";
export * from "./interfaces/cloudConfigSchema";
export * from "./interfaces/parseDbOrg";
+export * from "./interfaces/billingProvider";
export * from "./interfaces/customLLMProviderConfigSchemas";
export * from "./tableDefinitions";
export * from "./types";
diff --git a/packages/shared/src/interfaces/billingProvider.test.ts b/packages/shared/src/interfaces/billingProvider.test.ts
new file mode 100644
index 0000000000..924b0ad5ba
--- /dev/null
+++ b/packages/shared/src/interfaces/billingProvider.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+
+import { getBillingProvider, hasPaidBillingState } from "./billingProvider";
+import { CloudConfigSchema } from "./cloudConfigSchema";
+
+const CHB_ORG_ID = "0d5e6f7a-1b2c-4d3e-8f9a-0b1c2d3e4f5a";
+
+const orgWith = (cloudConfig: unknown) => ({
+ cloudConfig:
+ cloudConfig === null ? null : CloudConfigSchema.parse(cloudConfig),
+});
+
+// Cutoffs arrive as date-only env values, i.e. UTC midnight.
+const PAST = new Date("2020-01-01");
+
+describe("getBillingProvider", () => {
+ describe("orgs with existing Stripe state are pinned to stripe", () => {
+ it.each([
+ ["customerId only", { stripe: { customerId: "cus_123" } }],
+ [
+ "activeSubscriptionId only",
+ { stripe: { activeSubscriptionId: "sub_123" } },
+ ],
+ ])("%s, even with a past cutoff", (_label, cloudConfig) => {
+ expect(getBillingProvider(orgWith(cloudConfig), { cutoff: PAST })).toBe(
+ "stripe",
+ );
+ });
+ });
+
+ describe("orgs with CHB state resolve to clickhouse", () => {
+ it("with no cutoff (sticky decision)", () => {
+ expect(
+ getBillingProvider(
+ orgWith({ clickhouse: { organizationId: CHB_ORG_ID } }),
+ ),
+ ).toBe("clickhouse");
+ });
+
+ it("on both-state conflict, explicit CHB state wins", () => {
+ // Must never happen (interlocks in both checkout paths); if it does,
+ // the org stays on the provider that holds its live bundle.
+ expect(
+ getBillingProvider(
+ orgWith({
+ stripe: { customerId: "cus_123" },
+ clickhouse: { organizationId: CHB_ORG_ID },
+ }),
+ ),
+ ).toBe("clickhouse");
+ });
+ });
+
+ describe("never-billed orgs follow the cutoff", () => {
+ it.each([
+ ["empty cloudConfig", {}],
+ ["null cloudConfig", null],
+ ["manual plan override only", { plan: "Team" }],
+ ])("%s: no cutoff resolves to stripe", (_label, cloudConfig) => {
+ expect(getBillingProvider(orgWith(cloudConfig))).toBe("stripe");
+ });
+
+ // `now` omitted on purpose: covers the real-clock default.
+ it("cutoff in the past resolves to clickhouse", () => {
+ expect(getBillingProvider(orgWith({}), { cutoff: PAST })).toBe(
+ "clickhouse",
+ );
+ });
+
+ it("cutoff boundary: now exactly at the cutoff resolves to clickhouse", () => {
+ const cutoff = new Date("2026-01-01");
+ expect(getBillingProvider(orgWith({}), { cutoff, now: cutoff })).toBe(
+ "clickhouse",
+ );
+ expect(
+ getBillingProvider(orgWith({}), {
+ cutoff,
+ now: new Date(cutoff.getTime() - 1),
+ }),
+ ).toBe("stripe");
+ });
+ });
+});
+
+describe("hasPaidBillingState", () => {
+ it.each([
+ [
+ "active Stripe subscription",
+ { stripe: { activeSubscriptionId: "sub_123" } },
+ true,
+ ],
+ ["manual plan override", { plan: "Team" }, true],
+ [
+ "CHB bundle",
+ { clickhouse: { organizationId: CHB_ORG_ID, bundleId: "bdl_123" } },
+ true,
+ ],
+ [
+ "Stripe customer without subscription",
+ { stripe: { customerId: "cus_123" } },
+ false,
+ ],
+ [
+ "CHB org id without bundle (checkout started, never completed)",
+ { clickhouse: { organizationId: CHB_ORG_ID } },
+ false,
+ ],
+ ["empty cloudConfig", {}, false],
+ ["null cloudConfig", null, false],
+ ])("%s -> %s", (_label, cloudConfig, expected) => {
+ expect(hasPaidBillingState(orgWith(cloudConfig))).toBe(expected);
+ });
+});
diff --git a/packages/shared/src/interfaces/billingProvider.ts b/packages/shared/src/interfaces/billingProvider.ts
new file mode 100644
index 0000000000..31b69a41e1
--- /dev/null
+++ b/packages/shared/src/interfaces/billingProvider.ts
@@ -0,0 +1,58 @@
+import { type CloudConfigSchema } from "./cloudConfigSchema";
+
+export type BillingProvider = "stripe" | "clickhouse";
+
+type OrgWithCloudConfig = {
+ cloudConfig: CloudConfigSchema | null | undefined;
+};
+
+/**
+ * Resolve which billing provider owns an organization.
+ *
+ * Decision order:
+ * 1. Explicit CHB state always wins β€” the org is already on CHB. Sticky from
+ * the first checkout (which persists `clickhouse.organizationId`), so
+ * later cutoff changes cannot strand an org mid-flow.
+ * 2. Any existing Stripe billing state pins the org to Stripe (legacy). An
+ * existing billed customer can never flip providers via config.
+ * 3. Otherwise the org has never been billed: the cutoff decides at upgrade
+ * time β€” first checkouts on/after the cutoff go to CHB, regardless of when
+ * the org was created. Until a checkout writes CHB state, resolving to
+ * "clickhouse" has no side effects.
+ *
+ * The cutoff is injected rather than read from the environment: this module is
+ * exported from the client-safe barrel, so it must not reach for the server env
+ * schema. Each app passes the value from its own validated env.
+ *
+ * Absent cutoff β‡’ zero behavior change: nothing resolves to "clickhouse"
+ * unless it already carries a `clickhouse` block.
+ */
+export function getBillingProvider(
+ org: OrgWithCloudConfig,
+ opts?: { cutoff?: Date | null; now?: Date },
+): BillingProvider {
+ if (org.cloudConfig?.clickhouse?.organizationId) return "clickhouse";
+ if (
+ org.cloudConfig?.stripe?.customerId ||
+ org.cloudConfig?.stripe?.activeSubscriptionId
+ )
+ return "stripe";
+ const cutoff = opts?.cutoff;
+ if (cutoff && (opts?.now ?? new Date()).getTime() >= cutoff.getTime())
+ return "clickhouse";
+ return "stripe";
+}
+
+/**
+ * True when the org holds paid billing state with any provider: an active
+ * Stripe subscription, a manual plan override, or a CHB bundle. Used as the
+ * paid gate for free-tier usage-threshold enforcement β€” a paying customer
+ * must never be ingestion-blocked at the free-tier limit.
+ */
+export function hasPaidBillingState(org: OrgWithCloudConfig): boolean {
+ return Boolean(
+ org.cloudConfig?.stripe?.activeSubscriptionId ||
+ org.cloudConfig?.plan ||
+ org.cloudConfig?.clickhouse?.bundleId,
+ );
+}
diff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.ts
index d0a732ffe8..7d8f54725b 100644
--- a/packages/shared/src/interfaces/cloudConfigSchema.ts
+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { CloudConfigRateLimit } from "./rate-limits";
-import { cloudConfigPlans } from "../features/entitlements/plans";
+import { chbPlanCodes, cloudConfigPlans } from "../features/entitlements/plans";
export const CloudConfigSchema = z.object({
plan: z.enum(cloudConfigPlans).optional(),
@@ -23,6 +23,49 @@ export const CloudConfigSchema = z.object({
}))
.nullish(),
+ // ClickHouse Billing (CHB) state. Written only by the CHB webhook handler,
+ // except organizationId which checkout-session creation persists. Invariant:
+ // an org carries either `stripe` billing state or `clickhouse` state, never
+ // both β€” provider routing (getBillingProvider) and the worker jobs'
+ // Stripe-customer-id selection depend on it.
+ clickhouse: z
+ .object({
+ // ClickHouse Organization ID. Required and uuid-validated: parseDbOrg
+ // nulls the whole cloudConfig on parse failure, so strictness here is
+ // only safe because both writers (checkout response, webhook handler)
+ // validate the uuid before persisting. Change the stored schema first,
+ // writers second, if the id format ever loosens.
+ organizationId: z.uuid(),
+ bundleId: z.string().nullish(),
+ // Validated against the shared plan-code enum so downstream resolution is
+ // an exhaustive lookup. `.catch(null)` contains the damage if a code ever
+ // drifts (CHB renames a tier, or ships one before we deploy support for
+ // it): parseDbOrg nulls the *entire* cloudConfig on a parse failure, which
+ // would also discard the org's plan override, rate-limit overrides and
+ // stripe.customerId β€” and an org without a Stripe customer id drops out of
+ // the usage-metering job's selection and silently stops being billed.
+ // Unknown codes are rejected at the webhook so they are never stored.
+ planCode: z.enum(chbPlanCodes).nullish().catch(null),
+ paymentStatus: z.string().nullish(), // "active" | "failed" | ...
+ nextPaymentDate: z.string().nullish(),
+ // Stripe customer behind the CHB bundle (payment.provider.customerId on
+ // bundle.* events). Support tooling only β€” routing, plan resolution, and
+ // the worker jobs never read it.
+ stripeCustomerId: z.string().nullish(),
+ // Snapshot of a pending scheduled change (downgrade/cancel) for the UI.
+ scheduled: z
+ .object({
+ type: z.string(), // "upgrade" | "downgrade" | "cancel"
+ when: z.string(), // "immediate" | "billing_cycle_end" | ISO date
+ planCode: z.string().nullish(),
+ startDate: z.string().nullish(),
+ })
+ .nullish(),
+ // Monotonic guard against out-of-order webhook delivery.
+ lastEventCreatedAt: z.string().nullish(),
+ })
+ .nullish(),
+
// custom rate limits for an organization
rateLimitOverrides: CloudConfigRateLimit.optional(),
});
diff --git a/web/src/__tests__/server/unit/getPlan.servertest.ts b/web/src/__tests__/server/unit/getPlan.servertest.ts
new file mode 100644
index 0000000000..a74de94513
--- /dev/null
+++ b/web/src/__tests__/server/unit/getPlan.servertest.ts
@@ -0,0 +1,84 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server/getPlan";
+import { CloudConfigSchema } from "@langfuse/shared";
+
+const CHB_ORG_ID = "0d5e6f7a-1b2c-4d3e-8f9a-0b1c2d3e4f5a";
+const STRIPE_TEAM_PRODUCT_ID = "prod_QhK9qKGH25BTcS";
+
+const cloudConfig = (input: unknown) => CloudConfigSchema.parse(input);
+
+// getOrganizationPlanServerSide only resolves cloud plans when a cloud region is
+// set; without it every case would short-circuit to the self-hosted branch.
+describe("getOrganizationPlanServerSide (cloud)", () => {
+ const originalRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ beforeAll(() => {
+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "DEV";
+ });
+
+ afterAll(() => {
+ if (originalRegion === undefined) {
+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ } else {
+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;
+ }
+ });
+
+ it.each([
+ ["core", "cloud:core"],
+ ["pro", "cloud:pro"],
+ ["team", "cloud:team"],
+ ["enterprise", "cloud:enterprise"],
+ ])("maps CHB plan code %s to %s", (planCode, expected) => {
+ expect(
+ getOrganizationPlanServerSide(
+ cloudConfig({ clickhouse: { organizationId: CHB_ORG_ID, planCode } }),
+ ),
+ ).toBe(expected);
+ });
+
+ it("resolves a CHB org whose plan code drifted to cloud:hobby, not to stale Stripe state", () => {
+ // A code cloudConfigSchema does not recognize is dropped to null rather than
+ // failing the whole config. The org must still resolve to the free tier: it
+ // carries CHB state, so leftover Stripe fields must not decide its plan.
+ const parsed = cloudConfig({
+ clickhouse: { organizationId: CHB_ORG_ID, planCode: "scale" },
+ stripe: { activeProductId: STRIPE_TEAM_PRODUCT_ID },
+ });
+ expect(parsed.clickhouse?.planCode).toBeNull();
+
+ expect(getOrganizationPlanServerSide(parsed)).toBe("cloud:hobby");
+ });
+
+ it("resolves a CHB org with no plan code yet to cloud:hobby", () => {
+ expect(
+ getOrganizationPlanServerSide(
+ cloudConfig({ clickhouse: { organizationId: CHB_ORG_ID } }),
+ ),
+ ).toBe("cloud:hobby");
+ });
+
+ it("lets a manual plan override outrank a CHB plan code", () => {
+ expect(
+ getOrganizationPlanServerSide(
+ cloudConfig({
+ plan: "Enterprise",
+ clickhouse: { organizationId: CHB_ORG_ID, planCode: "core" },
+ }),
+ ),
+ ).toBe("cloud:enterprise");
+ });
+
+ it("still resolves Stripe orgs from the product id", () => {
+ expect(
+ getOrganizationPlanServerSide(
+ cloudConfig({ stripe: { activeProductId: STRIPE_TEAM_PRODUCT_ID } }),
+ ),
+ ).toBe("cloud:team");
+ });
+
+ it("resolves an org with no billing state to cloud:hobby", () => {
+ expect(getOrganizationPlanServerSide(cloudConfig({}))).toBe("cloud:hobby");
+ });
+});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 38f4ff59af..86dc29c995 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -399,6 +399,15 @@ export const env = createEnv({
STRIPE_SECRET_KEY: z.string().optional(),
STRIPE_WEBHOOK_SIGNING_SECRET: z.string().optional(),
+ // ClickHouse Billing (CHB) integration. First-time upgrades on/after this
+ // UTC date route to CHB; unset = feature off. Date-only (YYYY-MM-DD) so the
+ // cutline is a single unambiguous instant of UTC midnight, which is what
+ // new Date() yields for a date-only string. Parsed here so every consumer
+ // gets the same instant; keep in sync with worker/src/env.ts.
+ LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE: z.iso
+ .date()
+ .optional()
+ .transform((date) => (date ? new Date(date) : null)),
SENTRY_AUTH_TOKEN: z.string().optional(),
SENTRY_CSP_REPORT_URI: z.string().optional(),
LANGFUSE_RATE_LIMITS_ENABLED: z.enum(["true", "false"]).default("true"),
@@ -930,6 +939,8 @@ export const env = createEnv({
process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
STRIPE_WEBHOOK_SIGNING_SECRET: process.env.STRIPE_WEBHOOK_SIGNING_SECRET,
+ LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE:
+ process.env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE,
SENTRY_AUTH_TOKEN: process.env.SENTRY_AUTH_TOKEN,
SENTRY_CSP_REPORT_URI: process.env.SENTRY_CSP_REPORT_URI,
LANGFUSE_RATE_LIMITS_ENABLED: process.env.LANGFUSE_RATE_LIMITS_ENABLED,
diff --git a/web/src/features/entitlements/server/getPlan.ts b/web/src/features/entitlements/server/getPlan.ts
index 0d40abf693..f5f4d1a8c4 100644
--- a/web/src/features/entitlements/server/getPlan.ts
+++ b/web/src/features/entitlements/server/getPlan.ts
@@ -1,6 +1,6 @@
import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeCatalogue";
import { env } from "@/src/env.mjs";
-import { type Plan } from "@langfuse/shared";
+import { chbPlanCodeToPlan, type Plan } from "@langfuse/shared";
import { type CloudConfigSchema } from "@langfuse/shared";
/**
@@ -33,6 +33,17 @@ export function getOrganizationPlanServerSide(
throw new Error(`Unhandled plan case: ${exhaustiveCheck}`);
}
}
+ // ClickHouse Billing plan. Keyed on organizationId, not planCode, so a
+ // CHB org can never fall through to stale Stripe state β€” the same
+ // CHB-wins precedence getBillingProvider enforces. A missing plan code
+ // (drifted, so dropped by cloudConfigSchema) fails open to the free tier,
+ // never to a paid one; the paid gate for usage thresholds reads bundleId
+ // instead, so a drifted code does not get a paying org ingestion-blocked.
+ if (cloudConfig.clickhouse?.organizationId) {
+ const { planCode } = cloudConfig.clickhouse;
+ return planCode ? chbPlanCodeToPlan[planCode] : "cloud:hobby";
+ }
+
// stripe plan via product id
if (cloudConfig.stripe?.activeProductId) {
const stripePlan = mapStripeProductIdToPlan(
diff --git a/worker/src/__tests__/thresholdProcessing.test.ts b/worker/src/__tests__/thresholdProcessing.test.ts
index 2e5837f956..b0bf5a694c 100644
--- a/worker/src/__tests__/thresholdProcessing.test.ts
+++ b/worker/src/__tests__/thresholdProcessing.test.ts
@@ -608,4 +608,32 @@ describe("processThresholds", () => {
expect(result.emailSent).toBe(false);
});
});
+
+ describe("CHB-billed orgs", () => {
+ it("skips enforcement for orgs with a CHB bundle (paid gate covers clickhouse.bundleId)", async () => {
+ const org = createMockOrg({
+ cloudCurrentCycleUsage: 0,
+ cloudConfig: {
+ clickhouse: {
+ organizationId: "0d5e6f7a-1b2c-4d3e-8f9a-0b1c2d3e4f5a",
+ bundleId: "bdl_123",
+ planCode: "core",
+ },
+ },
+ });
+
+ const result = await processThresholds(org, 250_000);
+
+ expect(result.updateData).toEqual({
+ orgId: "org-1",
+ cloudCurrentCycleUsage: 250_000,
+ cloudBillingCycleUpdatedAt: expect.any(Date),
+ cloudFreeTierUsageThresholdState: null,
+ shouldInvalidateCache: false,
+ });
+
+ expect(result.actionTaken).toBe("PAID_PLAN");
+ expect(result.emailSent).toBe(false);
+ });
+ });
});
diff --git a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
index d7edbac697..d32c0135d4 100644
--- a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
+++ b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts
@@ -1,4 +1,4 @@
-import { parseDbOrg, Prisma } from "@langfuse/shared";
+import { getBillingProvider, parseDbOrg, Prisma } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import Stripe from "stripe";
import { env } from "../../env";
@@ -159,6 +159,31 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {
// update progress to prevent job from being stalled
job.updateProgress(countProcessedOrgs / organizations.length);
+ // Defensive guard: the org selection above keys on stripe.customerId,
+ // which CHB-billed orgs never get (their `stripe` block stays empty).
+ // If that invariant ever breaks, skip + count instead of double-metering β€”
+ // CHB meters its orgs by polling our billing metrics API.
+ if (
+ getBillingProvider(org, {
+ cutoff: env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE,
+ }) !== "stripe"
+ ) {
+ traceException(
+ `[CLOUD USAGE METERING] Org ${org.id} resolves to a non-Stripe billing provider but carries a Stripe customer id, skipping`,
+ );
+ logger.error(
+ `[CLOUD USAGE METERING] Org ${org.id} resolves to a non-Stripe billing provider but carries a Stripe customer id, skipping`,
+ );
+ recordIncrement(
+ "langfuse.queue.cloud_usage_metering_queue.skipped_non_stripe_orgs",
+ 1,
+ {
+ unit: "organizations",
+ },
+ );
+ continue;
+ }
+
const stripeCustomerId = org.cloudConfig?.stripe?.customerId;
if (!stripeCustomerId) {
// should not happen
diff --git a/worker/src/ee/usageThresholds/thresholdProcessing.ts b/worker/src/ee/usageThresholds/thresholdProcessing.ts
index bce7b3bf9a..25d42db7d5 100644
--- a/worker/src/ee/usageThresholds/thresholdProcessing.ts
+++ b/worker/src/ee/usageThresholds/thresholdProcessing.ts
@@ -1,6 +1,10 @@
import type { Organization } from "@prisma/client";
import { prisma } from "@langfuse/shared/src/db";
-import { type ParsedOrganization, Role } from "@langfuse/shared";
+import {
+ hasPaidBillingState,
+ type ParsedOrganization,
+ Role,
+} from "@langfuse/shared";
import {
sendUsageThresholdWarningEmail,
sendUsageThresholdSuspensionEmail,
@@ -300,8 +304,8 @@ export async function processThresholds(
cumulativeUsage: number,
): Promise<ThresholdProcessingResult> {
// 1. Skip notifications if org is on a paid plan (check this first, regardless of enforcement flag)
- // This includes both Stripe subscriptions and manual plan overrides
- if (org.cloudConfig?.stripe?.activeSubscriptionId || org.cloudConfig?.plan) {
+ // This includes Stripe subscriptions, manual plan overrides, and CHB bundles
+ if (hasPaidBillingState(org)) {
// Build update data
const updateData: OrgUpdateData = {
orgId: org.id,
diff --git a/worker/src/env.ts b/worker/src/env.ts
index a40313f138..abc2ffff6d 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -24,6 +24,18 @@ const EnvSchema = z.object({
STRIPE_SECRET_KEY: z.string().optional(),
+ // ClickHouse Billing cutoff, shared with web via the provider resolver in
+ // @langfuse/shared (getBillingProvider). The worker only consults it in the
+ // defensive usage-metering guard; unset = CHB routing off. Date-only
+ // (YYYY-MM-DD) so the cutline is a single unambiguous instant of UTC
+ // midnight, which is what new Date() yields for a date-only string. Parsed
+ // here so every consumer gets the same instant; keep in sync with
+ // web/src/env.mjs.
+ LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE: z.iso
+ .date()
+ .optional()
+ .transform((date) => (date ? new Date(date) : null)),
+
LANGFUSE_CACHE_AUTOMATIONS_ENABLED: z.enum(["true", "false"]).default("true"),
LANGFUSE_CACHE_AUTOMATIONS_TTL_SECONDS: z.coerce.number().default(60),
LANGFUSE_S3_BATCH_EXPORT_ENABLED: z.enum(["true", "false"]).default("false"),