🪢 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(billing): Enforce Usage Threshold on Hobby Plan (DRAFT) (#9426)
Michael Fröhlichbee927e1593f
diff --git a/.env.prod.example b/.env.prod.exampleindex 47131d6748..a7989f48db 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -270,6 +270,12 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# Rate limiting# LANGFUSE_RATE_LIMITS_ENABLED=+# Free tier usage thresholds (Cloud deployments only)+# Enable the queue consumer that monitors free tier usage (default: true, but requires cloud region)+# QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED=true+# Enable enforcement: send emails and block orgs that exceed free tier limits (default: false)+# LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED=false+# Stripe# STRIPE_SECRET_KEY=# STRIPE_WEBHOOK_SIGNING_SECRET=diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex a078138686..df7019a7ed 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -78,6 +78,7 @@"@types/bcryptjs": "^2.4.6","bcryptjs": "^2.4.3","bullmq": "^5.34.10",+ "date-fns": "^3.3.1","dd-trace": "^5.65.0","decimal.js": "^10.4.3","exponential-backoff": "^3.1.2",diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex a21700ed29..c764f9646c 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -641,6 +641,10 @@ export type Organization = {updated_at: Generated<Timestamp>;cloud_config: unknown | null;metadata: unknown | null;+ cloud_billing_cycle_anchor: Generated<Timestamp | null>;+ cloud_billing_cycle_updated_at: Timestamp | null;+ cloud_current_cycle_usage: number | null;+ cloud_free_tier_usage_threshold_state: string | null;ai_features_enabled: Generated<boolean>;};export type OrganizationMembership = {diff --git a/packages/shared/prisma/migrations/20251001161539_organization_cloud_billing_cycle_columns/migration.sql b/packages/shared/prisma/migrations/20251001161539_organization_cloud_billing_cycle_columns/migration.sqlnew file mode 100644index 0000000000..234ab67508--- /dev/null+++ b/packages/shared/prisma/migrations/20251001161539_organization_cloud_billing_cycle_columns/migration.sql@@ -0,0 +1,21 @@+-- AlterTable+ALTER TABLE "organizations" ADD COLUMN "cloud_billing_cycle_anchor" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,+ADD COLUMN "cloud_billing_cycle_updated_at" TIMESTAMP(3),+ADD COLUMN "cloud_current_cycle_usage" INTEGER,+ADD COLUMN "cloud_free_tier_usage_threshold_state" TEXT;++-- Backfill cloud_billing_cycle_anchor for existing organizations:+-- Step 1: Set to NULL for orgs WITH active subscriptions (will be backfilled from Stripe by worker job)+UPDATE "organizations"+SET "cloud_billing_cycle_anchor" = NULL;++-- Step 2: Set to created_at for orgs WITHOUT active subscriptions (free tier orgs)+UPDATE "organizations"+SET "cloud_billing_cycle_anchor" = "created_at"+WHERE+ "cloud_config" IS NULL+ OR NOT (+ "cloud_config"::jsonb -> 'stripe' ? 'activeSubscriptionId'+ AND "cloud_config"::jsonb -> 'stripe' ->> 'activeSubscriptionId' IS NOT NULL+ AND "cloud_config"::jsonb -> 'stripe' ->> 'activeSubscriptionId' != ''+ );diff --git a/packages/shared/prisma/migrations/20251002153814_add_backfill_billing_cycle_anchors_background_migration/migration.sql b/packages/shared/prisma/migrations/20251002153814_add_backfill_billing_cycle_anchors_background_migration/migration.sqlnew file mode 100644index 0000000000..11e5949a27--- /dev/null+++ b/packages/shared/prisma/migrations/20251002153814_add_backfill_billing_cycle_anchors_background_migration/migration.sql@@ -0,0 +1,2 @@+INSERT INTO background_migrations (id, name, script, args)+VALUES ('0199b890-1093-7d1f-b662-be3c03527e93', '20250102_backfill_billing_cycle_anchors', 'backfillBillingCycleAnchors', '{}');diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex dc9933addc..9f9cfd6fcf 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -104,18 +104,22 @@ model VerificationToken {}model Organization {- id String @id @default(cuid())- name String- createdAt DateTime @default(now()) @map("created_at")- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")- cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema- metadata Json?- aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")- organizationMemberships OrganizationMembership[]- projects Project[]- MembershipInvitation MembershipInvitation[]- ApiKey ApiKey[]- surveys Survey[]+ id String @id @default(cuid())+ name String+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")+ cloudConfig Json? @map("cloud_config") // Langfuse Cloud, for zod schema see @/src/features/organizations/utils/cloudConfigSchema+ metadata Json?+ cloudBillingCycleAnchor DateTime? @default(now()) @map("cloud_billing_cycle_anchor")+ cloudBillingCycleUpdatedAt DateTime? @map("cloud_billing_cycle_updated_at")+ cloudCurrentCycleUsage Int? @map("cloud_current_cycle_usage")+ cloudFreeTierUsageThresholdState String? @map("cloud_free_tier_usage_threshold_state")+ aiFeaturesEnabled Boolean @default(false) @map("ai_features_enabled")+ organizationMemberships OrganizationMembership[]+ projects Project[]+ MembershipInvitation MembershipInvitation[]+ ApiKey ApiKey[]+ surveys Survey[]@@map("organizations")}diff --git a/packages/shared/src/interfaces/parseDbOrg.ts b/packages/shared/src/interfaces/parseDbOrg.tsindex b168ebd275..8e7bb7a575 100644--- a/packages/shared/src/interfaces/parseDbOrg.ts+++ b/packages/shared/src/interfaces/parseDbOrg.ts@@ -1,11 +1,11 @@import { type Organization } from "@prisma/client";import { CloudConfigSchema } from "./cloudConfigSchema";-type parsedOrg = Omit<Organization, "cloudConfig"> & {+export type ParsedOrganization = Omit<Organization, "cloudConfig"> & {cloudConfig: CloudConfigSchema | null;};-export function parseDbOrg(dbOrg: Organization): parsedOrg {+export function parseDbOrg(dbOrg: Organization): ParsedOrganization {const { cloudConfig, ...org } = dbOrg;const parsedCloudConfig = CloudConfigSchema.safeParse(cloudConfig);diff --git a/packages/shared/src/server/auth/invalidateApiKeys.ts b/packages/shared/src/server/auth/invalidateApiKeys.tsnew file mode 100644index 0000000000..153716cab3--- /dev/null+++ b/packages/shared/src/server/auth/invalidateApiKeys.ts@@ -0,0 +1,119 @@+import { prisma } from "../../db";+import { redis, safeMultiDel } from "..";+import { logger } from "../logger";++import { type ApiKey } from "../../db";++/**+ * Invalidate cached API keys from Redis cache+ *+ * Utility used by higher-level helpers to remove individual API keys from the cache,+ * e.g. after key rotation, revocation, or entitlement/plan changes.+ *+ * Note: This only invalidates the Redis cache, not the API keys themselves in the database.+ *+ * Behavior:+ * - Skips keys without a `fastHashedSecretKey`+ * - No-ops when Redis is not configured+ *+ * @param apiKeys - List of API key records to invalidate from cache+ * @param identifier - Context string for logging (e.g., org or project identifier)+ */+export async function invalidateCachedApiKeys(+ apiKeys: ApiKey[],+ identifier: string,+) {+ const hashKeys = apiKeys.map((key) => key.fastHashedSecretKey);++ const filteredHashKeys = hashKeys.filter((hash): hash is string =>+ Boolean(hash),+ );+ if (filteredHashKeys.length === 0) {+ logger.info("No valid keys to invalidate");+ return;+ }++ if (redis) {+ logger.info(`Invalidating API keys in redis for ${identifier}`);+ const keysToDelete = filteredHashKeys.map((hash) => `api-key:${hash}`);+ await safeMultiDel(redis, keysToDelete);+ }+}++/**+ * Invalidate all cached API keys for an organization from Redis cache+ *+ * This function is used when organization-level changes occur that affect API key validity,+ * such as:+ * - Plan changes (subscription created/updated/deleted)+ * - Usage threshold state changes (blocking/unblocking)+ * - Billing cycle changes+ *+ * Note: This only invalidates the Redis cache, not the API keys themselves in the database.+ *+ * @param orgId - The organization ID whose API keys should be invalidated from cache+ */+export async function invalidateCachedOrgApiKeys(orgId: string): Promise<void> {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ OR: [+ {+ project: {+ orgId,+ },+ },+ { orgId },+ ],+ },+ });++ const hashKeys = apiKeys+ .map((key) => key.fastHashedSecretKey)+ .filter((hash): hash is string => Boolean(hash));++ if (hashKeys.length === 0) {+ logger.info(`No valid API keys to invalidate for org ${orgId}`);+ return;+ }++ if (redis) {+ logger.info(`Invalidating API keys in redis for org ${orgId}`);+ const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);+ await safeMultiDel(redis, keysToDelete);+ }+}++/**+ * Invalidate all cached API keys for a project from Redis cache+ *+ * This function is used when project-level changes occur that affect API key validity.+ *+ * Note: This only invalidates the Redis cache, not the API keys themselves in the database.+ *+ * @param projectId - The project ID whose API keys should be invalidated from cache+ */+export async function invalidateCachedProjectApiKeys(+ projectId: string,+): Promise<void> {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ projectId: projectId,+ scope: "PROJECT",+ },+ });++ const hashKeys = apiKeys+ .map((key) => key.fastHashedSecretKey)+ .filter((hash): hash is string => Boolean(hash));++ if (hashKeys.length === 0) {+ logger.info(`No valid API keys to invalidate for project ${projectId}`);+ return;+ }++ if (redis) {+ logger.info(`Invalidating API keys in redis for project ${projectId}`);+ const keysToDelete = hashKeys.map((hash) => `api-key:${hash}`);+ await safeMultiDel(redis, keysToDelete);+ }+}diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex 3281103936..a3ac3faa38 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -16,6 +16,7 @@ const ApiKeyBaseSchema = z.object({orgId: z.string(),plan: z.enum(plans as unknown as [string, ...string[]]),rateLimitOverrides: CloudConfigRateLimit.nullish(),+ isIngestionSuspended: z.boolean(),});export const OrgEnrichedApiKey = z.discriminatedUnion("scope", [@@ -64,6 +65,7 @@ type ApiAccessScopeMetadata = {rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;apiKeyId: string;publicKey: string;+ isIngestionSuspended: boolean;};export type ApiAccessScopeIngestion = BaseApiAccessScope &diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex d5252588de..321e6730e9 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -3,12 +3,15 @@ export * from "./services/email/organizationInvitation/sendMembershipInvitationEexport * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";export * from "./services/email/billingAlert/sendBillingAlertEmail";+export * from "./services/email/usageThresholdWarning/sendUsageThresholdWarningEmail";+export * from "./services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail";export * from "./services/PromptService";export * from "./services/PromptService/types";export * from "./services/traces-ui-table-service";export * from "./services/InMemoryFilterService";export * from "./evalJobConfigCache";export * from "./auth/apiKeys";+export * from "./auth/invalidateApiKeys";export * from "./auth/customSsoProvider";export * from "./auth/gitHubEnterpriseProvider";export * from "./llm/fetchLLMCompletion";@@ -18,6 +21,7 @@ export * from "./llm/compileChatMessages";export * from "./llm/testModelCall";export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";+export * from "./utils/billingCycleHelpers";export * from "./clickhouse/client";export * from "./clickhouse/schemaUtils";export * from "./clickhouse/schema";@@ -30,6 +34,7 @@ export * from "./redis/redis";export * from "./redis/traceUpsert";export * from "./redis/createEvalQueue";export * from "./redis/cloudUsageMeteringQueue";+export * from "./redis/cloudFreeTierUsageThresholdQueue";export * from "./redis/getQueue";export * from "./redis/webhookQueue";export * from "./redis/traceDelete";diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex b6f98c4b1c..5e6749727b 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -259,6 +259,7 @@ export enum QueueName {IngestionQueue = "ingestion-queue", // Process single events with S3-mergeIngestionSecondaryQueue = "secondary-ingestion-queue", // Separates high priority + high throughput projects from other projects.CloudUsageMeteringQueue = "cloud-usage-metering-queue",+ CloudFreeTierUsageThresholdQueue = "cloud-free-tier-usage-threshold-queue",ExperimentCreate = "experiment-create-queue",PostHogIntegrationQueue = "posthog-integration-queue",PostHogIntegrationProcessingQueue = "posthog-integration-processing-queue",@@ -285,6 +286,7 @@ export enum QueueJobs {EvaluationExecution = "evaluation-execution-job",BatchExportJob = "batch-export-job",CloudUsageMeteringJob = "cloud-usage-metering-job",+ CloudFreeTierUsageThresholdJob = "cloud-free-tier-usage-threshold-job",OtelIngestionJob = "otel-ingestion-job",IngestionJob = "ingestion-job",IngestionSecondaryJob = "secondary-ingestion-job",@@ -429,4 +431,9 @@ export type TQueueJobTypes = {payload: EntityChangeEventType;name: QueueJobs.EntityChangeJob;};+ [QueueName.CloudFreeTierUsageThresholdQueue]: {+ timestamp: Date;+ id: string;+ name: QueueJobs.CloudFreeTierUsageThresholdJob;+ };};diff --git a/packages/shared/src/server/redis/cloudFreeTierUsageThresholdQueue.ts b/packages/shared/src/server/redis/cloudFreeTierUsageThresholdQueue.tsnew file mode 100644index 0000000000..e08501799e--- /dev/null+++ b/packages/shared/src/server/redis/cloudFreeTierUsageThresholdQueue.ts@@ -0,0 +1,68 @@+import { Queue } from "bullmq";+import { env } from "../../env";+import { QueueName, QueueJobs } from "../queues";+import {+ createNewRedisInstance,+ redisQueueRetryOptions,+ getQueuePrefix,+} from "./redis";+import { logger } from "../logger";++export class CloudFreeTierUsageThresholdQueue {+ private static instance: Queue | null = null;++ public static getInstance(): Queue | null {+ // Only enable in cloud deployments with Stripe configured+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ return null;+ }++ if (CloudFreeTierUsageThresholdQueue.instance) {+ return CloudFreeTierUsageThresholdQueue.instance;+ }++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ CloudFreeTierUsageThresholdQueue.instance = newRedis+ ? new Queue(QueueName.CloudFreeTierUsageThresholdQueue, {+ connection: newRedis,+ prefix: getQueuePrefix(QueueName.CloudFreeTierUsageThresholdQueue),+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100,+ attempts: 5,+ backoff: {+ type: "exponential",+ delay: 5000,+ },+ },+ })+ : null;++ CloudFreeTierUsageThresholdQueue.instance?.on("error", (err) => {+ logger.error("CloudFreeTierUsageThresholdQueue error", err);+ });++ if (CloudFreeTierUsageThresholdQueue.instance) {+ CloudFreeTierUsageThresholdQueue.instance.add(+ QueueJobs.CloudFreeTierUsageThresholdJob,+ {},+ {+ // Run at minute 35 of every hour (30 minutes after cloudUsageMetering at :05)+ repeat: { pattern: "35 * * * *" },+ },+ );++ CloudFreeTierUsageThresholdQueue.instance.add(+ QueueJobs.CloudFreeTierUsageThresholdJob,+ {},+ {},+ );+ }++ return CloudFreeTierUsageThresholdQueue.instance;+ }+}diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex 70fe2512c3..b866793ee0 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -2,6 +2,7 @@ import { Queue } from "bullmq";import { QueueName } from "../queues";import { BatchExportQueue } from "./batchExport";import { CloudUsageMeteringQueue } from "./cloudUsageMeteringQueue";+import { CloudFreeTierUsageThresholdQueue } from "./cloudFreeTierUsageThresholdQueue";import { DatasetRunItemUpsertQueue } from "./datasetRunItemUpsert";import { EvalExecutionQueue } from "./evalExecutionQueue";import { ExperimentCreateQueue } from "./experimentCreateQueue";@@ -39,6 +40,8 @@ export function getQueue(return BatchExportQueue.getInstance();case QueueName.CloudUsageMeteringQueue:return CloudUsageMeteringQueue.getInstance();+ case QueueName.CloudFreeTierUsageThresholdQueue:+ return CloudFreeTierUsageThresholdQueue.getInstance();case QueueName.DatasetRunItemUpsert:return DatasetRunItemUpsertQueue.getInstance();case QueueName.DatasetDelete:diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex 0c5ea1a5ff..a499dba31e 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -1635,3 +1635,66 @@ export const getGenerationsForPostHog = async function* (};}};++/**+ * Get observation counts grouped by project and day within a date range.+ *+ * Returns one row per project per day with the count of observations started on that day.+ * Uses half-open interval [startDate, endDate) for filtering based on start_time.+ *+ * @param startDate - Start of date range (inclusive)+ * @param endDate - End of date range (exclusive)+ * @returns Array of { count, projectId, date } objects+ *+ * @example+ * // Get observation counts for March 1-2, 2024+ * const counts = await getObservationCountsByProjectAndDay({+ * startDate: new Date('2024-03-01T00:00:00Z'),+ * endDate: new Date('2024-03-03T00:00:00Z')+ * });+ *+ * Note: Skips using FINAL (double counting risk) for faster and cheaper+ * queries against clickhouse. Generous 4x overcompensation before blocking allows+ * for usage aggregation to be meaningful.+ */+export const getObservationCountsByProjectAndDay = async ({+ startDate,+ endDate,+}: {+ startDate: Date;+ endDate: Date;+}) => {+ const query = `+ SELECT+ count(*) as count,+ project_id,+ toDate(start_time) as date+ FROM observations+ WHERE start_time >= {startDate: DateTime64(3)}+ AND start_time < {endDate: DateTime64(3)}+ GROUP BY project_id, toDate(start_time)+ `;++ const rows = await queryClickhouse<{+ count: string;+ project_id: string;+ date: string;+ }>({+ query,+ params: {+ startDate: convertDateToClickhouseDateTime(startDate),+ endDate: convertDateToClickhouseDateTime(endDate),+ },+ tags: {+ feature: "tracing",+ type: "observation",+ kind: "analytic",+ },+ });++ return rows.map((row) => ({+ count: Number(row.count),+ projectId: row.project_id,+ date: row.date,+ }));+};diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex db9106887e..496dd3cea6 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -1584,7 +1584,7 @@ export const getScoreMetadataById = async (id: string,source?: ScoreSourceType,) => {- const query = ` SELECT+ const query = ` SELECTmetadataFROM scores sWHERE s.project_id = {projectId: String}@@ -1616,3 +1616,67 @@ export const getScoreMetadataById = async ().shift();};++/**+ * Get score counts grouped by project and day within a date range.+ *+ * Returns one row per project per day with the count of scores created on that day.+ * Uses half-open interval [startDate, endDate) for filtering based on timestamp.+ *+ * @param startDate - Start of date range (inclusive)+ * @param endDate - End of date range (exclusive)+ * @returns Array of { count, projectId, date } objects+ *+ * @example+ * // Get score counts for March 1-2, 2024+ * const counts = await getScoreCountsByProjectAndDay({+ * startDate: new Date('2024-03-01T00:00:00Z'),+ * endDate: new Date('2024-03-03T00:00:00Z')+ * });+ *+ * Note: Skips using FINAL (double counting risk) for faster and cheaper+ * queries against clickhouse. Generous 4x overcompensation before blocking allows+ * for usage aggregation to be meaningful.+ *+ */+export const getScoreCountsByProjectAndDay = async ({+ startDate,+ endDate,+}: {+ startDate: Date;+ endDate: Date;+}) => {+ const query = `+ SELECT+ count(*) as count,+ project_id,+ toDate(timestamp) as date+ FROM scores+ WHERE timestamp >= {startDate: DateTime64(3)}+ AND timestamp < {endDate: DateTime64(3)}+ GROUP BY project_id, toDate(timestamp)+ `;++ const rows = await queryClickhouse<{+ count: string;+ project_id: string;+ date: string;+ }>({+ query,+ params: {+ startDate: convertDateToClickhouseDateTime(startDate),+ endDate: convertDateToClickhouseDateTime(endDate),+ },+ tags: {+ feature: "tracing",+ type: "score",+ kind: "analytic",+ },+ });++ return rows.map((row) => ({+ count: Number(row.count),+ projectId: row.project_id,+ date: row.date,+ }));+};diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex e4e30409b7..f546e6f365 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -1996,3 +1996,73 @@ export async function getAgentGraphData(params: {},});}++/**+ * Get trace counts grouped by project and day within a date range.+ *+ * Returns one row per project per day with the count of traces created on that day.+ * Uses half-open interval [startDate, endDate) for filtering.+ *+ * @param startDate - Start of date range (inclusive)+ * @param endDate - End of date range (exclusive)+ * @returns Array of { count, projectId, date } objects+ *+ * @example+ * // Get trace counts for March 1-2, 2024+ * const counts = await getTraceCountsByProjectAndDay({+ * startDate: new Date('2024-03-01T00:00:00Z'),+ * endDate: new Date('2024-03-03T00:00:00Z')+ * });+ * // Returns: [+ * // { count: 1500, projectId: 'proj-123', date: '2024-03-01' },+ * // { count: 1200, projectId: 'proj-123', date: '2024-03-02' },+ * // { count: 2300, projectId: 'proj-456', date: '2024-03-01' },+ * // ...+ * // ]+ *+ * Note: Skips using FINAL (double counting risk) for faster and cheaper+ * queries against clickhouse. Generous 4x overcompensation before blocking allows+ * for usage aggregation to be meaningful.+ *+ */+export const getTraceCountsByProjectAndDay = async ({+ startDate,+ endDate,+}: {+ startDate: Date;+ endDate: Date;+}) => {+ const query = `+ SELECT+ count(*) as count,+ project_id,+ toDate(timestamp) as date+ FROM traces+ WHERE timestamp >= {startDate: DateTime64(3)}+ AND timestamp < {endDate: DateTime64(3)}+ GROUP BY project_id, toDate(timestamp)+ `;++ const rows = await queryClickhouse<{+ count: string;+ project_id: string;+ date: string;+ }>({+ query,+ params: {+ startDate: convertDateToClickhouseDateTime(startDate),+ endDate: convertDateToClickhouseDateTime(endDate),+ },+ tags: {+ feature: "tracing",+ type: "trace",+ kind: "analytic",+ },+ });++ return rows.map((row) => ({+ count: Number(row.count),+ projectId: row.project_id,+ date: row.date,+ }));+};diff --git a/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsx b/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsxnew file mode 100644index 0000000000..f056a47c37--- /dev/null+++ b/packages/shared/src/server/services/email/usageThresholdSuspension/UsageThresholdSuspensionEmailTemplate.tsx@@ -0,0 +1,134 @@+import React from "react";+import {+ Body,+ Button,+ Container,+ Head,+ Heading,+ Hr,+ Html,+ Img,+ Section,+ Text,+ Tailwind,+ Preview,+} from "@react-email/components";++interface UsageThresholdSuspensionEmailProps {+ organizationName: string;+ currentUsage: number;+ limit: number;+ billingUrl: string;+ receiverEmail: string;+}++export const UsageThresholdSuspensionEmailTemplate = ({+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+}: UsageThresholdSuspensionEmailProps) => {+ return (+ <Html>+ <Head />+ <Preview>+ 🚨 URGENT: Ingestion suspended for "{organizationName}" -+ limit exceeded+ </Preview>+ <Tailwind>+ <Body className="bg-background my-auto mx-auto font-sans">+ <Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">+ <Section className="mt-8">+ <Img+ src="https://static.langfuse.com/langfuse_logo_transactional_email.png"+ width="40"+ height="40"+ alt="Langfuse"+ className="mx-auto my-0"+ />+ </Section>++ <Section>+ <Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">+ ⚠️ Ingestion Suspended+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ Your organization "{organizationName}" has exceeded+ the <strong>{limit.toLocaleString()} event limit</strong> for+ the free tier. Data ingestion has been suspended.+ </Text>+ </Section>++ <Section className="mt-8">+ <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-center">+ <Text className="text-red-600 text-sm font-medium m-0 mb-1">+ Current Usage+ </Text>+ <Text className="text-3xl font-bold text-red-700 m-0">+ {currentUsage.toLocaleString()}+ </Text>+ <Text className="text-red-600 text-xs m-0 mt-1">+ Free tier limit: {limit.toLocaleString()} events+ </Text>+ </div>+ </Section>++ <Section className="mt-8 text-center">+ <Button+ className="rounded bg-red-600 px-5 py-3 text-center text-xs font-semibold text-white no-underline"+ href={billingUrl}+ >+ Upgrade Now to Resume Ingestion+ </Button>+ </Section>++ <Section className="mt-8">+ <Heading className="text-black text-[18px] font-semibold">+ What's affected?+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ •{" "}+ <strong>+ New traces, observations, and scores cannot be ingested+ </strong>+ <br />+ • Existing data remains accessible+ <br />+ • Dashboard and analytics continue to work+ <br />• API calls to ingestion endpoints return 403 errors+ </Text>+ </Section>++ <Section className="mt-8">+ <Heading className="text-black text-[18px] font-semibold">+ How to resolve:+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ • <strong>Upgrade plan</strong> for unlimited events and premium+ features+ <br />• Or contact support for custom plans and enterprise+ options+ </Text>+ </Section>++ <Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" />++ <Section>+ <Text className="text-[#666666] text-[12px] leading-[24px]">+ This urgent notification was sent to {receiverEmail} regarding+ ingestion suspension for "{organizationName}".+ </Text>+ <Text className="text-[#666666] text-[12px] leading-[24px]">+ Need immediate help? Simply reply to this email and we'll+ assist you right away.+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};++export default UsageThresholdSuspensionEmailTemplate;diff --git a/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.ts b/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.tsnew file mode 100644index 0000000000..88f1fe2102--- /dev/null+++ b/packages/shared/src/server/services/email/usageThresholdSuspension/sendUsageThresholdSuspensionEmail.ts@@ -0,0 +1,63 @@+import { createTransport } from "nodemailer";+import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";+import { render } from "@react-email/render";+import { UsageThresholdSuspensionEmailTemplate } from "./UsageThresholdSuspensionEmailTemplate";+import { logger } from "../../../logger";++export interface UsageThresholdSuspensionEmailProps {+ env: Partial<+ Record<+ "EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL" | "NEXTAUTH_URL",+ string | undefined+ >+ >;+ organizationName: string;+ currentUsage: number;+ limit: number;+ billingUrl: string;+ receiverEmail: string;+}++export const sendUsageThresholdSuspensionEmail = async ({+ env,+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+}: UsageThresholdSuspensionEmailProps) => {+ if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {+ logger.error(+ "Missing environment variables for sending usage threshold suspension email.",+ );+ return;+ }++ try {+ const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));++ const emailSubject = `🚨 URGENT: Langfuse ingestion suspended for ${organizationName}`;+ const emailHtml = await render(+ UsageThresholdSuspensionEmailTemplate({+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+ }),+ );++ await mailer.sendMail({+ to: receiverEmail,+ from: {+ address: env.EMAIL_FROM_ADDRESS,+ name: "Langfuse",+ },+ replyTo: "[email protected]",+ subject: emailSubject,+ html: emailHtml,+ });+ } catch (error) {+ logger.error(`Failed to send ingestion suspended email`, error);+ }+};diff --git a/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsx b/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsxnew file mode 100644index 0000000000..d10db97a14--- /dev/null+++ b/packages/shared/src/server/services/email/usageThresholdWarning/UsageThresholdWarningEmailTemplate.tsx@@ -0,0 +1,130 @@+import React from "react";+import {+ Body,+ Button,+ Container,+ Head,+ Heading,+ Hr,+ Html,+ Img,+ Section,+ Text,+ Tailwind,+ Row,+ Column,+ Preview,+} from "@react-email/components";++interface UsageThresholdWarningEmailProps {+ organizationName: string;+ currentUsage: number;+ limit: number;+ billingUrl: string;+ receiverEmail: string;+}++export const UsageThresholdWarningEmailTemplate = ({+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+}: UsageThresholdWarningEmailProps) => {+ return (+ <Html>+ <Head />+ <Preview>+ Your Langfuse organization "{organizationName}" has reached{" "}+ {currentUsage.toLocaleString()} events+ </Preview>+ <Tailwind>+ <Body className="bg-background my-auto mx-auto font-sans">+ <Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">+ <Section className="mt-8">+ <Img+ src="https://static.langfuse.com/langfuse_logo_transactional_email.png"+ width="40"+ height="40"+ alt="Langfuse"+ className="mx-auto my-0"+ />+ </Section>++ <Section>+ <Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">+ Usage Threshold Reached+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ Your organization "{organizationName}" has reached{" "}+ <strong>{currentUsage.toLocaleString()}</strong> events out of+ your <strong>{limit.toLocaleString()}</strong> event limit for+ the free tier.+ </Text>+ </Section>++ <Section className="mt-8">+ <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">+ <Row>+ <Column className="text-center">+ <Text className="text-gray-600 text-sm font-medium m-0 mb-1">+ Current Usage+ </Text>+ <Text className="text-2xl font-bold text-gray-900 m-0">+ {currentUsage.toLocaleString()}+ </Text>+ </Column>+ <Column className="text-center">+ <Text className="text-gray-600 text-sm font-medium m-0 mb-1">+ Threshold+ </Text>+ <Text className="text-2xl font-bold text-gray-900 m-0">+ {limit.toLocaleString()}+ </Text>+ </Column>+ </Row>+ </div>+ </Section>++ <Section className="mt-8 text-center">+ <Button+ className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"+ href={billingUrl}+ >+ Upgrade Your Plan+ </Button>+ </Section>++ <Section className="mt-8">+ <Heading className="text-black text-[18px] font-semibold">+ What happens next?+ </Heading>+ <Text className="text-gray-700 text-sm leading-6">+ • Your usage continues to be tracked for a grace period+ <br />+ • Ingestion will soon be suspended and incoming observations,+ traces, and scores will be dropped unless you upgrade+ <br />• Upgrade now for unlimited events and premium features+ </Text>+ </Section>++ <Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" />++ <Section>+ <Text className="text-[#666666] text-[12px] leading-[24px]">+ This email was sent to {receiverEmail} regarding usage alerts+ for "{organizationName}".+ </Text>+ <Text className="text-[#666666] text-[12px] leading-[24px]">+ Questions? Simply reply to this email and we'll be happy to+ help.+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};++export default UsageThresholdWarningEmailTemplate;diff --git a/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.ts b/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.tsnew file mode 100644index 0000000000..69ac8b13d2--- /dev/null+++ b/packages/shared/src/server/services/email/usageThresholdWarning/sendUsageThresholdWarningEmail.ts@@ -0,0 +1,63 @@+import { createTransport } from "nodemailer";+import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";+import { render } from "@react-email/render";+import { UsageThresholdWarningEmailTemplate } from "./UsageThresholdWarningEmailTemplate";+import { logger } from "../../../logger";++export interface UsageThresholdWarningEmailProps {+ env: Partial<+ Record<+ "EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL" | "NEXTAUTH_URL",+ string | undefined+ >+ >;+ organizationName: string;+ currentUsage: number;+ limit: number;+ billingUrl: string;+ receiverEmail: string;+}++export const sendUsageThresholdWarningEmail = async ({+ env,+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+}: UsageThresholdWarningEmailProps) => {+ if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {+ logger.error(+ "Missing environment variables for sending usage notification email.",+ );+ return;+ }++ try {+ const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));++ const emailSubject = `Langfuse Free Tier: ${organizationName} usage reached ${limit.toLocaleString()} events`;+ const emailHtml = await render(+ UsageThresholdWarningEmailTemplate({+ organizationName,+ currentUsage,+ limit,+ billingUrl,+ receiverEmail,+ }),+ );++ await mailer.sendMail({+ to: receiverEmail,+ from: {+ address: env.EMAIL_FROM_ADDRESS,+ name: "Langfuse",+ },+ replyTo: "[email protected]",+ subject: emailSubject,+ html: emailHtml,+ });+ } catch (error) {+ logger.error(`Failed to send usage notification email`, error);+ }+};diff --git a/packages/shared/src/server/utils/billingCycleHelpers.ts b/packages/shared/src/server/utils/billingCycleHelpers.tsnew file mode 100644index 0000000000..7070cb780a--- /dev/null+++ b/packages/shared/src/server/utils/billingCycleHelpers.ts@@ -0,0 +1,116 @@+import { getDaysInMonth, subMonths } from "date-fns";+import type { Organization } from "@prisma/client";++/**+ * Start of day in UTC (00:00:00.000Z)+ */+export function startOfDayUTC(date: Date): Date {+ const d = new Date(date);+ return new Date(+ Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()),+ );+}++/**+ * End of day in UTC (23:59:59.999Z)+ */+export function endOfDayUTC(date: Date): Date {+ const d = new Date(date);+ return new Date(+ Date.UTC(+ d.getUTCFullYear(),+ d.getUTCMonth(),+ d.getUTCDate(),+ 23,+ 59,+ 59,+ 999,+ ),+ );+}++/**+ * Get billing cycle anchor with fallback to createdAt+ * Always returns start of day in UTC+ */+export function getBillingCycleAnchor(org: Organization): Date {+ return org.cloudBillingCycleAnchor+ ? startOfDayUTC(org.cloudBillingCycleAnchor)+ : startOfDayUTC(org.createdAt);+}++/**+ * Calculate the billing cycle start date for the billing cycle containing the reference date+ * Handles month boundaries correctly (e.g., 31st → 28/29/30 for shorter months)+ *+ * Returns the most recent occurrence of the billing cycle day that is on or before the reference date+ *+ * Example: If anchor is Jan 31 and reference is Feb 15:+ * - Feb cycle day would be Feb 29 (adjusted from 31 due to leap year)+ * - Since Feb 15 < Feb 29, we're still in Jan's cycle → return Jan 31+ *+ * Example: If anchor is Jan 15 and reference is Feb 20:+ * - Feb cycle day is Feb 15+ * - Since Feb 20 >= Feb 15, we're in Feb's cycle → return Feb 15+ */+export function getBillingCycleStart(+ org: Organization,+ referenceDate: Date,+): Date {+ const anchor = getBillingCycleAnchor(org);+ const dayOfMonth = anchor.getUTCDate(); // e.g. 31++ // Get reference month/year in UTC+ const refYear = referenceDate.getUTCFullYear();+ const refMonth = referenceDate.getUTCMonth();++ // Calculate adjusted day for current month (handles 31 → 28/29/30)+ const daysInRefMonth = getDaysInMonth(+ new Date(Date.UTC(refYear, refMonth, 1)),+ );+ const adjustedDay = Math.min(dayOfMonth, daysInRefMonth);++ const currentMonthCycleStart = new Date(+ Date.UTC(refYear, refMonth, adjustedDay),+ );++ // If current month's cycle start is after reference date, use previous month+ if (currentMonthCycleStart > referenceDate) {+ const prevDate = subMonths(new Date(Date.UTC(refYear, refMonth, 1)), 1);+ const daysInPrevMonth = getDaysInMonth(prevDate);+ return new Date(+ Date.UTC(+ prevDate.getUTCFullYear(),+ prevDate.getUTCMonth(),+ Math.min(dayOfMonth, daysInPrevMonth),+ ),+ );+ }++ return currentMonthCycleStart;+}++/**+ * Calculate the maximum number of days to look back for a billing cycle+ *+ * Returns the number of days in the previous month relative to the reference date.+ * This ensures we capture a full billing cycle when processing usage.+ *+ * Examples:+ * - Reference date: March 15, 2024 → Look back 29 days (Feb has 29 days in 2024)+ * - Reference date: April 15, 2024 → Look back 31 days (March has 31 days)+ * - Reference date: May 15, 2024 → Look back 30 days (April has 30 days)+ *+ * @param referenceDate - The current date (typically "now")+ * @returns Number of days to look back to cover the full billing cycle+ */+export function getDaysToLookBack(referenceDate: Date): number {+ const refYear = referenceDate.getUTCFullYear();+ const refMonth = referenceDate.getUTCMonth();++ // Get the previous month+ const prevMonthDate = subMonths(new Date(Date.UTC(refYear, refMonth, 1)), 1);++ // Return the number of days in the previous month+ return getDaysInMonth(prevMonthDate);+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6817ac5c4e..bfb662b465 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -200,6 +200,9 @@ importers:bullmq:specifier: ^5.34.10version: 5.34.10+ date-fns:+ specifier: ^3.3.1+ version: 3.6.0dd-trace:specifier: ^5.65.0version: 5.65.0@@ -11044,7 +11047,7 @@ packages:resolution: {integrity: sha512-39olGaX2djYUdhaQQHDZ0T0GwEp+5f9UB9HmEP0qHfdQHIq0xGQZuAZ5TLnJIc/88SrPLpEflPC+xUqOTv3c5g==}- deprecated: < 22.8.2 is no longer supported+ deprecated: < 24.9.0 is no longer supportedresolution: {integrity: sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==}diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.tsindex 308c23b2fc..952ab2b281 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/api-auth.servertest.ts@@ -317,6 +317,7 @@ describe("Authenticate API calls", () => {},],createdAt: apiKey?.createdAt.toISOString(),+ isIngestionSuspended: expect.any(Boolean),});await prisma.organization.update({@@ -435,6 +436,7 @@ describe("Authenticate API calls", () => {},],createdAt: apiKey?.createdAt.toISOString(),+ isIngestionSuspended: expect.any(Boolean),});await prisma.organization.update({@@ -547,6 +549,7 @@ describe("Authenticate API calls", () => {createdAt: expect.any(String),lastUsedAt: null,expiresAt: null,+ isIngestionSuspended: expect.any(Boolean),projectId: expect.any(String),orgId: "seed-org-id",plan: "cloud:hobby",@@ -643,6 +646,7 @@ describe("Authenticate API calls", () => {plan: "cloud:hobby",createdAt: apiKey?.createdAt.toISOString(),scope: "PROJECT",+ isIngestionSuspended: expect.any(Boolean),});await new ApiAuthService(prisma, redis).deleteApiKey(@@ -717,7 +721,7 @@ describe("Authenticate API calls", () => {);expect(cachedKey).not.toBeNull();- await new ApiAuthService(prisma, redis).invalidateOrgApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys("seed-org-id",);@@ -737,7 +741,7 @@ describe("Authenticate API calls", () => {},});- await new ApiAuthService(prisma, redis).invalidateOrgApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys("seed-org-id",);@@ -748,7 +752,7 @@ describe("Authenticate API calls", () => {it("if no keys in redis, invalidating org keys without fast hash should do nothing", async () => {await createAPIKey();- await new ApiAuthService(prisma, redis).invalidateOrgApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys("seed-org-id",);@@ -777,7 +781,7 @@ describe("Authenticate API calls", () => {);expect(cachedKey).not.toBeNull();- await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",);@@ -797,7 +801,7 @@ describe("Authenticate API calls", () => {},});- await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",);@@ -815,7 +819,7 @@ describe("Authenticate API calls", () => {},});- await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(+ await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",);diff --git a/web/src/__tests__/billingCycleHelpers.servertest.ts b/web/src/__tests__/billingCycleHelpers.servertest.tsnew file mode 100644index 0000000000..ef359722b9--- /dev/null+++ b/web/src/__tests__/billingCycleHelpers.servertest.ts@@ -0,0 +1,406 @@+/** @jest-environment node */+import {+ getBillingCycleAnchor,+ getBillingCycleStart,+ getDaysToLookBack,+ startOfDayUTC,+ endOfDayUTC,+} from "@langfuse/shared/src/server";+import { type Organization } from "@langfuse/shared";++describe("getBillingCycleAnchor", () => {+ it("returns cloudBillingCycleAnchor when set", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T10:30:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ const result = getBillingCycleAnchor(org);++ expect(result).toEqual(new Date("2024-01-15T00:00:00Z")); // start of day+ });++ it("falls back to createdAt when cloudBillingCycleAnchor is null", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: null,+ createdAt: new Date("2024-01-01T10:30:00Z"),+ } as Organization;++ const result = getBillingCycleAnchor(org);++ expect(result).toEqual(new Date("2024-01-01T00:00:00Z")); // start of day+ });+});++describe("getBillingCycleStart", () => {+ it("handles anchor on 15th consistently across months", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // March 15th reference → cycle starts March 15+ expect(getBillingCycleStart(org, new Date("2024-03-20T10:00:00Z"))).toEqual(+ new Date("2024-03-15T00:00:00Z"),+ );++ // February 10th reference → cycle starts January 15 (previous month)+ expect(getBillingCycleStart(org, new Date("2024-02-10T10:00:00Z"))).toEqual(+ new Date("2024-01-15T00:00:00Z"),+ );+ });++ it("handles anchor on 31st → adjusts to last day of month", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-31T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // February (29 days in 2024, leap year) - reference after cycle day → Feb 29+ expect(getBillingCycleStart(org, new Date("2024-03-05T10:00:00Z"))).toEqual(+ new Date("2024-02-29T00:00:00Z"),+ );++ // April (30 days) - reference after cycle day → April 30+ expect(getBillingCycleStart(org, new Date("2024-05-05T10:00:00Z"))).toEqual(+ new Date("2024-04-30T00:00:00Z"),+ );++ // March (31 days) - reference after cycle day → March 31+ expect(getBillingCycleStart(org, new Date("2024-04-05T10:00:00Z"))).toEqual(+ new Date("2024-03-31T00:00:00Z"),+ );+ });++ it("handles leap year February correctly", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-31T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // 2024 is leap year - reference after Feb 29 → Feb 29+ expect(getBillingCycleStart(org, new Date("2024-03-01T10:00:00Z"))).toEqual(+ new Date("2024-02-29T00:00:00Z"),+ );++ // 2025 is not leap year - reference after Feb 28 → Feb 28+ const org2025 = {+ ...org,+ cloudBillingCycleAnchor: new Date("2025-01-31T00:00:00Z"),+ } as Organization;++ expect(+ getBillingCycleStart(org2025, new Date("2025-03-01T10:00:00Z")),+ ).toEqual(new Date("2025-02-28T00:00:00Z"));+ });++ it("handles reference date before cycle start in current month", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ createdAt: new Date("2024-01-01T00:00:00Z"),+ } as Organization;++ // Feb 10 (before Feb 15) → goes back to Jan 15+ expect(getBillingCycleStart(org, new Date("2024-02-10T10:00:00Z"))).toEqual(+ new Date("2024-01-15T00:00:00Z"),+ );++ // Feb 15 exactly → stays at Feb 15+ expect(getBillingCycleStart(org, new Date("2024-02-15T00:00:00Z"))).toEqual(+ new Date("2024-02-15T00:00:00Z"),+ );++ // Feb 20 (after Feb 15) → stays at Feb 15+ expect(getBillingCycleStart(org, new Date("2024-02-20T10:00:00Z"))).toEqual(+ new Date("2024-02-15T00:00:00Z"),+ );+ });++ it("handles month boundaries with 31st anchor across year transition", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2023-12-31T00:00:00Z"),+ createdAt: new Date("2023-12-01T00:00:00Z"),+ } as Organization;++ // Jan 2024 - reference after Jan 31 → Jan 31+ expect(getBillingCycleStart(org, new Date("2024-02-05T10:00:00Z"))).toEqual(+ new Date("2024-01-31T00:00:00Z"),+ );++ // Feb 2024 (leap year) - reference after Feb 29 → Feb 29+ expect(getBillingCycleStart(org, new Date("2024-03-01T10:00:00Z"))).toEqual(+ new Date("2024-02-29T00:00:00Z"),+ );+ });++ it("handles year crossover with December anchor", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: new Date("2023-12-15T00:00:00Z"),+ createdAt: new Date("2023-12-01T00:00:00Z"),+ } as Organization;++ // Jan 10 (before Jan 15) → goes back to Dec 15 previous year+ expect(getBillingCycleStart(org, new Date("2024-01-10T10:00:00Z"))).toEqual(+ new Date("2023-12-15T00:00:00Z"),+ );++ // Jan 15 exactly → Jan 15 current year+ expect(getBillingCycleStart(org, new Date("2024-01-15T00:00:00Z"))).toEqual(+ new Date("2024-01-15T00:00:00Z"),+ );++ // Jan 20 (after Jan 15) → Jan 15 current year+ expect(getBillingCycleStart(org, new Date("2024-01-20T10:00:00Z"))).toEqual(+ new Date("2024-01-15T00:00:00Z"),+ );+ });++ it("uses createdAt as fallback when cloudBillingCycleAnchor is null", () => {+ const org = {+ id: "org-1",+ cloudBillingCycleAnchor: null,+ createdAt: new Date("2024-01-15T10:30:00Z"),+ } as Organization;++ expect(getBillingCycleStart(org, new Date("2024-02-20T10:00:00Z"))).toEqual(+ new Date("2024-02-15T00:00:00Z"),+ );+ });+});++describe("getDaysToLookBack", () => {+ it("returns days in previous month for March reference (leap year)", () => {+ // March 2024, previous month is Feb with 29 days (leap year)+ const result = getDaysToLookBack(new Date("2024-03-15T10:00:00Z"));+ expect(result).toBe(29);+ });++ it("returns days in previous month for April reference", () => {+ // April 2024, previous month is March with 31 days+ const result = getDaysToLookBack(new Date("2024-04-15T10:00:00Z"));+ expect(result).toBe(31);+ });++ it("returns days in previous month for May reference", () => {+ // May 2024, previous month is April with 30 days+ const result = getDaysToLookBack(new Date("2024-05-15T10:00:00Z"));+ expect(result).toBe(30);+ });++ it("returns days in previous month for March in non-leap year", () => {+ // March 2025, previous month is Feb with 28 days (non-leap year)+ const result = getDaysToLookBack(new Date("2025-03-15T10:00:00Z"));+ expect(result).toBe(28);+ });++ it("handles January reference (previous month is December)", () => {+ // January 2024, previous month is December 2023 with 31 days+ const result = getDaysToLookBack(new Date("2024-01-15T10:00:00Z"));+ expect(result).toBe(31);+ });+});++describe("startOfDayUTC", () => {+ it("returns start of day in UTC for a date with time", () => {+ const result = startOfDayUTC(new Date("2024-09-30T14:30:45.123Z"));+ expect(result).toEqual(new Date("2024-09-30T00:00:00.000Z"));+ });++ it("returns same date if already at start of day UTC", () => {+ const result = startOfDayUTC(new Date("2024-09-30T00:00:00.000Z"));+ expect(result).toEqual(new Date("2024-09-30T00:00:00.000Z"));+ });++ it("handles date at end of day", () => {+ const result = startOfDayUTC(new Date("2024-09-30T23:59:59.999Z"));+ expect(result).toEqual(new Date("2024-09-30T00:00:00.000Z"));+ });++ it("handles date created in non-UTC timezone", () => {+ // Create a date from local time components (e.g., Germany timezone)+ const localDate = new Date("2024-09-30T14:30:00+02:00"); // 14:30 in Berlin = 12:30 UTC+ const result = startOfDayUTC(localDate);+ // Should return 2024-09-30 00:00:00 UTC regardless of input timezone+ expect(result).toEqual(new Date("2024-09-30T00:00:00.000Z"));+ });+});++describe("endOfDayUTC", () => {+ it("returns end of day in UTC for a date with time", () => {+ const result = endOfDayUTC(new Date("2024-09-30T14:30:45.123Z"));+ expect(result).toEqual(new Date("2024-09-30T23:59:59.999Z"));+ });++ it("returns end of day if already at start of day UTC", () => {+ const result = endOfDayUTC(new Date("2024-09-30T00:00:00.000Z"));+ expect(result).toEqual(new Date("2024-09-30T23:59:59.999Z"));+ });++ it("returns same date if already at end of day UTC", () => {+ const result = endOfDayUTC(new Date("2024-09-30T23:59:59.999Z"));+ expect(result).toEqual(new Date("2024-09-30T23:59:59.999Z"));+ });++ it("handles date created in non-UTC timezone", () => {+ // Create a date from local time components (e.g., Germany timezone)+ const localDate = new Date("2024-09-30T14:30:00+02:00"); // 14:30 in Berlin = 12:30 UTC+ const result = endOfDayUTC(localDate);+ // Should return 2024-09-30 23:59:59.999 UTC regardless of input timezone+ expect(result).toEqual(new Date("2024-09-30T23:59:59.999Z"));+ });++ it("handles year boundary", () => {+ const result = endOfDayUTC(new Date("2024-12-31T10:00:00Z"));+ expect(result).toEqual(new Date("2024-12-31T23:59:59.999Z"));+ });+});++describe("Organization cloudBillingCycleAnchor persistence", () => {+ it("should preserve startOfDayUTC when creating and reading organization", async () => {+ const { prisma } = await import("@langfuse/shared/src/db");++ const inputDate = new Date("2024-09-30T14:30:45.123Z");+ const expectedDate = startOfDayUTC(inputDate); // 2024-09-30T00:00:00.000Z++ // Create organization with billing cycle anchor+ const org = await prisma.organization.create({+ data: {+ name: `Test Org ${Date.now()}`,+ cloudBillingCycleAnchor: expectedDate,+ },+ });++ // Read back from database+ const readOrg = await prisma.organization.findUnique({+ where: { id: org.id },+ });++ expect(readOrg).not.toBeNull();+ expect(readOrg!.cloudBillingCycleAnchor).toEqual(expectedDate);+ expect(readOrg!.cloudBillingCycleAnchor?.toISOString()).toBe(+ "2024-09-30T00:00:00.000Z",+ );++ // Cleanup+ await prisma.organization.delete({ where: { id: org.id } });+ });++ it("should preserve endOfDayUTC when creating and reading organization", async () => {+ const { prisma } = await import("@langfuse/shared/src/db");++ const inputDate = new Date("2024-09-30T14:30:45.123Z");+ const expectedDate = endOfDayUTC(inputDate); // 2024-09-30T23:59:59.999Z++ // Create organization with billing cycle anchor+ const org = await prisma.organization.create({+ data: {+ name: `Test Org ${Date.now()}`,+ cloudBillingCycleAnchor: expectedDate,+ },+ });++ // Read back from database+ const readOrg = await prisma.organization.findUnique({+ where: { id: org.id },+ });++ expect(readOrg).not.toBeNull();+ expect(readOrg!.cloudBillingCycleAnchor).toEqual(expectedDate);+ expect(readOrg!.cloudBillingCycleAnchor?.toISOString()).toBe(+ "2024-09-30T23:59:59.999Z",+ );++ // Cleanup+ await prisma.organization.delete({ where: { id: org.id } });+ });++ it("should preserve random time in UTC when creating and reading organization", async () => {+ const { prisma } = await import("@langfuse/shared/src/db");++ // Random time in the middle of the day+ const randomDate = new Date("2024-09-30T14:37:22.456Z");++ // Create organization with billing cycle anchor+ const org = await prisma.organization.create({+ data: {+ name: `Test Org ${Date.now()}`,+ cloudBillingCycleAnchor: randomDate,+ },+ });++ // Read back from database+ const readOrg = await prisma.organization.findUnique({+ where: { id: org.id },+ });++ expect(readOrg).not.toBeNull();+ expect(readOrg!.cloudBillingCycleAnchor).toEqual(randomDate);+ expect(readOrg!.cloudBillingCycleAnchor?.toISOString()).toBe(+ "2024-09-30T14:37:22.456Z",+ );++ // Cleanup+ await prisma.organization.delete({ where: { id: org.id } });+ });++ it("should handle null cloudBillingCycleAnchor correctly", async () => {+ const { prisma } = await import("@langfuse/shared/src/db");++ // Create organization without billing cycle anchor+ const org = await prisma.organization.create({+ data: {+ name: `Test Org ${Date.now()}`,+ cloudBillingCycleAnchor: null,+ },+ });++ // Read back from database+ const readOrg = await prisma.organization.findUnique({+ where: { id: org.id },+ });++ expect(readOrg).not.toBeNull();+ expect(readOrg!.cloudBillingCycleAnchor).toBeNull();++ // Cleanup+ await prisma.organization.delete({ where: { id: org.id } });+ });++ it("should correctly normalize different timezone inputs to UTC", async () => {+ const { prisma } = await import("@langfuse/shared/src/db");++ // Date created with timezone offset (Berlin time, +02:00)+ const berlinTime = new Date("2024-09-30T14:30:00+02:00"); // 12:30 UTC+ const expectedUTC = startOfDayUTC(berlinTime); // 2024-09-30T00:00:00.000Z++ // Create organization with billing cycle anchor+ const org = await prisma.organization.create({+ data: {+ name: `Test Org ${Date.now()}`,+ cloudBillingCycleAnchor: expectedUTC,+ },+ });++ // Read back from database+ const readOrg = await prisma.organization.findUnique({+ where: { id: org.id },+ });++ expect(readOrg).not.toBeNull();+ expect(readOrg!.cloudBillingCycleAnchor).toEqual(expectedUTC);+ expect(readOrg!.cloudBillingCycleAnchor?.toISOString()).toBe(+ "2024-09-30T00:00:00.000Z",+ );++ // Cleanup+ await prisma.organization.delete({ where: { id: org.id } });+ });+});diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 4cd2c48c54..2fbed7341d 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -113,6 +113,7 @@ export const getQueues = () => {QueueName.BlobStorageIntegrationQueue,QueueName.DeadLetterRetryQueue,QueueName.PostHogIntegrationQueue,+ QueueName.CloudFreeTierUsageThresholdQueue,];return queuesdiff --git a/web/src/ee/features/admin-api/server/projects/projectById/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/index.tsindex dcc5013bf7..013856dc8d 100644--- a/web/src/ee/features/admin-api/server/projects/projectById/index.ts+++ b/web/src/ee/features/admin-api/server/projects/projectById/index.ts@@ -109,7 +109,9 @@ export async function handleDeleteProject() {try {// API keys need to be deleted from cache. Otherwise, they will still be valid.- await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(projectId);+ await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys(+ projectId,+ );// Delete API keys from DBawait prisma.apiKey.deleteMany({diff --git a/web/src/ee/features/billing/server/stripeWebhookHandler.ts b/web/src/ee/features/billing/server/stripeWebhookHandler.tsindex 1674c87933..5d971b3b65 100644--- a/web/src/ee/features/billing/server/stripeWebhookHandler.ts+++ b/web/src/ee/features/billing/server/stripeWebhookHandler.ts@@ -13,9 +13,13 @@ import {type Organization,parseDbOrg,} from "@langfuse/shared";-import { traceException, redis, logger } from "@langfuse/shared/src/server";+import {+ traceException,+ logger,+ invalidateCachedOrgApiKeys,+ startOfDayUTC,+} from "@langfuse/shared/src/server";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { sendBillingAlertEmail } from "@langfuse/shared/src/server";import { Role } from "@langfuse/shared";import { UsageAlertService } from "@/src/ee/features/billing/server/usageAlertService";@@ -356,6 +360,23 @@ async function ensureMetadataIsSetOnStripeSubscription(}}+/**+ * Update organization billing cycle anchor.+ * When no anchor is provided, sets to start of current day in UTC.+ * When an anchor is provided, stores it as-is (caller is responsible for UTC normalization).+ */+export async function updateOrgBillingCycleAnchor(+ orgId: string,+ anchor?: Date,+) {+ return await prisma.organization.update({+ where: { id: orgId },+ data: {+ cloudBillingCycleAnchor: anchor ?? startOfDayUTC(new Date()),+ },+ });+}+async function handleSubscriptionChanged(subscription: Stripe.Subscription,action: "created" | "deleted" | "updated",@@ -532,6 +553,16 @@ async function handleSubscriptionChanged(},});+ // Set billing cycle anchor on first paid subscription from Stripe+ if (action === "created" && subscription.billing_cycle_anchor) {+ // Convert unix timestamp (seconds) to Date object+ const anchorDate = new Date(subscription.billing_cycle_anchor * 1000);+ await updateOrgBillingCycleAnchor(parsedOrg.id, anchorDate);+ }++ // Invalidate API keys in Redis for it to be updated+ await invalidateCachedOrgApiKeys(parsedOrg.id);+void auditLog({session: {user: { id: "stripe-webhook" },@@ -567,6 +598,10 @@ async function handleSubscriptionChanged(},});+ // Reset billing cycle anchor on downgrade to hobby to start of today+ await updateOrgBillingCycleAnchor(parsedOrg.id);+ await invalidateCachedOrgApiKeys(parsedOrg.id);+void auditLog({session: {user: { id: "stripe-webhook" },@@ -581,9 +616,6 @@ async function handleSubscriptionChanged(});}- // need to update the plan in the api keys- await new ApiAuthService(prisma, redis).invalidateOrgApiKeys(parsedOrg.id);-return;}diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex a47d5b6593..69a0e5b405 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -14,6 +14,7 @@ import { TRPCError } from "@trpc/server";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripeBillingService";+import { env } from "@/src/env.mjs";export const organizationsRouter = createTRPCRouter({@@ -157,7 +158,7 @@ export const organizationsRouter = createTRPCRouter({});// the api keys contain which org they belong to, so we need to remove them from Redis- await new ApiAuthService(ctx.prisma, redis).invalidateOrgApiKeys(+ await new ApiAuthService(ctx.prisma, redis).invalidateCachedOrgApiKeys(input.orgId,);diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex 49e16d8ce3..e73ef4683e 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -150,9 +150,10 @@ export const projectsRouter = createTRPCRouter({});// API keys need to be deleted from cache. Otherwise, they will still be valid.- await new ApiAuthService(ctx.prisma, redis).invalidateProjectApiKeys(- input.projectId,- );+ await new ApiAuthService(+ ctx.prisma,+ redis,+ ).invalidateCachedProjectApiKeys(input.projectId);// Delete API keys from DBawait ctx.prisma.apiKey.deleteMany({@@ -264,9 +265,10 @@ export const projectsRouter = createTRPCRouter({// API keys need to be deleted from cache. Otherwise, they will still be valid.// It has to be called after the db is done to prevent new API keys from being cached.- await new ApiAuthService(ctx.prisma, redis).invalidateProjectApiKeys(- input.projectId,- );+ await new ApiAuthService(+ ctx.prisma,+ redis,+ ).invalidateCachedProjectApiKeys(input.projectId);}),environmentFilterOptions: protectedProjectProcedurediff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 3ae098e920..8bed724f76 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -9,7 +9,9 @@ import {logger,instrumentAsync,addUserToSpan,- safeMultiDel,+ invalidateCachedApiKeys as invalidateCachedApiKeysShared,+ invalidateCachedOrgApiKeys as invalidateCachedOrgApiKeysShared,+ invalidateCachedProjectApiKeys as invalidateCachedProjectApiKeysShared,} from "@langfuse/shared/src/server";import {type PrismaClient,@@ -36,52 +38,16 @@ export class ApiAuthService {// this function needs to be called, when the organisation is updated// - when projects move across organisations, the orgId in the API key cache needs to be updated// - when the plan of the org changes, the plan in the API key cache needs to be updated as well- async invalidate(apiKeys: ApiKey[], identifier: string) {- const hashKeys = apiKeys.map((key) => key.fastHashedSecretKey);-- const filteredHashKeys = hashKeys.filter((hash): hash is string =>- Boolean(hash),- );- if (filteredHashKeys.length === 0) {- logger.info("No valid keys to invalidate");- return;- }-- if (this.redis) {- logger.info(`Invalidating API keys in redis for ${identifier}`);- const keysToDelete = filteredHashKeys.map((hash) =>- this.createRedisKey(hash),- );- await safeMultiDel(this.redis, keysToDelete);- }+ async invalidateCachedApiKeys(apiKeys: ApiKey[], identifier: string) {+ await invalidateCachedApiKeysShared(apiKeys, identifier);}- async invalidateOrgApiKeys(orgId: string) {- const apiKeys = await this.prisma.apiKey.findMany({- where: {- OR: [- {- project: {- orgId: orgId,- },- },- { orgId },- ],- },- });-- await this.invalidate(apiKeys, `org ${orgId}`);+ async invalidateCachedOrgApiKeys(orgId: string) {+ await invalidateCachedOrgApiKeysShared(orgId);}- async invalidateProjectApiKeys(projectId: string) {- const apiKeys = await this.prisma.apiKey.findMany({- where: {- projectId: projectId,- scope: "PROJECT",- },- });-- await this.invalidate(apiKeys, `project ${projectId}`);+ async invalidateCachedProjectApiKeys(projectId: string) {+ await invalidateCachedProjectApiKeysShared(projectId);}/**@@ -107,7 +73,7 @@ export class ApiAuthService {// if redis is available, delete the key from there as well// delete from redis even if caching is disabled via env for consistency- this.invalidate([apiKey], `key ${id}`);+ this.invalidateCachedApiKeys([apiKey], `key ${id}`);await this.prisma.apiKey.delete({where: {@@ -226,6 +192,7 @@ export class ApiAuthService {apiKeyId: finalApiKey.id,scope: finalApiKey.scope,publicKey,+ isIngestionSuspended: finalApiKey.isIngestionSuspended,},};}@@ -241,7 +208,7 @@ export class ApiAuthService {);}- const { orgId, cloudConfig } =+ const { orgId, cloudConfig, cloudFreeTierUsageThresholdState } =this.extractOrgIdAndCloudConfig(dbKey);addUserToSpan({@@ -261,6 +228,8 @@ export class ApiAuthService {apiKeyId: dbKey.id,scope: dbKey.scope,publicKey,+ isIngestionSuspended:+ cloudFreeTierUsageThresholdState === "BLOCKED",},};}@@ -427,6 +396,7 @@ export class ApiAuthService {createdAt: Date;updatedAt: Date;cloudConfig: Prisma.JsonValue;+ cloudFreeTierUsageThresholdState: string | null;};} | null;} & {@@ -436,6 +406,7 @@ export class ApiAuthService {createdAt: Date;updatedAt: Date;cloudConfig: Prisma.JsonValue;+ cloudFreeTierUsageThresholdState: string | null;} | null;},) {@@ -445,6 +416,10 @@ export class ApiAuthService {const rawCloudConfig =apiKeyAndOrganisation.project?.organization.cloudConfig ??apiKeyAndOrganisation.organization?.cloudConfig;+ const cloudFreeTierUsageThresholdState =+ apiKeyAndOrganisation.project?.organization+ .cloudFreeTierUsageThresholdState ??+ apiKeyAndOrganisation.organization?.cloudFreeTierUsageThresholdState;if (!orgId) {logger.error(@@ -460,6 +435,7 @@ export class ApiAuthService {return {orgId,cloudConfig,+ cloudFreeTierUsageThresholdState,};}@@ -479,6 +455,7 @@ export class ApiAuthService {createdAt: Date;updatedAt: Date;cloudConfig: Prisma.JsonValue;+ cloudFreeTierUsageThresholdState: string | null;};} | null;} & {@@ -488,12 +465,12 @@ export class ApiAuthService {createdAt: Date;updatedAt: Date;cloudConfig: Prisma.JsonValue;+ cloudFreeTierUsageThresholdState: string | null;} | null;},) {- const { orgId, cloudConfig } = this.extractOrgIdAndCloudConfig(- apiKeyAndOrganisation,- );+ const { orgId, cloudConfig, cloudFreeTierUsageThresholdState } =+ this.extractOrgIdAndCloudConfig(apiKeyAndOrganisation);const newApiKey = OrgEnrichedApiKey.parse({...apiKeyAndOrganisation,@@ -501,6 +478,7 @@ export class ApiAuthService {orgId,plan: getOrganizationPlanServerSide(cloudConfig),rateLimitOverrides: cloudConfig?.rateLimitOverrides,+ isIngestionSuspended: cloudFreeTierUsageThresholdState === "BLOCKED",});if (!orgId) {diff --git a/web/src/pages/api/admin/api-keys/index.ts b/web/src/pages/api/admin/api-keys/index.tsindex 7f5b039d5f..8da5c65ccc 100644--- a/web/src/pages/api/admin/api-keys/index.ts+++ b/web/src/pages/api/admin/api-keys/index.ts@@ -72,7 +72,7 @@ export default async function handler(});// then delete from the cache- await new ApiAuthService(prisma, redis).invalidate(+ await new ApiAuthService(prisma, redis).invalidateCachedApiKeys(apiKeysToBeDeleted,`projects ${body.data.projectIds.join(", ")}`,);@@ -94,7 +94,7 @@ export default async function handler(});// then delete from the cache- await new ApiAuthService(prisma, redis).invalidate(+ await new ApiAuthService(prisma, redis).invalidateCachedApiKeys(apiKeysToBeInvalidated,`projects ${body.data.projectIds.join(", ")}`,);diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 965b3726db..0b56493cb2 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -15,6 +15,7 @@ import {MethodNotAllowedError,BaseError,UnauthorizedError,+ ForbiddenError,} from "@langfuse/shared";import { processEventBatch } from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";@@ -85,6 +86,11 @@ export default async function handler("Missing projectId in scope. Are you using an organization key?",);}+ if (authCheck.scope.isIngestionSuspended) {+ throw new ForbiddenError(+ "Ingestion suspended: Usage threshold exceeded. Please upgrade your plan.",+ );+ }const ctx = contextWithLangfuseProps({headers: req.headers,diff --git a/web/src/pages/api/public/media/index.ts b/web/src/pages/api/public/media/index.tsindex 6d4c0fa600..07786ba248 100644--- a/web/src/pages/api/public/media/index.ts+++ b/web/src/pages/api/public/media/index.ts@@ -26,6 +26,13 @@ export default withMiddlewares({successStatusCode: 201,rateLimitResource: "ingestion",fn: async ({ body, auth }) => {+ // Check if ingestion is suspended due to usage threshold+ if (auth.scope.isIngestionSuspended) {+ throw new ForbiddenError(+ "Ingestion suspended: Usage threshold exceeded. Please upgrade your plan.",+ );+ }+if (auth.scope.accessLevel !== "project") throw new ForbiddenError();const { projectId } = auth.scope;diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex a823e98315..a33ba6913f 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -4,6 +4,7 @@ import { logger, OtelIngestionProcessor } from "@langfuse/shared/src/server";import { z } from "zod/v4";import { $root } from "@/src/pages/api/public/otel/otlp-proto/generated/root";import { gunzip } from "node:zlib";+import { ForbiddenError } from "@langfuse/shared";export const config = {api: {@@ -18,6 +19,13 @@ export default withMiddlewares({responseSchema: z.any(),rateLimitResource: "ingestion",fn: async ({ req, res, auth }) => {+ // Check if ingestion is suspended due to usage threshold+ if (auth.scope.isIngestionSuspended) {+ throw new ForbiddenError(+ "Ingestion suspended: Usage threshold exceeded. Please upgrade your plan.",+ );+ }+let body: Buffer;try {body = await new Promise((resolve, reject) => {diff --git a/worker/src/__tests__/thresholdProcessing.test.ts b/worker/src/__tests__/thresholdProcessing.test.tsnew file mode 100644index 0000000000..7d754b4f75--- /dev/null+++ b/worker/src/__tests__/thresholdProcessing.test.ts@@ -0,0 +1,491 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import { type Mock } from "vitest";++// Hoist environment variable setting to ensure it happens before module initialization+vi.hoisted(() => {+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED = "true";+});++// Mock prisma+vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ organization: {+ update: vi.fn(),+ },+ organizationMembership: {+ findMany: vi.fn(),+ },+ apiKey: {+ findMany: vi.fn(),+ },+ },+}));++import { processThresholds } from "../ee/usageThresholds/thresholdProcessing";+import { prisma } from "@langfuse/shared/src/db";+import { type ParsedOrganization } from "@langfuse/shared";++const mockOrgUpdate = prisma.organization.update as Mock;+const mockOrgMembershipFindMany = prisma.organizationMembership+ .findMany as Mock;+const mockApiKeyFindMany = prisma.apiKey.findMany as Mock;++// Mock organization helper+const createMockOrg = (+ overrides: Partial<ParsedOrganization> = {},+): ParsedOrganization => ({+ id: "org-1",+ name: "Test Org",+ cloudConfig: null,+ metadata: null,+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ cloudBillingCycleUpdatedAt: null,+ cloudCurrentCycleUsage: null,+ cloudFreeTierUsageThresholdState: null,+ aiFeaturesEnabled: false,+ createdAt: new Date("2024-01-01T00:00:00Z"),+ updatedAt: new Date("2024-01-01T00:00:00Z"),+ ...overrides,+});++describe("processThresholds", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockOrgUpdate.mockResolvedValue({} as any);+ // Mock empty admin list - emails won't be sent but threshold logic will execute+ mockOrgMembershipFindMany.mockResolvedValue([]);+ // Mock API key lookup for cache invalidation - return empty list+ mockApiKeyFindMany.mockResolvedValue([]);+ });++ describe("threshold detection", () => {+ it("detects first notification threshold crossing (50k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ await processThresholds(org, 50_000);++ // Verify update was called with WARNING state (even though no emails sent due to empty admin list)+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("detects second notification threshold crossing (100k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 60_000 });++ await processThresholds(org, 100_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 100_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("detects blocking threshold crossing (250k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 150_000 });++ await processThresholds(org, 250_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });+ });++ it("does not trigger when usage below threshold", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ await processThresholds(org, 40_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 40_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ },+ });+ });++ it("does not trigger when already past threshold", async () => {+ const org = createMockOrg({+ cloudCurrentCycleUsage: 60_000,+ cloudFreeTierUsageThresholdState: "WARNING", // Already in WARNING state+ });++ await processThresholds(org, 70_000);++ // State-based: Should maintain WARNING state (above 50k threshold)+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 70_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });+ });++ describe("threshold boundary cases", () => {+ it("triggers exactly at threshold (50k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 49_999 });++ await processThresholds(org, 50_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("triggers exactly at threshold (100k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 99_999 });++ await processThresholds(org, 100_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 100_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("triggers exactly at threshold (250k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 249_999 });++ await processThresholds(org, 250_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });+ });+ });++ describe("multiple threshold crossings", () => {+ it("crosses both notification thresholds in one run (0 -> 150k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ await processThresholds(org, 150_000);++ // Should send notification for highest threshold (100k), not 50k+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 150_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("crosses all thresholds in one run (0 -> 250k)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ await processThresholds(org, 250_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });+ });++ it("crosses from 50k to 250k (skips intermediate notifications)", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 50_000 });++ await processThresholds(org, 250_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });+ });+ });++ describe("idempotency", () => {+ it("does not re-trigger notification for same usage level", async () => {+ const org = createMockOrg({+ cloudCurrentCycleUsage: 60_000,+ cloudFreeTierUsageThresholdState: "WARNING", // Already in WARNING state+ });++ // Already processed 60k (past 50k threshold), now at 70k (still below 100k)+ await processThresholds(org, 70_000);++ // State-based: Should maintain WARNING state, not send email (no state transition)+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 70_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("does not re-trigger blocking for same usage level", async () => {+ const org = createMockOrg({+ cloudCurrentCycleUsage: 250_000,+ cloudFreeTierUsageThresholdState: "BLOCKED", // Already in BLOCKED state+ });++ // Already blocked at 250k, now at 260k+ await processThresholds(org, 260_000);++ // State-based: Should maintain BLOCKED state, not send email (no state transition)+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 260_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });+ });+ });++ describe("null/undefined lastUsage", () => {+ it("treats null cloudCurrentCycleUsage as 0", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: null });++ await processThresholds(org, 50_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });++ it("treats undefined cloudCurrentCycleUsage as 0", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: undefined as any });++ await processThresholds(org, 50_000);++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 50_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "WARNING",+ },+ });+ });+ });++ describe("database updates", () => {+ it("updates cloudCurrentCycleUsage and cloudBillingCycleUpdatedAt", async () => {+ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });+ const beforeTime = new Date();++ await processThresholds(org, 30_000);++ const afterTime = new Date();++ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 30_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ const updateCall = mockOrgUpdate.mock.calls[0][0];+ const updatedAt = updateCall.data.cloudBillingCycleUpdatedAt as Date;++ expect(updatedAt.getTime()).toBeGreaterThanOrEqual(beforeTime.getTime());+ expect(updatedAt.getTime()).toBeLessThanOrEqual(afterTime.getTime());+ });+ });++ describe("enforcement feature flag", () => {+ it("tracks usage but does not enforce when LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED is false", async () => {+ // Temporarily set enforcement to disabled+ const originalEnv =+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED;+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ "false";++ // Need to reload the module to pick up the new env var+ vi.resetModules();+ const { processThresholds: processThresholdsDisabled } = await import(+ "../ee/usageThresholds/thresholdProcessing"+ );++ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ const result = await processThresholdsDisabled(org, 250_000);++ // Should track usage but not set state+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ // Should return ENFORCEMENT_DISABLED+ expect(result.actionTaken).toBe("ENFORCEMENT_DISABLED");+ expect(result.emailSent).toBe(false);+ expect(result.emailFailed).toBe(false);++ // Restore original env+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ originalEnv;+ vi.resetModules();+ });++ it("clears state when enforcement is disabled and org was previously blocked", async () => {+ // Temporarily set enforcement to disabled+ const originalEnv =+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED;+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ "false";++ // Need to reload the module to pick up the new env var+ vi.resetModules();+ const { processThresholds: processThresholdsDisabled } = await import(+ "../ee/usageThresholds/thresholdProcessing"+ );++ const org = createMockOrg({+ cloudCurrentCycleUsage: 250_000,+ cloudFreeTierUsageThresholdState: "BLOCKED",+ });++ await processThresholdsDisabled(org, 260_000);++ // Should clear the state when enforcement is disabled+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 260_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ // Restore original env+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ originalEnv;+ vi.resetModules();+ });++ it("enforces thresholds when LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED is true", async () => {+ // This is the default for all other tests, but let's be explicit+ const originalEnv =+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED;+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ "true";++ vi.resetModules();+ const { processThresholds: processThresholdsEnabled } = await import(+ "../ee/usageThresholds/thresholdProcessing"+ );++ const org = createMockOrg({ cloudCurrentCycleUsage: 0 });++ const result = await processThresholdsEnabled(org, 250_000);++ // Should enforce and block+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: "BLOCKED",+ },+ });++ expect(result.actionTaken).toBe("BLOCKED");++ // Restore original env+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ originalEnv;+ vi.resetModules();+ });++ it("skips enforcement for paid plan orgs regardless of enforcement flag", async () => {+ // Set enforcement to enabled+ const originalEnv =+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED;+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ "true";++ vi.resetModules();+ const { processThresholds: processThresholdsEnabled } = await import(+ "../ee/usageThresholds/thresholdProcessing"+ );++ const org = createMockOrg({+ cloudCurrentCycleUsage: 0,+ cloudConfig: {+ stripe: {+ customerId: "cus_123",+ activeSubscriptionId: "sub_123",+ isLegacySubscription: false,+ },+ },+ });++ const result = await processThresholdsEnabled(org, 250_000);++ // Should not enforce for paid plan+ expect(mockOrgUpdate).toHaveBeenCalledWith({+ where: { id: "org-1" },+ data: {+ cloudCurrentCycleUsage: 250_000,+ cloudBillingCycleUpdatedAt: expect.any(Date),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ expect(result.actionTaken).toBe("PAID_PLAN");+ expect(result.emailSent).toBe(false);++ // Restore original env+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED =+ originalEnv;+ vi.resetModules();+ });+ });+});diff --git a/worker/src/__tests__/usageAggregation.test.ts b/worker/src/__tests__/usageAggregation.test.tsnew file mode 100644index 0000000000..eeb268e481--- /dev/null+++ b/worker/src/__tests__/usageAggregation.test.ts@@ -0,0 +1,194 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import { type Mock } from "vitest";++// Mock prisma+vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {+ project: {+ findMany: vi.fn(),+ },+ organization: {+ findMany: vi.fn(),+ update: vi.fn(),+ },+ },+}));++// Mock Clickhouse repository functions and parseDbOrg+vi.mock("@langfuse/shared/src/server", async () => {+ const originalModule = await vi.importActual("@langfuse/shared/src/server");+ return {+ ...originalModule,+ getTraceCountsByProjectAndDay: vi.fn(),+ getObservationCountsByProjectAndDay: vi.fn(),+ getScoreCountsByProjectAndDay: vi.fn(),+ parseDbOrg: vi.fn((org: any) => org), // Pass through by default+ };+});++import {+ buildProjectToOrgMap,+ aggregateByOrg,+} from "../ee/usageThresholds/usageAggregation";+import { prisma } from "@langfuse/shared/src/db";+import { type ParsedOrganization } from "@langfuse/shared";++const mockProjectFindMany = prisma.project.findMany as Mock;++describe("buildProjectToOrgMap", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("builds correct map of projectId to orgId", async () => {+ mockProjectFindMany.mockResolvedValue([+ { id: "proj-1", orgId: "org-a" } as any,+ { id: "proj-2", orgId: "org-a" } as any,+ { id: "proj-3", orgId: "org-b" } as any,+ ]);++ const map = await buildProjectToOrgMap();++ expect(map).toEqual({+ "proj-1": "org-a",+ "proj-2": "org-a",+ "proj-3": "org-b",+ });+ });++ it("handles empty project list", async () => {+ mockProjectFindMany.mockResolvedValue([]);++ const map = await buildProjectToOrgMap();++ expect(map).toEqual({});+ });+});++describe("aggregateByOrg", () => {+ it("aggregates project counts to org level", () => {+ const projectToOrgMap = {+ "proj-1": "org-a",+ "proj-2": "org-a",+ "proj-3": "org-b",+ };++ const traceCounts = [+ { count: 100, projectId: "proj-1", date: "2024-03-01" },+ { count: 200, projectId: "proj-2", date: "2024-03-01" },+ { count: 300, projectId: "proj-3", date: "2024-03-01" },+ ];++ const obsCounts = [+ { count: 50, projectId: "proj-1", date: "2024-03-01" },+ { count: 75, projectId: "proj-3", date: "2024-03-01" },+ ];++ const scoreCounts = [+ { count: 10, projectId: "proj-2", date: "2024-03-01" },+ ];++ const result = aggregateByOrg(+ traceCounts,+ obsCounts,+ scoreCounts,+ projectToOrgMap,+ );++ expect(result).toEqual({+ "org-a": {+ traces: 300, // 100 + 200+ observations: 50,+ scores: 10,+ total: 360,+ },+ "org-b": {+ traces: 300,+ observations: 75,+ scores: 0,+ total: 375,+ },+ });+ });++ it("handles projects not in map (filters them out)", () => {+ const projectToOrgMap = {+ "proj-1": "org-a",+ };++ const traceCounts = [+ { count: 100, projectId: "proj-1", date: "2024-03-01" },+ { count: 200, projectId: "proj-unknown", date: "2024-03-01" },+ ];++ const result = aggregateByOrg(traceCounts, [], [], projectToOrgMap);++ expect(result).toEqual({+ "org-a": {+ traces: 100,+ observations: 0,+ scores: 0,+ total: 100,+ },+ });+ expect(result["org-unknown"]).toBeUndefined();+ });++ it("handles empty counts", () => {+ const projectToOrgMap = {+ "proj-1": "org-a",+ };++ const result = aggregateByOrg([], [], [], projectToOrgMap);++ expect(result).toEqual({});+ });+});++describe("aggregateByOrg edge cases", () => {+ it("handles multiple counts from same project", () => {+ const projectToOrgMap = {+ "proj-1": "org-a",+ };++ // Same project appears multiple times (shouldn't happen in reality but test defensive coding)+ const traceCounts = [+ { count: 100, projectId: "proj-1", date: "2024-03-01" },+ { count: 50, projectId: "proj-1", date: "2024-03-01" },+ ];++ const result = aggregateByOrg(traceCounts, [], [], projectToOrgMap);++ expect(result["org-a"].traces).toBe(150); // Should sum both+ });++ it("calculates total correctly across all types", () => {+ const projectToOrgMap = {+ "proj-1": "org-a",+ };++ const traceCounts = [+ { count: 1000, projectId: "proj-1", date: "2024-03-01" },+ ];+ const obsCounts = [+ { count: 2000, projectId: "proj-1", date: "2024-03-01" },+ ];+ const scoreCounts = [+ { count: 3000, projectId: "proj-1", date: "2024-03-01" },+ ];++ const result = aggregateByOrg(+ traceCounts,+ obsCounts,+ scoreCounts,+ projectToOrgMap,+ );++ expect(result["org-a"]).toEqual({+ traces: 1000,+ observations: 2000,+ scores: 3000,+ total: 6000,+ });+ });+});diff --git a/worker/src/__tests__/usageThresholdCacheInvalidation.test.ts b/worker/src/__tests__/usageThresholdCacheInvalidation.test.tsnew file mode 100644index 0000000000..5aaa1b7dd4--- /dev/null+++ b/worker/src/__tests__/usageThresholdCacheInvalidation.test.ts@@ -0,0 +1,454 @@+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";+import { prisma } from "@langfuse/shared/src/db";+import { type ParsedOrganization } from "@langfuse/shared";+import {+ redis,+ hashSecretKey,+ getDisplaySecretKey,+ createShaHash,+} from "@langfuse/shared/src/server";+import { processThresholds } from "../ee/usageThresholds/thresholdProcessing";++// Enable enforcement feature flag for tests+vi.hoisted(() => {+ process.env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED = "true";+});++// SALT is defined in web env, not worker env+const SALT = process.env.SALT || "test-salt-for-hashing";++describe("Usage Threshold Cache Invalidation", () => {+ const testOrgId = "test-org-cache-invalidation";+ const testProjectId = "test-project-cache-invalidation";+ const testApiKeyId = "test-api-key-cache-invalidation";+ const testApiKeyPublic = "pk-lf-test-cache-inv";+ const testApiKeySecret = "sk-lf-test-cache-inv";++ beforeEach(async () => {+ // Clean up any existing test data+ await prisma.apiKey.deleteMany({+ where: { id: testApiKeyId },+ });+ await prisma.project.deleteMany({+ where: { id: testProjectId },+ });+ await prisma.organization.deleteMany({+ where: { id: testOrgId },+ });++ // Create test organization+ await prisma.organization.create({+ data: {+ id: testOrgId,+ name: "Test Org Cache Invalidation",+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ },+ });++ // Create test project+ await prisma.project.create({+ data: {+ id: testProjectId,+ name: "Test Project Cache Invalidation",+ orgId: testOrgId,+ },+ });++ // Create test API key+ await prisma.apiKey.create({+ data: {+ id: testApiKeyId,+ publicKey: testApiKeyPublic,+ hashedSecretKey: await hashSecretKey(testApiKeySecret),+ displaySecretKey: getDisplaySecretKey(testApiKeySecret),+ projectId: testProjectId,+ note: "Test key for cache invalidation",+ },+ });++ // Clear Redis cache+ if (redis) {+ const keys = await redis.keys("api-key:*");+ if (keys.length > 0) {+ await redis.del(keys);+ }+ }+ });++ afterEach(async () => {+ // Clean up test data+ await prisma.apiKey.deleteMany({+ where: { id: testApiKeyId },+ });+ await prisma.project.deleteMany({+ where: { id: testProjectId },+ });+ await prisma.organization.deleteMany({+ where: { id: testOrgId },+ });++ // Clear Redis cache+ if (redis) {+ const keys = await redis.keys("api-key:*");+ if (keys.length > 0) {+ await redis.del(keys);+ }+ }+ });++ it("should invalidate API key cache when org blocking state changes to BLOCKED", async () => {+ if (!redis) {+ console.log("Redis not available, skipping test");+ return;+ }++ // Step 1: Add API key to cache+ const fastHashedKey = createShaHash(testApiKeySecret, SALT);++ await prisma.apiKey.update({+ where: { id: testApiKeyId },+ data: { fastHashedSecretKey: fastHashedKey },+ });++ // Simulate cached API key in Redis+ const cachedApiKey = {+ id: testApiKeyId,+ publicKey: testApiKeyPublic,+ hashedSecretKey: await hashSecretKey(testApiKeySecret),+ fastHashedSecretKey: fastHashedKey,+ displaySecretKey: getDisplaySecretKey(testApiKeySecret),+ note: "Test key",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ projectId: testProjectId,+ orgId: testOrgId,+ plan: "cloud:hobby",+ scope: "PROJECT",+ rateLimitOverrides: null,+ isIngestionSuspended: false,+ };++ await redis.set(+ `api-key:${fastHashedKey}`,+ JSON.stringify(cachedApiKey),+ "EX",+ 3600,+ );++ // Verify key is in cache+ const cachedBefore = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedBefore).not.toBeNull();++ // Step 2: Trigger threshold processing that blocks the org (250k threshold)+ const org: ParsedOrganization = {+ id: testOrgId,+ name: "Test Org",+ cloudConfig: null,+ metadata: null,+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ cloudBillingCycleUpdatedAt: null,+ cloudCurrentCycleUsage: 150_000, // Below blocking threshold+ cloudFreeTierUsageThresholdState: null, // Not blocked yet+ aiFeaturesEnabled: false,+ createdAt: new Date("2024-01-01T00:00:00Z"),+ updatedAt: new Date("2024-01-01T00:00:00Z"),+ };++ await processThresholds(org, 250_000); // Cross blocking threshold++ // Step 3: Verify cache was invalidated+ const cachedAfter = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedAfter).toBeNull();++ // Step 4: Verify org state was updated+ const updatedOrg = await prisma.organization.findUnique({+ where: { id: testOrgId },+ });+ expect(updatedOrg?.cloudFreeTierUsageThresholdState).toBe("BLOCKED");+ });++ it("should invalidate API key cache when org blocking state changes from BLOCKED to null", async () => {+ if (!redis) {+ console.log("Redis not available, skipping test");+ return;+ }++ // Step 1: Set org to BLOCKED state+ await prisma.organization.update({+ where: { id: testOrgId },+ data: {+ cloudFreeTierUsageThresholdState: "BLOCKED",+ cloudCurrentCycleUsage: 250_000,+ },+ });++ // Step 2: Add API key to cache with isIngestionSuspended = true+ const fastHashedKey = createShaHash(testApiKeySecret, SALT);++ await prisma.apiKey.update({+ where: { id: testApiKeyId },+ data: { fastHashedSecretKey: fastHashedKey },+ });++ const cachedApiKey = {+ id: testApiKeyId,+ publicKey: testApiKeyPublic,+ hashedSecretKey: await hashSecretKey(testApiKeySecret),+ fastHashedSecretKey: fastHashedKey,+ displaySecretKey: getDisplaySecretKey(testApiKeySecret),+ note: "Test key",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ projectId: testProjectId,+ orgId: testOrgId,+ plan: "cloud:hobby",+ scope: "PROJECT",+ rateLimitOverrides: null,+ isIngestionSuspended: true, // Blocked+ };++ await redis.set(+ `api-key:${fastHashedKey}`,+ JSON.stringify(cachedApiKey),+ "EX",+ 3600,+ );++ // Verify key is in cache+ const cachedBefore = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedBefore).not.toBeNull();++ // Step 3: Simulate org moving to paid plan (usage still high but now allowed)+ await prisma.organization.update({+ where: { id: testOrgId },+ data: {+ cloudConfig: {+ stripe: {+ customerId: "cus_test",+ activeSubscriptionId: "sub_test",+ activeProductId: "prod_test",+ },+ },+ },+ });++ // Trigger threshold processing (paid plan = no blocking)+ const org: ParsedOrganization = {+ id: testOrgId,+ name: "Test Org",+ cloudConfig: {+ stripe: {+ customerId: "cus_test",+ activeSubscriptionId: "sub_test",+ activeProductId: "prod_test",+ isLegacySubscription: false,+ },+ },+ metadata: null,+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ cloudBillingCycleUpdatedAt: new Date(),+ cloudCurrentCycleUsage: 250_000,+ cloudFreeTierUsageThresholdState: "BLOCKED", // Previously blocked+ aiFeaturesEnabled: false,+ createdAt: new Date("2024-01-01T00:00:00Z"),+ updatedAt: new Date("2024-01-01T00:00:00Z"),+ };++ await processThresholds(org, 300_000); // Still high usage but paid plan++ // Step 4: Verify cache was invalidated+ const cachedAfter = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedAfter).toBeNull();++ // Step 5: Verify org state was updated to unblocked+ const updatedOrg = await prisma.organization.findUnique({+ where: { id: testOrgId },+ });+ expect(updatedOrg?.cloudFreeTierUsageThresholdState).toBeNull();+ });++ it("should NOT invalidate cache when state does not change", async () => {+ if (!redis) {+ console.log("Redis not available, skipping test");+ return;+ }++ // Step 1: Add API key to cache+ const fastHashedKey = createShaHash(testApiKeySecret, SALT);++ await prisma.apiKey.update({+ where: { id: testApiKeyId },+ data: { fastHashedSecretKey: fastHashedKey },+ });++ const cachedApiKey = {+ id: testApiKeyId,+ publicKey: testApiKeyPublic,+ hashedSecretKey: await hashSecretKey(testApiKeySecret),+ fastHashedSecretKey: fastHashedKey,+ displaySecretKey: getDisplaySecretKey(testApiKeySecret),+ note: "Test key",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ projectId: testProjectId,+ orgId: testOrgId,+ plan: "cloud:hobby",+ scope: "PROJECT",+ rateLimitOverrides: null,+ isIngestionSuspended: false,+ };++ await redis.set(+ `api-key:${fastHashedKey}`,+ JSON.stringify(cachedApiKey),+ "EX",+ 3600,+ );++ // Verify key is in cache+ const cachedBefore = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedBefore).not.toBeNull();++ // Step 2: Trigger threshold processing with usage that doesn't cross thresholds+ const org: ParsedOrganization = {+ id: testOrgId,+ name: "Test Org",+ cloudConfig: null,+ metadata: null,+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ cloudBillingCycleUpdatedAt: null,+ cloudCurrentCycleUsage: 30_000,+ cloudFreeTierUsageThresholdState: null,+ aiFeaturesEnabled: false,+ createdAt: new Date("2024-01-01T00:00:00Z"),+ updatedAt: new Date("2024-01-01T00:00:00Z"),+ };++ await processThresholds(org, 40_000); // Still below thresholds++ // Step 3: Verify cache was NOT invalidated (state didn't change)+ const cachedAfter = await redis.get(`api-key:${fastHashedKey}`);+ expect(cachedAfter).not.toBeNull();+ expect(cachedAfter).toBe(cachedBefore);+ });++ it("should handle multiple API keys for same org", async () => {+ if (!redis) {+ console.log("Redis not available, skipping test");+ return;+ }++ // Create second API key+ const testApiKeyId2 = "test-api-key-cache-inv-2";+ const testApiKeyPublic2 = "pk-lf-test-cache-inv-2";+ const testApiKeySecret2 = "sk-lf-test-cache-inv-2";++ await prisma.apiKey.create({+ data: {+ id: testApiKeyId2,+ publicKey: testApiKeyPublic2,+ hashedSecretKey: await hashSecretKey(testApiKeySecret2),+ displaySecretKey: getDisplaySecretKey(testApiKeySecret2),+ projectId: testProjectId,+ note: "Test key 2",+ },+ });++ // Add both keys to cache+ const fastHashedKey1 = createShaHash(testApiKeySecret, SALT);+ const fastHashedKey2 = createShaHash(testApiKeySecret2, SALT);++ await prisma.apiKey.update({+ where: { id: testApiKeyId },+ data: { fastHashedSecretKey: fastHashedKey1 },+ });++ await prisma.apiKey.update({+ where: { id: testApiKeyId2 },+ data: { fastHashedSecretKey: fastHashedKey2 },+ });++ const cachedApiKey1 = {+ id: testApiKeyId,+ publicKey: testApiKeyPublic,+ hashedSecretKey: await hashSecretKey(testApiKeySecret),+ fastHashedSecretKey: fastHashedKey1,+ displaySecretKey: getDisplaySecretKey(testApiKeySecret),+ note: "Test key 1",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ projectId: testProjectId,+ orgId: testOrgId,+ plan: "cloud:hobby",+ scope: "PROJECT",+ rateLimitOverrides: null,+ isIngestionSuspended: false,+ };++ const cachedApiKey2 = {+ id: testApiKeyId2,+ publicKey: testApiKeyPublic2,+ hashedSecretKey: await hashSecretKey(testApiKeySecret2),+ fastHashedSecretKey: fastHashedKey2,+ displaySecretKey: getDisplaySecretKey(testApiKeySecret2),+ note: "Test key 2",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ projectId: testProjectId,+ orgId: testOrgId,+ plan: "cloud:hobby",+ scope: "PROJECT",+ rateLimitOverrides: null,+ isIngestionSuspended: false,+ };++ await redis.set(+ `api-key:${fastHashedKey1}`,+ JSON.stringify(cachedApiKey1),+ "EX",+ 3600,+ );++ await redis.set(+ `api-key:${fastHashedKey2}`,+ JSON.stringify(cachedApiKey2),+ "EX",+ 3600,+ );++ // Verify both keys are in cache+ expect(await redis.get(`api-key:${fastHashedKey1}`)).not.toBeNull();+ expect(await redis.get(`api-key:${fastHashedKey2}`)).not.toBeNull();++ // Trigger blocking+ const org: ParsedOrganization = {+ id: testOrgId,+ name: "Test Org",+ cloudConfig: null,+ metadata: null,+ cloudBillingCycleAnchor: new Date("2024-01-15T00:00:00Z"),+ cloudBillingCycleUpdatedAt: null,+ cloudCurrentCycleUsage: 150_000,+ cloudFreeTierUsageThresholdState: null,+ aiFeaturesEnabled: false,+ createdAt: new Date("2024-01-01T00:00:00Z"),+ updatedAt: new Date("2024-01-01T00:00:00Z"),+ };++ await processThresholds(org, 250_000);++ // Verify both keys were invalidated+ expect(await redis.get(`api-key:${fastHashedKey1}`)).toBeNull();+ expect(await redis.get(`api-key:${fastHashedKey2}`)).toBeNull();++ // Clean up second key+ await prisma.apiKey.delete({+ where: { id: testApiKeyId2 },+ });+ });+});diff --git a/worker/src/app.ts b/worker/src/app.tsindex 5ce50bccdf..305e2e84f5 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -18,6 +18,7 @@ import { batchExportQueueProcessor } from "./queues/batchExportQueue";import { onShutdown } from "./utils/shutdown";import helmet from "helmet";import { cloudUsageMeteringQueueProcessor } from "./queues/cloudUsageMeteringQueue";+import { cloudFreeTierUsageThresholdQueueProcessor } from "./queues/cloudFreeTierUsageThresholdQueue";import { WorkerManager } from "./queues/workerManager";import {CoreDataS3ExportQueue,@@ -31,6 +32,7 @@ import {IngestionQueue,OtelIngestionQueue,TraceUpsertQueue,+ CloudFreeTierUsageThresholdQueue,} from "@langfuse/shared/src/server";import { env } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";@@ -300,6 +302,28 @@ if ();}+// Free Tier Usage Threshold Queue: Only enable in cloud environment+if (+ env.QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED === "true" &&+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && // Only in cloud deployments+ env.STRIPE_SECRET_KEY+) {+ // Instantiate the queue to trigger scheduled jobs+ CloudFreeTierUsageThresholdQueue.getInstance();+ WorkerManager.register(+ QueueName.CloudFreeTierUsageThresholdQueue,+ cloudFreeTierUsageThresholdQueueProcessor,+ {+ concurrency: 1,+ limiter: {+ // Process at most `max` jobs per 30 seconds+ max: 1,+ duration: 30_000,+ },+ },+ );+}+if (env.QUEUE_CONSUMER_EXPERIMENT_CREATE_QUEUE_IS_ENABLED === "true") {WorkerManager.register(QueueName.ExperimentCreate,diff --git a/worker/src/backgroundMigrations/backfillBillingCycleAnchors.ts b/worker/src/backgroundMigrations/backfillBillingCycleAnchors.tsnew file mode 100644index 0000000000..3a767a9c45--- /dev/null+++ b/worker/src/backgroundMigrations/backfillBillingCycleAnchors.ts@@ -0,0 +1,375 @@+import { IBackgroundMigration } from "./IBackgroundMigration";+import { logger } from "@langfuse/shared/src/server";+import { parseArgs } from "node:util";+import { prisma } from "@langfuse/shared/src/db";+import { parseDbOrg } from "@langfuse/shared";+import Stripe from "stripe";+import { env } from "../env";++const stripeClient = env.STRIPE_SECRET_KEY+ ? new Stripe(env.STRIPE_SECRET_KEY)+ : undefined;++/**+ * Background migration to backfill billing cycle anchors for organizations.+ *+ * Background:+ * - Organizations created before the billing cycle anchor feature need to be backfilled+ * - For hobby plan users: set anchor to organization createdAt+ * - For paid plan users: fetch from Stripe subscription and use billing_cycle_anchor+ *+ * This migration is idempotent and can be safely re-run if interrupted.+ */+export default class BackfillBillingCycleAnchors+ implements IBackgroundMigration+{+ private isAborted = false;++ async validate(+ // eslint-disable-next-line no-unused-vars+ args: Record<string, unknown>,+ ): Promise<{ valid: boolean; invalidReason: string | undefined }> {+ // If not in cloud environment, validation passes (will skip in run())+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ logger.info(+ "[Background Migration] Not in cloud environment, migration will be skipped",+ );+ return { valid: true, invalidReason: undefined };+ }++ // In cloud environment: Stripe is required+ if (!env.STRIPE_SECRET_KEY) {+ return {+ valid: false,+ invalidReason:+ "Migration requires Stripe integration in cloud environment (STRIPE_SECRET_KEY not set)",+ };+ }++ // Check that the required column exists in the database+ try {+ const columnCheck = await prisma.$queryRaw<+ Array<{ column_name: string }>+ >`+ SELECT column_name+ FROM information_schema.columns+ WHERE table_name = 'organizations'+ AND column_name = 'cloudBillingCycleAnchor'+ `;++ if (columnCheck.length === 0) {+ return {+ valid: false,+ invalidReason:+ "Required column 'cloudBillingCycleAnchor' does not exist in organizations table. Please run database migrations first.",+ };+ }+ } catch (error) {+ logger.error(+ "[Background Migration] Failed to check for required columns",+ { error },+ );+ return {+ valid: false,+ invalidReason: `Failed to verify database schema: ${error}`,+ };+ }++ return { valid: true, invalidReason: undefined };+ }++ async run(args: Record<string, unknown>): Promise<void> {+ const startTime = Date.now();+ logger.info(+ `[Background Migration] Starting billing cycle anchor backfill with args: ${JSON.stringify(args)}`,+ );++ // Skip if not in cloud environment (graceful skip, not an error)+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ logger.info(+ "[Background Migration] Not in cloud environment, skipping migration",+ );+ return;+ }++ try {+ // Find all organizations with null cloudBillingCycleAnchor+ const orgsToBackfill = await prisma.organization.findMany({+ where: {+ cloudBillingCycleAnchor: null,+ },+ });++ const total = orgsToBackfill.length;+ logger.info(+ `[Background Migration] Found ${total} organizations to backfill`,+ );++ if (total === 0) {+ logger.info(+ "[Background Migration] No organizations to backfill, migration complete",+ );+ return;+ }++ // Check for abort signal+ if (this.isAborted) {+ logger.info(+ "[Background Migration] Migration aborted before processing",+ );+ return;+ }++ // Separate orgs by whether they have an active subscription+ const orgsWithoutSubscription: Array<{+ id: string;+ createdAt: Date;+ }> = [];+ const orgsWithSubscription: Array<{+ id: string;+ subscriptionId: string;+ }> = [];++ for (const org of orgsToBackfill) {+ const parsedOrg = parseDbOrg(org);+ const activeSubscriptionId =+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;++ if (activeSubscriptionId) {+ orgsWithSubscription.push({+ id: org.id,+ subscriptionId: activeSubscriptionId,+ });+ } else {+ orgsWithoutSubscription.push({+ id: org.id,+ createdAt: org.createdAt,+ });+ }+ }++ logger.info(+ `[Background Migration] Backfill breakdown: ${orgsWithoutSubscription.length} without subscription, ${orgsWithSubscription.length} with subscription`,+ );++ let backfilled = 0;+ let errors = 0;++ // Backfill orgs without subscription (use createdAt)+ for (const org of orgsWithoutSubscription) {+ // Check for abort signal+ if (this.isAborted) {+ logger.info(+ `[Background Migration] Migration aborted after processing ${backfilled} organizations`,+ );+ return;+ }++ try {+ await prisma.organization.update({+ where: { id: org.id },+ data: {+ cloudBillingCycleAnchor: org.createdAt,+ },+ });+ backfilled++;+ logger.debug(+ `[Background Migration] Backfilled ${org.id} with createdAt: ${org.createdAt}`,+ );+ } catch (error) {+ errors++;+ logger.error(`[Background Migration] Failed to backfill ${org.id}`, {+ error,+ orgId: org.id,+ });+ }+ }++ // Backfill orgs with subscription (fetch from Stripe)+ if (orgsWithSubscription.length > 0) {+ if (!stripeClient) {+ logger.error(+ "[Background Migration] Stripe client not available, skipping subscription-based backfill",+ );+ errors += orgsWithSubscription.length;+ } else {+ const result = await this.backfillFromStripe(+ stripeClient,+ orgsWithSubscription,+ );+ backfilled += result.backfilled;+ errors += result.errors;+ }+ }++ const duration = Date.now() - startTime;+ logger.info(+ `[Background Migration] Billing cycle anchor backfill completed in ${duration}ms: ${backfilled}/${total} backfilled, ${errors} errors`,+ );+ } catch (error) {+ logger.error(+ "[Background Migration] Billing cycle anchor backfill failed",+ {+ error,+ },+ );+ throw error;+ }+ }++ async abort(): Promise<void> {+ logger.info(+ "[Background Migration] Aborting BackfillBillingCycleAnchors migration",+ );+ this.isAborted = true;+ }++ /**+ * Backfill organizations with active subscriptions by fetching billing_cycle_anchor from Stripe+ */+ private async backfillFromStripe(+ stripe: Stripe,+ orgs: Array<{ id: string; subscriptionId: string }>,+ ): Promise<{ backfilled: number; errors: number }> {+ let backfilled = 0;+ let errors = 0;++ // Process in batches with concurrency control+ const CONCURRENCY = 10;+ const batches: Array<Array<{ id: string; subscriptionId: string }>> = [];++ for (let i = 0; i < orgs.length; i += CONCURRENCY) {+ batches.push(orgs.slice(i, i + CONCURRENCY));+ }++ for (const batch of batches) {+ // Check for abort signal+ if (this.isAborted) {+ logger.info(+ `[Background Migration] Migration aborted during Stripe backfill after ${backfilled} organizations`,+ );+ return { backfilled, errors };+ }++ const results = await Promise.allSettled(+ batch.map((org) => this.backfillSingleOrgFromStripe(stripe, org)),+ );++ for (const result of results) {+ if (result.status === "fulfilled" && result.value.success) {+ backfilled++;+ } else {+ errors++;+ }+ }+ }++ return { backfilled, errors };+ }++ /**+ * Backfill a single organization from Stripe with exponential backoff for rate limits+ */+ private async backfillSingleOrgFromStripe(+ stripe: Stripe,+ org: { id: string; subscriptionId: string },+ attempt = 1,+ maxAttempts = 5,+ ): Promise<{ success: boolean }> {+ try {+ // Fetch subscription from Stripe+ const subscription = await stripe.subscriptions.retrieve(+ org.subscriptionId,+ );++ if (!subscription.billing_cycle_anchor) {+ logger.warn(+ `[Background Migration] No billing_cycle_anchor found for subscription ${org.subscriptionId}`,+ {+ orgId: org.id,+ subscriptionId: org.subscriptionId,+ },+ );+ return { success: false };+ }++ // Convert unix timestamp (seconds) to Date+ const anchorDate = new Date(subscription.billing_cycle_anchor * 1000);++ // Update organization+ await prisma.organization.update({+ where: { id: org.id },+ data: {+ cloudBillingCycleAnchor: anchorDate,+ },+ });++ logger.debug(+ `[Background Migration] Backfilled ${org.id} with billing_cycle_anchor from Stripe: ${anchorDate}`,+ );+ return { success: true };+ } catch (error: any) {+ const status = error?.statusCode || error?.status;+ const code = error?.code;++ // Handle rate limiting with exponential backoff+ if (attempt < maxAttempts && (status === 429 || code === "rate_limit")) {+ const delayMs = Math.min(500 * Math.pow(2, attempt - 1), 8000);+ logger.debug(+ `[Background Migration] Rate limited while backfilling ${org.id}, retrying after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`,+ );++ await new Promise((resolve) => setTimeout(resolve, delayMs));+ return this.backfillSingleOrgFromStripe(+ stripe,+ org,+ attempt + 1,+ maxAttempts,+ );+ }++ // Log and fail for other errors+ logger.error(+ `[Background Migration] Failed to backfill ${org.id} from Stripe`,+ {+ error,+ orgId: org.id,+ subscriptionId: org.subscriptionId,+ attempt,+ },+ );+ return { success: false };+ }+ }+}++async function main() {+ const args = parseArgs({+ options: {},+ });++ const migration = new BackfillBillingCycleAnchors();+ const { valid, invalidReason } = await migration.validate(args.values);++ if (!valid) {+ logger.error(`[Background Migration] Validation failed: ${invalidReason}`);+ throw new Error(`Validation failed: ${invalidReason}`);+ }++ await migration.run(args.values);+}++// If the script is being executed directly (not imported), run the main function+if (require.main === module) {+ main()+ .then(() => {+ logger.info("[Background Migration] Migration completed successfully");+ process.exit(0);+ })+ .catch((error) => {+ logger.error(+ `[Background Migration] Migration execution failed: ${error}`,+ );+ process.exit(1); // Exit with an error code+ });+}diff --git a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.tsindex 09118defcd..1180e93bf8 100644--- a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts+++ b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts@@ -15,7 +15,7 @@ import {} from "./constants";import {QueueJobs,- recordGauge,+ recordIncrement,traceException,} from "@langfuse/shared/src/server";import { Job } from "bullmq";@@ -161,6 +161,20 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {logger.error(`[CLOUD USAGE METERING] Stripe customer id not found for org ${org.id}`,);+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.skipped_orgs",+ 1,+ {+ unit: "organizations",+ },+ );+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.skipped_orgs_with_errors",+ 1,+ {+ unit: "organizations",+ },+ );continue;}@@ -218,25 +232,42 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {);}+ if (countEvents === 0 && countObservations === 0) {+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.skipped_orgs",+ 1,+ {+ unit: "organizations",+ },+ );+ }++ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.processed_orgs",+ 1,+ {+ unit: "organizations",+ },+ );+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.processed_observations",+ countObservations,+ {+ unit: "observations",+ },+ );+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.processed_events",+ countEvents,+ {+ unit: "events",+ },+ );countProcessedOrgs++;countProcessedObservations += countObservations;countProcessedEvents += countEvents;}- recordGauge("cloud_usage_metering_processed_orgs", countProcessedOrgs, {- unit: "organizations",- });- recordGauge(- "cloud_usage_metering_processed_observations",- countProcessedObservations,- {- unit: "observations",- },- );- recordGauge("cloud_usage_metering_processed_events", countProcessedEvents, {- unit: "events",- });-// update cron jobawait prisma.cronJobs.update({where: { name: cloudUsageMeteringDbCronJobName },@@ -260,9 +291,13 @@ export const handleCloudUsageMeteringJob = async (job: Job) => {logger.info(`[CLOUD USAGE METERING] Enqueueing next Cloud Usage Metering Job to catch up `,);- recordGauge("cloud_usage_metering_scheduled_catchup_jobs", 1, {- unit: "jobs",- });+ recordIncrement(+ "langfuse.queue.cloud_usage_metering_queue.scheduled_catchup_jobs",+ 1,+ {+ unit: "jobs",+ },+ );await CloudUsageMeteringQueue.getInstance()?.add(QueueJobs.CloudUsageMeteringJob,{},diff --git a/worker/src/ee/usageThresholds/constants.ts b/worker/src/ee/usageThresholds/constants.tsnew file mode 100644index 0000000000..4fdcca7d63--- /dev/null+++ b/worker/src/ee/usageThresholds/constants.ts@@ -0,0 +1,38 @@+/**+ * Usage threshold constants for free-tier enforcement+ */++/**+ * Maximum events allowed in free plan (50,000)+ * Copied from web billing constants to avoid cross-package dependency+ */+export const MAX_EVENTS_FREE_PLAN = 50_000;++/**+ * Notification thresholds trigger email alerts+ * Multiple thresholds can be breached, but only ONE email is sent per job run+ * with the highest breached threshold+ */+export const NOTIFICATION_THRESHOLDS = [+ MAX_EVENTS_FREE_PLAN, // 50,000+ MAX_EVENTS_FREE_PLAN * 2, // 100,000+ MAX_EVENTS_FREE_PLAN * 4, // 200,000+] as const;++/**+ * Blocking threshold triggers API blocking+ * When reached, ingestion endpoints are blocked for the organization+ */+export const BLOCKING_THRESHOLD = MAX_EVENTS_FREE_PLAN * 5; // 250,000++/**+ * All thresholds combined for validation+ */+export const ALL_THRESHOLDS = [+ ...NOTIFICATION_THRESHOLDS,+ BLOCKING_THRESHOLD,+] as const;++export type NotificationThreshold = (typeof NOTIFICATION_THRESHOLDS)[number];+export type BlockingThreshold = typeof BLOCKING_THRESHOLD;+export type Threshold = (typeof ALL_THRESHOLDS)[number];diff --git a/worker/src/ee/usageThresholds/handleCloudFreeTierUsageThresholdJob.ts b/worker/src/ee/usageThresholds/handleCloudFreeTierUsageThresholdJob.tsnew file mode 100644index 0000000000..c585cc1f17--- /dev/null+++ b/worker/src/ee/usageThresholds/handleCloudFreeTierUsageThresholdJob.ts@@ -0,0 +1,19 @@+import { logger } from "@langfuse/shared/src/server";+import { Job } from "bullmq";+import { processUsageAggregationForAllOrgs } from "./usageAggregation";++export const handleCloudFreeTierUsageThresholdJob = async (job: Job) => {+ logger.info("[FREE TIER USAGE THRESHOLDS] Job started");++ const stats = await processUsageAggregationForAllOrgs(+ new Date(),+ async (progress) => {+ // Update job progress to prevent staleness+ await job.updateProgress(progress * 100); // BullMQ expects 0-100+ },+ );++ logger.info("[FREE TIER USAGE THRESHOLDS] Job completed successfully", {+ stats,+ });+};diff --git a/worker/src/ee/usageThresholds/thresholdProcessing.ts b/worker/src/ee/usageThresholds/thresholdProcessing.tsnew file mode 100644index 0000000000..379ac043d8--- /dev/null+++ b/worker/src/ee/usageThresholds/thresholdProcessing.ts@@ -0,0 +1,428 @@+import type { Organization } from "@prisma/client";+import { prisma } from "@langfuse/shared/src/db";+import { type ParsedOrganization, Role } from "@langfuse/shared";+import {+ sendUsageThresholdWarningEmail,+ sendUsageThresholdSuspensionEmail,+ logger,+ invalidateCachedOrgApiKeys,+ recordIncrement,+ traceException,+} from "@langfuse/shared/src/server";+import {+ NOTIFICATION_THRESHOLDS,+ BLOCKING_THRESHOLD,+ type NotificationThreshold,+ MAX_EVENTS_FREE_PLAN,+} from "./constants";+import { env } from "../../env";++/**+ * Get email addresses for OWNER and ADMIN members of an organization+ */+async function getOrgAdminEmails(orgId: string): Promise<string[]> {+ const adminMembers = await prisma.organizationMembership.findMany({+ where: {+ orgId,+ role: { in: [Role.ADMIN, Role.OWNER] },+ },+ include: {+ user: {+ select: { email: true },+ },+ },+ });++ return adminMembers+ .map((m) => m.user.email)+ .filter((email): email is string => !!email);+}++/**+ *+ * Sends usage notification to all OWNER/ADMIN users when 50k or 100k threshold is crossed+ *+ * @param org - Organization that crossed threshold+ * @param threshold - The notification threshold that was breached+ * @param cumulativeUsage - Current cumulative usage for the billing cycle+ * @returns Object with emailSent and emailFailed flags+ */+async function sendThresholdNotificationEmail(+ org: Organization | ParsedOrganization,+ threshold: NotificationThreshold,+ cumulativeUsage: number,+): Promise<{ emailSent: boolean; emailFailed: boolean }> {+ let emailSent = false;+ let emailFailed = false;++ try {+ // Get admin/owner emails+ const adminEmails = await getOrgAdminEmails(org.id);++ if (adminEmails.length === 0) {+ logger.warn(+ `[FREE TIER USAGE THRESHOLDS] No admin/owner emails found for org ${org.id}`,+ );+ return { emailSent: false, emailFailed: false };+ }++ // Note: We assume that we run in a cloud environment, so the NEXTAUTH_URL must be set+ if (!env.NEXTAUTH_URL) {+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] NEXTAUTH_URL is not set, cannot send usage notification email for org ${org.id}`,+ );+ traceException(+ `[FREE TIER USAGE THRESHOLDS] NEXTAUTH_URL is not set, cannot send usage notification email for org ${org.id}`,+ );+ return { emailSent: false, emailFailed: false };+ }++ // Generate billing URL+ const billingUrl = `${env.NEXTAUTH_URL}/organization/${org.id}/settings/billing`;++ // Send email to each admin/owner+ const emailResults = await Promise.allSettled(+ adminEmails.map(async (email) => {+ await sendUsageThresholdWarningEmail({+ env,+ organizationName: org.name,+ currentUsage: cumulativeUsage,+ limit: MAX_EVENTS_FREE_PLAN,+ billingUrl,+ receiverEmail: email,+ });++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Usage notification email sent to ${email} for org ${org.id}`,+ );+ }),+ );++ // Check if any emails succeeded or failed+ for (const result of emailResults) {+ if (result.status === "fulfilled") {+ emailSent = true;+ } else {+ emailFailed = true;+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to send usage notification email for org ${org.id}`,+ result.reason,+ );+ }+ }++ // Record metrics once per org (not per recipient)+ if (emailSent) {+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.warning_emails_sent",+ 1,+ {+ unit: "emails",+ },+ );+ }+ if (emailFailed) {+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.email_failures",+ 1,+ {+ unit: "emails",+ },+ );+ }+ } catch (error) {+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Error sending threshold notification for org ${org.id}`,+ error,+ );+ emailFailed = true;+ recordIncrement("langfuse.queue.usage_threshold_queue.email_failures", 1, {+ unit: "emails",+ });+ }++ return { emailSent, emailFailed };+}++/**+ *+ * Sends ingestion suspended email to all OWNER/ADMIN users when 200k threshold is crossed+ *+ * @param org - Organization that was blocked+ * @param cumulativeUsage - Current cumulative usage for the billing cycle+ * @returns Object with emailSent and emailFailed flags+ */+async function sendBlockingNotificationEmail(+ org: Organization | ParsedOrganization,+ cumulativeUsage: number,+): Promise<{ emailSent: boolean; emailFailed: boolean }> {+ let emailSent = false;+ let emailFailed = false;++ try {+ // Get admin/owner emails+ const adminEmails = await getOrgAdminEmails(org.id);++ if (adminEmails.length === 0) {+ logger.warn(+ `[FREE TIER USAGE THRESHOLDS] No admin/owner emails found for org ${org.id}`,+ );+ return { emailSent: false, emailFailed: false };+ }++ // Note: We assume that we run in a cloud environment, so the NEXTAUTH_URL must be set+ if (!env.NEXTAUTH_URL) {+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] NEXTAUTH_URL is not set, cannot send ingestion suspended email for org ${org.id}`,+ );+ traceException(+ `[FREE TIER USAGE THRESHOLDS] NEXTAUTH_URL is not set, cannot send ingestion suspended email for org ${org.id}`,+ );+ return { emailSent: false, emailFailed: false };+ }++ // Generate billing URL+ const billingUrl = `${env.NEXTAUTH_URL}/organization/${org.id}/settings/billing`;++ // Send email to each admin/owner+ const emailResults = await Promise.allSettled(+ adminEmails.map(async (email) => {+ await sendUsageThresholdSuspensionEmail({+ env,+ organizationName: org.name,+ currentUsage: cumulativeUsage,+ limit: MAX_EVENTS_FREE_PLAN,+ billingUrl,+ receiverEmail: email,+ });++ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Ingestion suspended email sent to ${email} for org ${org.id}`,+ );+ }),+ );++ // Check if any emails succeeded or failed+ for (const result of emailResults) {+ if (result.status === "fulfilled") {+ emailSent = true;+ } else {+ emailFailed = true;+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Failed to send ingestion suspended email for org ${org.id}`,+ result.reason,+ );+ }+ }++ // Record metrics once per org (not per recipient)+ if (emailSent) {+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.blocking_emails_sent",+ 1,+ {+ unit: "emails",+ },+ );+ }+ if (emailFailed) {+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.email_failures",+ 1,+ {+ unit: "emails",+ },+ );+ }+ } catch (error) {+ logger.error(+ `[FREE TIER USAGE THRESHOLDS] Error sending blocking notification for org ${org.id}`,+ error,+ );+ emailFailed = true;+ recordIncrement("langfuse.queue.usage_threshold_queue.email_failures", 1, {+ unit: "emails",+ });+ }++ return { emailSent, emailFailed };+}++/**+ * Action taken during threshold processing+ */+export type ThresholdProcessingResult = {+ actionTaken:+ | "BLOCKED"+ | "WARNING"+ | "PAID_PLAN"+ | "ENFORCEMENT_DISABLED"+ | "NONE";+ emailSent: boolean;+ emailFailed: boolean;+};++/**+ * Process threshold crossings for an organization+ *+ * Called from usage aggregation engine when we reach an org's billing cycle start.+ * Detects threshold crossings since last check and triggers appropriate actions.+ *+ * Key Rules:+ * - Only ONE email per org per job run+ * - Blocking email takes precedence over notification emails+ * - If blocking threshold crossed: send blocking email AND block org+ * - Otherwise: send highest crossed notification email+ * - Idempotent: safe to call multiple times with same usage+ *+ * @param org - Full organization object (already fetched in aggregation setup)+ * @param cumulativeUsage - Total usage for the billing cycle+ * @returns ThresholdProcessingResult with action taken and email status+ */+export async function processThresholds(+ org: ParsedOrganization,+ cumulativeUsage: number,+): Promise<ThresholdProcessingResult> {+ if (env.LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED !== "true") {+ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Enforcement disabled via feature flag for org ${org.id}, tracking usage only`,+ );++ // Always track usage even when enforcement is disabled+ await prisma.organization.update({+ where: { id: org.id },+ data: {+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ return {+ actionTaken: "ENFORCEMENT_DISABLED",+ emailSent: false,+ emailFailed: false,+ };+ }++ // 1. Skip notifications if org is on a paid plan+ if (org.cloudConfig?.stripe?.activeSubscriptionId) {+ await prisma.organization.update({+ where: { id: org.id },+ data: {+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(),+ cloudFreeTierUsageThresholdState: null,+ },+ });++ // If org was previously blocked, invalidate cache+ if (org.cloudFreeTierUsageThresholdState === "BLOCKED") {+ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Org ${org.id} moved to paid plan, was previously blocked, invalidating API key cache`,+ );+ await invalidateCachedOrgApiKeys(org.id);+ }++ return {+ actionTaken: "PAID_PLAN",+ emailSent: false,+ emailFailed: false,+ };+ }++ // 2. Get previous state+ const previousState = org.cloudFreeTierUsageThresholdState;++ // 3. Determine current state based on cumulative usage (state-based, not transition-based)+ // This makes the system idempotent and self-healing+ let currentState: string | null = null;++ if (cumulativeUsage >= BLOCKING_THRESHOLD) {+ currentState = "BLOCKED";+ } else if (cumulativeUsage >= NOTIFICATION_THRESHOLDS[0]) {+ // Above any notification threshold+ currentState = "WARNING";+ } else {+ currentState = null;+ }++ // 4. Determine if we should send email (only on state transitions)+ let emailSent = false;+ let emailFailed = false;++ // Check for state transition+ const stateTransitioned = previousState !== currentState;++ if (stateTransitioned && currentState === "BLOCKED") {+ // Transitioning to BLOCKED state - send blocking email+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.blocked_orgs_total",+ 1,+ {+ unit: "organizations",+ },+ );+ const emailResult = await sendBlockingNotificationEmail(+ org,+ cumulativeUsage,+ );+ emailSent = emailResult.emailSent;+ emailFailed = emailResult.emailFailed;+ } else if (stateTransitioned && currentState === "WARNING") {+ // Transitioning to WARNING state - send warning email+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.warning_orgs_total",+ 1,+ {+ unit: "organizations",+ },+ );+ // Determine which threshold was crossed+ const highestCrossedThreshold = Math.max(+ ...NOTIFICATION_THRESHOLDS.filter((t) => cumulativeUsage >= t),+ );+ const emailResult = await sendThresholdNotificationEmail(+ org,+ highestCrossedThreshold,+ cumulativeUsage,+ );+ emailSent = emailResult.emailSent;+ emailFailed = emailResult.emailFailed;+ }++ // 5. Update last processed usage in DB with current state+ await prisma.organization.update({+ where: { id: org.id },+ data: {+ cloudCurrentCycleUsage: cumulativeUsage,+ cloudBillingCycleUpdatedAt: new Date(), // Stored as UTC in timestamptz column+ cloudFreeTierUsageThresholdState: currentState,+ },+ });++ // 6. Invalidate API key cache if blocking state changed+ const blockingStateChanged =+ (previousState === "BLOCKED" && currentState !== "BLOCKED") ||+ (previousState !== "BLOCKED" && currentState === "BLOCKED");++ if (blockingStateChanged) {+ logger.info(+ `[FREE TIER USAGE THRESHOLDS] Blocking state changed for org ${org.id}, invalidating API key cache`,+ );+ await invalidateCachedOrgApiKeys(org.id);+ }++ // 7. Return result for metrics tracking+ const actionTaken =+ currentState === "BLOCKED"+ ? "BLOCKED"+ : currentState === "WARNING"+ ? "WARNING"+ : "NONE";+ return {+ actionTaken,+ emailSent,+ emailFailed,+ };+}diff --git a/worker/src/ee/usageThresholds/usageAggregation.ts b/worker/src/ee/usageThresholds/usageAggregation.tsnew file mode 100644index 0000000000..0ee51d5086--- /dev/null+++ b/worker/src/ee/usageThresholds/usageAggregation.ts@@ -0,0 +1,299 @@+import { prisma } from "@langfuse/shared/src/db";+import {+ getTraceCountsByProjectAndDay,+ getObservationCountsByProjectAndDay,+ getScoreCountsByProjectAndDay,+ getBillingCycleStart,+ startOfDayUTC,+ endOfDayUTC,+ getDaysToLookBack,+ recordIncrement,+} from "@langfuse/shared/src/server";++import { parseDbOrg, type ParsedOrganization } from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";++import {+ processThresholds,+ type ThresholdProcessingResult,+} from "./thresholdProcessing";++/**+ * Map of projectId to orgId+ */+interface ProjectToOrgMap {+ [projectId: string]: string;+}++/**+ * Usage counts aggregated at org level+ */+interface UsageByOrg {+ [orgId: string]: {+ traces: number;+ observations: number;+ scores: number;+ total: number;+ };+}++/**+ * Organization with calculated billing cycle start date+ */+interface OrgWithBillingStart extends ParsedOrganization {+ billingCycleStartForReference: Date;+}++/**+ * Build a map of projectId → orgId for all projects+ */+async function buildProjectToOrgMap(): Promise<ProjectToOrgMap> {+ const projects = await prisma.project.findMany({+ select: {+ id: true,+ orgId: true,+ },+ });++ const map: ProjectToOrgMap = {};+ for (const project of projects) {+ map[project.id] = project.orgId;+ }++ return map;+}++/**+ * Fetch all organizations with billing-related fields+ * Uses parseDbOrg to properly parse cloudConfig+ */+async function fetchAllOrgsWithBillingInfo(): Promise<ParsedOrganization[]> {+ const orgs = await prisma.organization.findMany();++ return orgs.map((org) => parseDbOrg(org));+}++/**+ * Aggregate project-level counts to org-level counts+ */+function aggregateByOrg(+ traceCounts: Array<{ count: number; projectId: string; date: string }>,+ obsCounts: Array<{ count: number; projectId: string; date: string }>,+ scoreCounts: Array<{ count: number; projectId: string; date: string }>,+ projectToOrgMap: ProjectToOrgMap,+): UsageByOrg {+ const orgCounts: UsageByOrg = {};++ // Aggregate traces+ for (const row of traceCounts) {+ const orgId = projectToOrgMap[row.projectId];+ if (!orgId) {+ logger.warn(+ `[FREE TIER USAGE THRESHOLDS] aggregateByOrg: Project ${row.projectId} not found in projectToOrgMap`,+ );+ continue;+ }++ if (!orgCounts[orgId]) {+ orgCounts[orgId] = { traces: 0, observations: 0, scores: 0, total: 0 };+ }+ orgCounts[orgId].traces += row.count;+ }++ // Aggregate observations+ for (const row of obsCounts) {+ const orgId = projectToOrgMap[row.projectId];+ if (!orgId) {+ logger.warn(+ `[FREE TIER USAGE THRESHOLDS] aggregateByOrg: Project ${row.projectId} not found in projectToOrgMap`,+ );+ continue;+ }++ if (!orgCounts[orgId]) {+ orgCounts[orgId] = { traces: 0, observations: 0, scores: 0, total: 0 };+ }+ orgCounts[orgId].observations += row.count;+ }++ // Aggregate scores+ for (const row of scoreCounts) {+ const orgId = projectToOrgMap[row.projectId];+ if (!orgId) {+ logger.warn(+ `[FREE TIER USAGE THRESHOLDS] aggregateByOrg: Project ${row.projectId} not found in projectToOrgMap`,+ );+ continue;+ }++ if (!orgCounts[orgId]) {+ orgCounts[orgId] = { traces: 0, observations: 0, scores: 0, total: 0 };+ }+ orgCounts[orgId].scores += row.count;+ }++ // Calculate totals+ for (const orgId of Object.keys(orgCounts)) {+ const counts = orgCounts[orgId];+ counts.total = counts.traces + counts.observations + counts.scores;+ }++ return orgCounts;+}++/**+ * Statistics returned from usage aggregation processing+ */+export type UsageAggregationStats = {};++/**+ * Main orchestrator: Process usage aggregation for all organizations+ *+ * Algorithm:+ * 1. Setup: Fetch project→org map, all orgs, calculate billing starts+ * 2. Process day-by-day backwards from referenceDate (0 to 31 days ago)+ * 3. For each day:+ * - Fetch counts from Clickhouse (3 queries for ALL projects)+ * - Aggregate to org level+ * - Accumulate into running totals+ * - Process orgs whose billing cycle starts on THIS day+ *+ * @param referenceDate - Date to process from (default: now)+ * @param onProgress - Optional callback to report progress (0.0 to 1.0)+ * @returns Statistics about the processing run+ */+export async function processUsageAggregationForAllOrgs(+ referenceDate: Date = new Date(),+ onProgress?: (progress: number) => void | Promise<void>, // eslint-disable-line no-unused-vars+): Promise<UsageAggregationStats> {+ // Normalize referenceDate to UTC end of day+ const normalizedReferenceDate = endOfDayUTC(referenceDate);++ // Setup+ const projectToOrgMap = await buildProjectToOrgMap();+ const allOrgs = await fetchAllOrgsWithBillingInfo();+ const orgsWithBillingStarts = allOrgs.map((org) => ({+ ...org,+ billingCycleStartForReference: getBillingCycleStart(+ org,+ normalizedReferenceDate,+ ),+ }));++ // Group orgs by billing cycle start date for efficient lookup+ const orgsByBillingStartMap = new Map<string, OrgWithBillingStart[]>();+ for (const org of orgsWithBillingStarts) {+ const dateString = org.billingCycleStartForReference+ .toISOString()+ .split("T")[0];+ if (!orgsByBillingStartMap.has(dateString)) {+ orgsByBillingStartMap.set(dateString, []);+ }+ orgsByBillingStartMap.get(dateString)!.push(org);+ }++ // Initialize usage state for all orgs+ const usageByOrgMap: UsageByOrg = {};+ for (const org of allOrgs) {+ usageByOrgMap[org.id] = { traces: 0, observations: 0, scores: 0, total: 0 };+ }++ // Initialize statistics tracking+ const stats: UsageAggregationStats = {};++ // Calculate how many days to look back (based on previous month's length)+ const daysToLookBack = getDaysToLookBack(normalizedReferenceDate);++ // Process day-by-day (backwards from referenceDate)+ const totalDays = daysToLookBack + 1; // Total days to process (0 to daysToLookBack inclusive)++ for (let daysAgo = 0; daysAgo <= daysToLookBack; daysAgo++) {+ const dayDate = new Date(normalizedReferenceDate);+ dayDate.setUTCDate(dayDate.getUTCDate() - daysAgo);++ const dayStart = startOfDayUTC(dayDate);++ // For today (daysAgo === 0), use normalizedReferenceDate as end time+ // For past days, use end of day+ const dayEnd =+ daysAgo === 0 ? normalizedReferenceDate : endOfDayUTC(dayDate);++ // Fetch counts from Clickhouse (3 queries for ALL projects)+ const [traceCounts, obsCounts, scoreCounts] = await Promise.all([+ getTraceCountsByProjectAndDay({ startDate: dayStart, endDate: dayEnd }),+ getObservationCountsByProjectAndDay({+ startDate: dayStart,+ endDate: dayEnd,+ }),+ getScoreCountsByProjectAndDay({ startDate: dayStart, endDate: dayEnd }),+ ]);++ // Aggregate to org level+ const orgDailyCounts = aggregateByOrg(+ traceCounts,+ obsCounts,+ scoreCounts,+ projectToOrgMap,+ );++ // Accumulate for all orgs and previous days+ for (const [orgId, counts] of Object.entries(orgDailyCounts)) {+ const state = usageByOrgMap[orgId];+ if (state) {+ state.traces += counts.traces;+ state.observations += counts.observations;+ state.scores += counts.scores;+ state.total += counts.total;+ }+ }++ // Process orgs with billing cycle starting THIS day+ const dayDateString = dayStart.toISOString().split("T")[0];+ const orgsToProcess = orgsByBillingStartMap.get(dayDateString) || [];++ for (const org of orgsToProcess) {+ const state = usageByOrgMap[org.id];+ if (state) {+ const result: ThresholdProcessingResult = await processThresholds(+ org,+ state.total,+ );++ // Track statistics with increments+ recordIncrement("langfuse.queue.usage_threshold_queue.total_orgs", 1, {+ unit: "organizations",+ });++ if (result.actionTaken === "PAID_PLAN") {+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.paid_plan_orgs",+ 1,+ {+ unit: "organizations",+ },+ );+ } else {+ // Count as free tier if not paid plan+ recordIncrement(+ "langfuse.queue.usage_threshold_queue.free_tier_orgs",+ 1,+ {+ unit: "organizations",+ },+ );+ }+ }+ }++ // Update progress+ if (onProgress) {+ const progress = (daysAgo + 1) / totalDays;+ await onProgress(progress);+ }+ }++ return stats;+}++// Export helper functions for testing+export { buildProjectToOrgMap, fetchAllOrgsWithBillingInfo, aggregateByOrg };diff --git a/worker/src/env.ts b/worker/src/env.tsindex 97863f6d6f..038e8eca96 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -16,6 +16,12 @@ const EnvSchema = z.object({NEXTAUTH_URL: z.string().optional(),+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z+ .enum(["US", "EU", "STAGING", "DEV", "HIPAA"])+ .optional(),++ STRIPE_SECRET_KEY: z.string().optional(),+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"),@@ -115,7 +121,6 @@ const EnvSchema = z.object({.number().positive().default(5),- STRIPE_SECRET_KEY: z.string().optional(),// Skip the read from ClickHouse within the Ingestion pipeline for the given// project ids. Applicable for projects that were created after the S3 write@@ -148,6 +153,9 @@ const EnvSchema = z.object({QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),+ QUEUE_CONSUMER_FREE_TIER_USAGE_THRESHOLD_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),QUEUE_CONSUMER_INGESTION_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),@@ -243,6 +251,12 @@ const EnvSchema = z.object({.enum(["true", "false"]).default("false"),+ // When disabled: Usage is still tracked in DB but no emails are sent and no orgs are blocked+ // When enabled: Full enforcement (emails + blocking)+ LANGFUSE_FREE_TIER_USAGE_THRESHOLD_ENFORCEMENT_ENABLED: z+ .enum(["true", "false"])+ .default("false"),+LANGFUSE_S3_CONCURRENT_READS: z.coerce.number().positive().default(50),LANGFUSE_CLICKHOUSE_PROJECT_DELETION_CONCURRENCY_DURATION_MS: z.coerce.number()diff --git a/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts b/worker/src/queues/cloudFreeTierUsageThresholdQueue.tsnew file mode 100644index 0000000000..e08016ff48--- /dev/null+++ b/worker/src/queues/cloudFreeTierUsageThresholdQueue.ts@@ -0,0 +1,17 @@+import { Processor } from "bullmq";+import { logger, QueueJobs } from "@langfuse/shared/src/server";+import { handleCloudFreeTierUsageThresholdJob } from "../ee/usageThresholds/handleCloudFreeTierUsageThresholdJob";++export const cloudFreeTierUsageThresholdQueueProcessor: Processor = async (+ job,+) => {+ if (job.name === QueueJobs.CloudFreeTierUsageThresholdJob) {+ logger.info("Executing Free Tier Usage Threshold Job", job.data);+ try {+ return await handleCloudFreeTierUsageThresholdJob(job);+ } catch (error) {+ logger.error("Error executing Free Tier Usage Threshold Job", error);+ throw error;+ }+ }+};diff --git a/worker/src/scripts/send-test-threshold-emails.ts b/worker/src/scripts/send-test-threshold-emails.tsnew file mode 100644index 0000000000..a311e17c37--- /dev/null+++ b/worker/src/scripts/send-test-threshold-emails.ts@@ -0,0 +1,95 @@+// This script sends test threshold emails for visual testing.+// Execute with: pnpm tsx src/scripts/send-test-threshold-emails.ts+// WARNING: This sends real emails! Comment out before pushing to production.++/*+ * Run the script with:+ *+ * pnpm dotenv -e ../.env -- tsx src/scripts/send-test-threshold-emails.ts+ *+ */++import {+ sendUsageThresholdWarningEmail,+ sendUsageThresholdSuspensionEmail,+ logger,+} from "@langfuse/shared/src/server";+import { env } from "../env";++const TEST_EMAILS: string[] = [+ // TODO ADD EMAILS HERE – these accounts will receive test emails+ // [email protected]+];+const TEST_ORG_NAME = "Test Organization";+const BILLING_URL =+ "http://localhost:3000/organization/test-org-id/settings/billing";++const main = async () => {+ // Check if TEST_EMAILS is empty+ if (TEST_EMAILS.length === 0) {+ console.error("\n❌ Error: TEST_EMAILS list is empty!");+ console.error(+ "\nPlease add email addresses to the TEST_EMAILS array in this script before running it.",+ );+ console.error(+ "Edit the file at: worker/src/scripts/send-test-threshold-emails.ts\n",+ );+ process.exit(1);+ }++ console.log(+ `Sending test threshold emails to ${TEST_EMAILS.length} recipients`,+ );++ for (const email of TEST_EMAILS) {+ console.log(`\n📧 Sending to ${email}...`);++ // Send warning email (50k threshold)+ console.log(" → Warning email (50k threshold)...");+ await sendUsageThresholdWarningEmail({+ env: {+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,+ NEXTAUTH_URL: env.NEXTAUTH_URL,+ },+ organizationName: TEST_ORG_NAME,+ currentUsage: 52_347,+ limit: 50_000,+ billingUrl: BILLING_URL,+ receiverEmail: email,+ });+ console.log(" ✓ Warning email sent");++ // Send blocking/suspension email (200k threshold)+ console.log(" → Blocking email (200k threshold)...");+ await sendUsageThresholdSuspensionEmail({+ env: {+ EMAIL_FROM_ADDRESS: env.EMAIL_FROM_ADDRESS,+ SMTP_CONNECTION_URL: env.SMTP_CONNECTION_URL,+ NEXTAUTH_URL: env.NEXTAUTH_URL,+ },+ organizationName: TEST_ORG_NAME,+ currentUsage: 203_891,+ limit: 50_000,+ billingUrl: BILLING_URL,+ receiverEmail: email,+ });+ console.log(" ✓ Blocking email sent");+ }++ console.log(+ `\n✅ All test emails sent successfully to ${TEST_EMAILS.length} recipients`,+ );+ console.log("Recipients:", TEST_EMAILS.join(", "));+};++if (require.main === module) {+ main()+ .catch((err) => {+ logger.error("Error sending test emails:", err);+ process.exit(1);+ })+ .finally(() => {+ process.exit(0);+ });+}