🪢 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: add sampling to ingestion pipeline (#8128)
Hassieb Pakzadc935d4ae7361
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex e493ecee78..b9fc789761 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -140,6 +140,38 @@ const EnvSchema = z.object({LANGFUSE_EXPERIMENT_RETURN_NEW_RESULT: z.enum(["true", "false"]).default("false"),+ LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS: z+ .string()+ .optional()+ .transform((val) => {+ try {+ if (!val) return new Map<string, number>();++ const map = new Map<string, number>();+ const parts = val.split(",");++ for (const part of parts) {+ const [projectId, sampleRateStr] = part.split(":");++ if (!projectId || sampleRateStr === undefined) {+ throw new Error(`Invalid format: ${part}`);+ }++ // Validate sample rate is between 0 and 1+ const sampleRate = z.coerce+ .number()+ .min(0)+ .max(1)+ .parse(sampleRateStr);++ map.set(projectId, sampleRate);+ }++ return map;+ } catch (err) {+ return new Map<string, number>();+ }+ }),});export const env: z.infer<typeof EnvSchema> =diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex 3c69a27ef7..dd669a6bba 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -30,6 +30,7 @@ import {StorageService,StorageServiceFactory,} from "../services/StorageService";+import { isTraceIdInSample } from "./sampling";let s3StorageServiceClient: StorageService;@@ -273,6 +274,29 @@ export const processEventBatch = async (const shouldSkipS3List =isDatasetRunItemEvent || (isObservationEvent && isOtelOrSkipS3Project);+ const { isSampled, isSamplingConfigured } = isTraceIdInSample({+ projectId: authCheck.scope.projectId,+ event: eventData.data[0],+ });++ if (!isSampled) {+ recordIncrement(+ "langfuse.ingestion.sampling.events_out",+ eventData.data.length,+ { projectId: authCheck.scope.projectId ?? "<not set>" },+ );++ return;+ }++ if (isSamplingConfigured) {+ recordIncrement(+ "langfuse.ingestion.sampling.events_in",+ eventData.data.length,+ { projectId: authCheck.scope.projectId ?? "<not set>" },+ );+ }+return queue? queue.add(QueueJobs.IngestionJob,diff --git a/packages/shared/src/server/ingestion/sampling.ts b/packages/shared/src/server/ingestion/sampling.tsnew file mode 100644index 0000000000..2129b143d4--- /dev/null+++ b/packages/shared/src/server/ingestion/sampling.ts@@ -0,0 +1,59 @@+import crypto from "node:crypto";+import { logger } from "../logger";+import { env } from "../../env";+import { IngestionEventType } from "./types";++export function isTraceIdInSample(params: {+ projectId: string | null;+ event: IngestionEventType;+}): { isSampled: boolean; isSamplingConfigured: boolean } {+ const { projectId, event } = params;++ const sampledProjects = env.LANGFUSE_INGESTION_PROCESSING_SAMPLED_PROJECTS;++ if (!projectId || !sampledProjects.has(projectId))+ return { isSampled: true, isSamplingConfigured: false };++ const sampleRate = sampledProjects.get(projectId);+ if (sampleRate === undefined)+ return { isSampled: true, isSamplingConfigured: true };++ const traceId = parseTraceId(event);+ if (!traceId) return { isSampled: true, isSamplingConfigured: true };++ return {+ isSampled: isInSample(traceId, sampleRate),+ isSamplingConfigured: true,+ };+}++function isInSample(traceId: string, sampleRate: number) {+ if (sampleRate < 0 || sampleRate > 1) {+ logger.error(`Invalid sample rate ${sampleRate}`);++ // Be conservative and keep the trace ID in sample for invalid configs+ return true;+ }++ if (sampleRate === 0) return false;+ if (sampleRate === 1) return true;++ // Create SHA-256 hash of the input+ const hash = crypto.createHash("sha256").update(traceId).digest("hex");++ // Take first 8 characters and convert to integer+ // Equivalent to 4 bytes, 32 bit integer+ const hashInt = parseInt(hash.substring(0, 8), 16);++ // Convert to a value between 0 and 1 by dividing by largest integer+ const normalizedHash = hashInt / 0xffffffff;++ // Return true if normalized hash is less than sample rate+ return normalizedHash < sampleRate;+}++function parseTraceId(event: IngestionEventType): string | null | undefined {+ if (event.type === "trace-create") return event.body.id;++ return "traceId" in event.body ? event.body.traceId : null;+}