🪢 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
chore: introduing a metric indicating how many projects are experiencing ingestion failures (#14403)
Valery Meleshkin80b7d6b5395b
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex a5d45b5f79..fd33b4035a 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -297,6 +297,11 @@ const EnvSchema = z.object({.number().positive().default(3600), // 1 hour+ LANGFUSE_INGEST_FAILURE_PROJECT_TTL_SECONDS: z.coerce+ .number()+ .int()+ .gt(60)+ .default(3600), // 1 hourLANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED: z.enum(["true", "false"]).default("false"),diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 227fed1f2a..50777a5279 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -105,6 +105,7 @@ export * from "./redis/entityChangeQueue";export * from "./redis/eventPropagationQueue";export * from "./redis/otelProjectTracking";export * from "./redis/s3SlowdownTracking";+export * from "./redis/ingestionFailureTracking";export * from "./auth/types";export * from "./queues";export * from "./orderByToPrisma";diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex 69e8914073..04bb434279 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -42,6 +42,7 @@ import {isS3SlowDownError,markProjectS3Slowdown,} from "../redis/s3SlowdownTracking";+import { markProjectIngestFailure } from "../redis/ingestionFailureTracking";let s3StorageServiceClient: StorageService;@@ -300,8 +301,16 @@ export const processEventBatch = async (error: result.reason,},);- // Fire and forget - don't await, don't block the error flowmarkProjectS3Slowdown(authCheck.scope.projectId!).catch(() => {});+ markProjectIngestFailure(authCheck.scope.projectId!, {+ source: "process_event_batch",+ reason: "s3_slowdown",+ });+ } else {+ markProjectIngestFailure(authCheck.scope.projectId!, {+ source: "process_event_batch",+ reason: "s3_upload_error",+ });}logger.error("Failed to upload event to S3", {diff --git a/packages/shared/src/server/redis/ingestionFailureTracking.ts b/packages/shared/src/server/redis/ingestionFailureTracking.tsnew file mode 100644index 0000000000..b3b76da910--- /dev/null+++ b/packages/shared/src/server/redis/ingestionFailureTracking.ts@@ -0,0 +1,130 @@+import { env } from "../../env";+import { recordGauge, traceException } from "../instrumentation";+import { logger } from "../logger";+import { redis } from "./redis";++export const INGESTION_FAILURE_ACTIVE_PROJECTS_KEY =+ "langfuse:ingestion-failure:active-projects";+const INGESTION_FAILURE_ACTIVE_PROJECTS_METRIC =+ "langfuse.ingestion.project_failure.active_projects";++const MARK_RATE_LIMIT_WINDOW_MS = 60_000;+const MAX_PROJECT_MARKS_PER_WINDOW = 100;++const recentProjectMarks = new Map<string, number>();++export type IngestionFailureSource =+ | "process_event_batch"+ | "ingestion_queue"+ | "otel_ingestion_queue"+ | "public_ingestion_api"+ | "public_otel_api";++export type IngestionFailureReason =+ | "api_internal_error"+ | "processing_error"+ | "publish_failed"+ | "s3_slowdown"+ | "s3_upload_error";++function shouldRecordProjectMark(projectId: string, now: number): boolean {+ for (const [cachedProjectId, cachedAt] of recentProjectMarks) {+ if (now - cachedAt >= MARK_RATE_LIMIT_WINDOW_MS) {+ recentProjectMarks.delete(cachedProjectId);+ }+ }++ if (recentProjectMarks.has(projectId)) {+ return false;+ }++ if (recentProjectMarks.size >= MAX_PROJECT_MARKS_PER_WINDOW) {+ return false;+ }++ recentProjectMarks.set(projectId, now);+ return true;+}++function logMarkFailure(+ projectId: string,+ tags: {+ source: IngestionFailureSource;+ reason?: IngestionFailureReason;+ },+ error: unknown,+): void {+ logger.error("Failed to mark project ingestion failure", {+ projectId,+ source: tags.source,+ reason: tags.reason,+ error,+ });+ traceException(error);+}++export function markProjectIngestFailure(+ projectId: string,+ tags: {+ source: IngestionFailureSource;+ reason?: IngestionFailureReason;+ },+): void {+ if (!redis) return;++ const now = Date.now();+ if (!shouldRecordProjectMark(projectId, now)) return;++ const ttlSeconds = env.LANGFUSE_INGEST_FAILURE_PROJECT_TTL_SECONDS;+ const expiresAtMs = now + ttlSeconds * 1000;++ try {+ redis+ .pipeline()+ .zadd(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY, expiresAtMs, projectId)+ .expire(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY, ttlSeconds + 60)+ .exec()+ .then((results) => {+ const commandError = results?.find(([error]) => error)?.[0];+ if (commandError) {+ logMarkFailure(projectId, tags, commandError);+ }+ })+ .catch((error) => {+ logMarkFailure(projectId, tags, error);+ });+ } catch (error) {+ logMarkFailure(projectId, tags, error);+ }+}++export async function updateActiveIngestFailureProjectsMetric(): Promise<+ number | null+> {+ if (!redis) return null;++ try {+ const results = await redis+ .pipeline()+ .zremrangebyscore(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY, 0, Date.now())+ .zcard(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY)+ .exec();++ const commandError = results?.find(([error]) => error)?.[0];+ if (commandError) throw commandError;++ const activeProjects = Number(results?.[1]?.[1] ?? 0);++ recordGauge(INGESTION_FAILURE_ACTIVE_PROJECTS_METRIC, activeProjects, {+ unit: "projects",+ });++ return activeProjects;+ } catch (error) {+ logger.error("Failed to record active ingestion failure projects", {+ error,+ });+ traceException(error);+ return null;+ }+}diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 22ba851dc4..c84639b31a 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -8,6 +8,7 @@ import {getCurrentSpan,contextWithLangfuseProps,eventTypes,+ markProjectIngestFailure,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { jsonSchema } from "@langfuse/shared";@@ -53,6 +54,8 @@ export default async function handler(req: NextApiRequest,res: NextApiResponse,) {+ let projectIdForIngestFailure: string | undefined;+try {await runMiddleware(req, res, cors);@@ -88,6 +91,8 @@ export default async function handler("Missing projectId in scope. Are you using an organization key?",);}+ const projectId = authCheck.scope.projectId;+ projectIdForIngestFailure = projectId;if (authCheck.scope.isIngestionSuspended) {throw new ForbiddenError(@@ -97,64 +102,80 @@ export default async function handler(const ctx = contextWithLangfuseProps({headers: req.headers,- projectId: authCheck.scope.projectId,+ projectId,apiKeyId: authCheck.scope.apiKeyId,});// Execute the rest of the handler within the contextreturn opentelemetry.context.with(ctx, async () => {try {- const rateLimitCheck =- await RateLimitService.getInstance().rateLimitRequest(- authCheck.scope,- "ingestion",- );-- if (rateLimitCheck?.isRateLimited()) {- return rateLimitCheck.sendRestResponseIfLimited(res);+ try {+ const rateLimitCheck =+ await RateLimitService.getInstance().rateLimitRequest(+ authCheck.scope,+ "ingestion",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+ } catch (e) {+ // If rate-limiter returns an error, we log it and continue processing.+ // This allows us to fail open instead of reject requests.+ logger.error("Error while rate limiting", e);}- } catch (e) {- // If rate-limiter returns an error, we log it and continue processing.- // This allows us to fail open instead of reject requests.- logger.error("Error while rate limiting", e);- }- const batchType = z.object({- batch: z.array(z.unknown()),- metadata: jsonSchema.nullish(),- });+ const batchType = z.object({+ batch: z.array(z.unknown()),+ metadata: jsonSchema.nullish(),+ });- const parsedSchema = batchType.safeParse(req.body);+ const parsedSchema = batchType.safeParse(req.body);- if (!parsedSchema.success) {- logger.info("Invalid request data", parsedSchema.error);- return res.status(400).json({- message: "Invalid request data",- errors: parsedSchema.error.issues.map((issue) => issue.message),- });- }+ if (!parsedSchema.success) {+ logger.info("Invalid request data", parsedSchema.error);+ return res.status(400).json({+ message: "Invalid request data",+ errors: parsedSchema.error.issues.map((issue) => issue.message),+ });+ }- await telemetry();+ await telemetry();- // V4 events_only mode: refuse trace/observation events because their- // writes would land in the legacy ClickHouse tables this deployment no- // longer reads. Scores and SDK logs are unaffected and pass through.- // Reject per-event so a mixed batch still processes its score events.- const { batchForProcessing, rejectedErrors } = filterBatchForEventsOnly(- parsedSchema.data.batch,- env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only",- );+ // V4 events_only mode: refuse trace/observation events because their+ // writes would land in the legacy ClickHouse tables this deployment no+ // longer reads. Scores and SDK logs are unaffected and pass through.+ // Reject per-event so a mixed batch still processes its score events.+ const { batchForProcessing, rejectedErrors } = filterBatchForEventsOnly(+ parsedSchema.data.batch,+ env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only",+ );- const result = await processEventBatch(batchForProcessing, authCheck);- if (rejectedErrors.length > 0) {- result.errors = [...result.errors, ...rejectedErrors];+ const result = await processEventBatch(batchForProcessing, authCheck);+ if (rejectedErrors.length > 0) {+ result.errors = [...result.errors, ...rejectedErrors];+ }+ return res.status(207).json(result);+ } catch (error) {+ if (!(error instanceof BaseError && error.isUserError())) {+ markProjectIngestFailure(projectId, {+ source: "public_ingestion_api",+ reason: "api_internal_error",+ });+ }+ throw error;}- return res.status(207).json(result);});} catch (error: unknown) {if (error instanceof BaseError) {if (!error.isUserError()) {logger.error(error);traceException(error);+ if (projectIdForIngestFailure) {+ markProjectIngestFailure(projectIdForIngestFailure, {+ source: "public_ingestion_api",+ reason: "api_internal_error",+ });+ }}return res.status(error.httpCode).json({@@ -174,6 +195,13 @@ export default async function handler(logger.error("error_handling_ingestion_event", error);traceException(error);+ if (projectIdForIngestFailure) {+ markProjectIngestFailure(projectIdForIngestFailure, {+ source: "public_ingestion_api",+ reason: "api_internal_error",+ });+ }+if (isPrismaException(error)) {return res.status(500).json({error: "Internal Server Error",diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex dd6db5cc32..25bcfd1f1d 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -2,6 +2,7 @@ import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewareimport { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {logger,+ markProjectIngestFailure,OtelIngestionProcessor,markProjectAsOtelUser,} from "@langfuse/shared/src/server";@@ -184,7 +185,15 @@ export default withMiddlewares({// At this point, we have the raw OpenTelemetry Span body. We upload the full batch to S3// and the OtelIngestionProcessor logic will handle processing in the worker container.- return processor.publishToOtelIngestionQueue(resourceSpans);+ try {+ return await processor.publishToOtelIngestionQueue(resourceSpans);+ } catch (error) {+ markProjectIngestFailure(auth.scope.projectId, {+ source: "public_otel_api",+ reason: "publish_failed",+ });+ throw error;+ }},}),});diff --git a/worker/src/__tests__/ingestionFailureTracking.test.ts b/worker/src/__tests__/ingestionFailureTracking.test.tsnew file mode 100644index 0000000000..5be9418836--- /dev/null+++ b/worker/src/__tests__/ingestionFailureTracking.test.ts@@ -0,0 +1,100 @@+import { randomUUID } from "node:crypto";+import { setTimeout as sleep } from "node:timers/promises";++import { env } from "@langfuse/shared/src/env";+import {+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ markProjectIngestFailure,+ redis,+ updateActiveIngestFailureProjectsMetric,+} from "@langfuse/shared/src/server";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++async function waitForActiveProjectCount(expected: number): Promise<void> {+ if (!redis) throw new Error("Redis must be configured");++ for (let attempt = 0; attempt < 100; attempt++) {+ const count = await redis.zcard(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY);+ if (count === expected) return;+ await sleep(10);+ }++ expect(await redis.zcard(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY)).toBe(+ expected,+ );+}++describe("ingestion failure tracking", () => {+ beforeAll(async () => {+ if (!redis) {+ throw new Error("Redis must be configured for worker integration tests");+ }++ await redis.del(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY);+ });++ afterAll(async () => {+ await redis?.del(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY);+ });++ it("tracks active projects in Redis, caps distinct local projects per minute, and prunes expired projects", async () => {+ if (!redis) throw new Error("Redis must be configured");+ expect(env.LANGFUSE_INGEST_FAILURE_PROJECT_TTL_SECONDS).toBeGreaterThan(60);++ const projectPrefix = `project-${randomUUID()}`;+ const startedAt = Date.now();++ for (let i = 0; i < 650; i++) {+ markProjectIngestFailure(`${projectPrefix}-noisy`, {+ source: "otel_ingestion_queue",+ reason: "processing_error",+ });+ }++ for (let i = 0; i < 150; i++) {+ markProjectIngestFailure(`${projectPrefix}-${i}`, {+ source: "otel_ingestion_queue",+ reason: "processing_error",+ });+ }++ await waitForActiveProjectCount(100);++ const firstScore = await redis.zscore(+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ `${projectPrefix}-noisy`,+ );+ expect(Number(firstScore)).toBeGreaterThanOrEqual(+ startedAt + env.LANGFUSE_INGEST_FAILURE_PROJECT_TTL_SECONDS * 1000,+ );+ await expect(+ redis.zscore(+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ `${projectPrefix}-98`,+ ),+ ).resolves.not.toBeNull();+ await expect(+ redis.zscore(+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ `${projectPrefix}-99`,+ ),+ ).resolves.toBeNull();++ await redis.zadd(+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ Date.now() - 1,+ `${projectPrefix}-expired`,+ );++ await expect(updateActiveIngestFailureProjectsMetric()).resolves.toBe(100);+ await expect(+ redis.zscore(+ INGESTION_FAILURE_ACTIVE_PROJECTS_KEY,+ `${projectPrefix}-expired`,+ ),+ ).resolves.toBeNull();+ expect(+ await redis.ttl(INGESTION_FAILURE_ACTIVE_PROJECTS_KEY),+ ).toBeGreaterThan(0);+ });+});diff --git a/worker/src/features/queue-metrics-runner/index.ts b/worker/src/features/queue-metrics-runner/index.tsindex e970c7b4d7..7fd2cac31e 100644--- a/worker/src/features/queue-metrics-runner/index.ts+++ b/worker/src/features/queue-metrics-runner/index.ts@@ -4,6 +4,7 @@ import {QueueName,convertQueueNameToMetricName,recordGauge,+ updateActiveIngestFailureProjectsMetric,logger,} from "@langfuse/shared/src/server";@@ -66,6 +67,17 @@ export class QueueMetricsRunner extends PeriodicRunner {const registeredNames = new Set(WorkerManager.getRegisteredQueueNames());const promises: Promise<void>[] = [];+ promises.push(+ updateActiveIngestFailureProjectsMetric()+ .then(() => undefined)+ .catch((err) => {+ logger.error(+ "Queue metrics: failed to record active ingestion failure projects",+ err,+ );+ }),+ );+// Non-sharded queues: only poll queues with registered workersfor (const queueName of Object.values(QueueName)) {if (SHARDED_QUEUE_BASE_NAMES.has(queueName)) continue;diff --git a/worker/src/queues/ingestionQueue.ts b/worker/src/queues/ingestionQueue.tsindex a31c0437ab..a06e9ae8f3 100644--- a/worker/src/queues/ingestionQueue.ts+++ b/worker/src/queues/ingestionQueue.ts@@ -8,6 +8,7 @@ import {IngestionEventType,isS3SlowDownError,logger,+ markProjectIngestFailure,markProjectS3Slowdown,QueueName,rawEventBucketPrefix,@@ -324,6 +325,15 @@ export const ingestionQueueProcessorBuilder = ({ projectId, error: e },);await markProjectS3Slowdown(projectId);+ markProjectIngestFailure(projectId, {+ source: "ingestion_queue",+ reason: "s3_slowdown",+ });+ } else {+ markProjectIngestFailure(job.data.payload.authCheck.scope.projectId, {+ source: "ingestion_queue",+ reason: "processing_error",+ });}logger.error(diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex 0d47b5a2da..5b0a9e8c3f 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -7,6 +7,7 @@ import {getS3EventStorageClient,type IngestionEventType,logger,+ markProjectIngestFailure,OtelIngestionProcessor,processEventBatch,QueueName,@@ -563,6 +564,11 @@ export const otelIngestionQueueProcessorBuilder = (return;}+ markProjectIngestFailure(job.data.payload.authCheck.scope.projectId, {+ source: "otel_ingestion_queue",+ reason: "processing_error",+ });+logger.error(`Failed job otel ingestion processing for ${job.data.payload.authCheck.scope.projectId}`,{ error: e, fileKey },