🪢 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
fix(worker): make evaluator sampling deterministic (#15798)
Tobias Wochingerb4dd4e6e0a05
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex 505592f163..ec61d7b920 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -1250,6 +1250,53 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;expect(jobs.length).toBe(0);}, 10_000);+ test("deterministically creates nested samples across configs", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const traceId = "trace-456";+ const sampledOutConfigId = randomUUID();+ const sampledInConfigId = randomUUID();++ await prisma.jobConfiguration.createMany({+ data: [+ {+ id: sampledOutConfigId,+ projectId,+ filter: JSON.parse("[]"),+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("0.5"),+ targetObject: EvalTargetObject.TRACE,+ scoreName: "score",+ variableMapping: JSON.parse("[]"),+ },+ {+ id: sampledInConfigId,+ projectId,+ filter: JSON.parse("[]"),+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("0.9"),+ targetObject: EvalTargetObject.TRACE,+ scoreName: "score",+ variableMapping: JSON.parse("[]"),+ },+ ],+ });++ await createEvalJobs({+ sourceEventType: "trace-upsert",+ event: { projectId, traceId },+ jobTimestamp,+ });++ const jobs = await prisma.jobExecution.findMany({+ where: { projectId },+ });++ expect(jobs).toHaveLength(1);+ expect(jobs[0].jobConfigurationId).toBe(sampledInConfigId);+ }, 10_000);+test("does not create eval job for existing traces if time scope is EXISTING but handler enforces NEW only", async () => {const { projectId } = await createOrgProjectAndApiKey();const traceId = randomUUID();diff --git a/worker/src/features/evaluation/__tests__/deterministicSampling.test.ts b/worker/src/features/evaluation/__tests__/deterministicSampling.test.tsnew file mode 100644index 0000000000..ab4024a727--- /dev/null+++ b/worker/src/features/evaluation/__tests__/deterministicSampling.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";+import {+ getDeterministicSamplingValue,+ shouldSampleEvaluation,+} from "../deterministicSampling";++describe("deterministic evaluation sampling", () => {+ it("maps a target ID to a stable value in the half-open unit interval", () => {+ expect(getDeterministicSamplingValue("obs-123")).toBe(0.6881281372814657);++ for (const targetId of ["", "obs-123", "trace-456"]) {+ const samplingValue = getDeterministicSamplingValue(targetId);++ expect(samplingValue).toBeGreaterThanOrEqual(0);+ expect(samplingValue).toBeLessThan(1);+ expect(getDeterministicSamplingValue(targetId)).toBe(samplingValue);+ }+ });++ it("creates nested samples as the sampling rate increases", () => {+ const samplingValue = getDeterministicSamplingValue("obs-123");++ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 0.5 })).toBe(+ false,+ );+ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 0.7 })).toBe(+ true,+ );+ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 0.9 })).toBe(+ true,+ );+ });++ it("uses a half-open threshold and preserves zero and one boundaries", () => {+ const targetId = "obs-123";+ const samplingValue = getDeterministicSamplingValue(targetId);++ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 0 })).toBe(+ false,+ );+ expect(shouldSampleEvaluation({ samplingValue, samplingRate: -0.1 })).toBe(+ false,+ );+ expect(+ shouldSampleEvaluation({ samplingValue, samplingRate: samplingValue }),+ ).toBe(false);+ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 1 })).toBe(+ true,+ );+ expect(shouldSampleEvaluation({ samplingValue, samplingRate: 1.1 })).toBe(+ true,+ );+ });+});diff --git a/worker/src/features/evaluation/deterministicSampling.ts b/worker/src/features/evaluation/deterministicSampling.tsnew file mode 100644index 0000000000..efb4fd2948--- /dev/null+++ b/worker/src/features/evaluation/deterministicSampling.ts@@ -0,0 +1,29 @@+import { createHash } from "node:crypto";++const SAMPLING_DOMAIN = "langfuse:evaluation-sampling:v1\0";+const SAMPLING_BUCKET_COUNT = 2 ** 53;++export function getDeterministicSamplingValue(targetId: string) {+ const digest = createHash("sha256")+ .update(SAMPLING_DOMAIN, "utf8")+ .update(targetId, "utf8")+ .digest();++ // JavaScript Numbers represent integers through 2^53 - 1 exactly. Taking+ // 53 hash bits therefore keeps every bucket distinct after conversion.+ const hash53 = digest.readBigUInt64BE(0) >> 11n;++ return Number(hash53) / SAMPLING_BUCKET_COUNT;+}++export function shouldSampleEvaluation(params: {+ samplingValue: number;+ samplingRate: number;+}) {+ const { samplingValue, samplingRate } = params;++ if (samplingRate >= 1) return true;+ if (samplingRate <= 0) return false;++ return samplingValue < samplingRate;+}diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex f973baa858..02a5f4d091 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -93,6 +93,10 @@ import {buildEvalExecutionSpanAttributes,buildEvaluatorLlmErrorSpanAttributes,} from "./evalSpanAttributes";+import {+ getDeterministicSamplingValue,+ shouldSampleEvaluation,+} from "./deterministicSampling";/*** Determines which eval jobs to create for a given event (traces or dataset run items).@@ -397,6 +401,12 @@ export const createEvalJobs = async ({);};+ const samplingTargetId =+ "observationId" in event && event.observationId+ ? event.observationId+ : event.traceId;+ const samplingValue = getDeterministicSamplingValue(samplingTargetId);+for (const config of configs) {if (config.status === JobConfigState.INACTIVE) {logger.debug(`Skipping inactive config ${config.id}`);@@ -640,16 +650,17 @@ export const createEvalJobs = async ({continue;}- // apply sampling. Only if the job is sampled, we create a job- // user supplies a number between 0 and 1, which is the probability of sampling- if (Number(config.sampling) !== 1) {- const random = Math.random();- if (random > Number(config.sampling)) {- logger.debug(- `Eval job for config ${config.id} and trace ${event.traceId} was sampled out`,- );- continue;- }+ const samplingRate = Number(config.sampling);+ if (+ !shouldSampleEvaluation({+ samplingValue,+ samplingRate,+ })+ ) {+ logger.debug(+ `Eval job for config ${config.id} and trace ${event.traceId} was sampled out`,+ );+ continue;}logger.debug(diff --git a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.tsindex f5d8e66ba9..185ca8d0b0 100644--- a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts@@ -328,6 +328,33 @@ describe("scheduleObservationEvals", () => {expect(schedulerDeps.upsertJobExecution).toHaveBeenCalled();expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalled();});++ it("should deterministically create nested samples across configs", async () => {+ const schedulerDeps = createMockSchedulerDeps();+ const observation = createMockObservation({ span_id: "obs-123" });++ await scheduleObservationEvals({+ observation,+ configs: [+ createMockConfig({+ id: "sampled-out-config",+ sampling: { toNumber: () => 0.5 } as unknown as Prisma.Decimal,+ }),+ createMockConfig({+ id: "sampled-in-config",+ sampling: { toNumber: () => 0.7 } as unknown as Prisma.Decimal,+ }),+ ],+ schedulerDeps,+ });++ expect(schedulerDeps.uploadObservationToS3).toHaveBeenCalledTimes(1);+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalledTimes(1);+ expect(schedulerDeps.upsertJobExecution).toHaveBeenCalledWith(+ expect.objectContaining({ jobConfigurationId: "sampled-in-config" }),+ );+ expect(schedulerDeps.enqueueEvalJob).toHaveBeenCalledTimes(1);+ });});describe("job creation and enqueuing", () => {diff --git a/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.ts b/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.tsdeleted file mode 100644index 2750960715..0000000000--- a/worker/src/features/evaluation/observationEval/__tests__/shouldSampleObservation.test.ts+++ /dev/null@@ -1,129 +0,0 @@-import { describe, it, expect } from "vitest";-import { shouldSampleObservation } from "../shouldSampleObservation";--describe("shouldSampleObservation", () => {- describe("edge cases", () => {- it("should always return true when samplingRate is 1", () => {- // Even with random values near the boundary, sampling rate 1 should always pass- expect(shouldSampleObservation({ samplingRate: 1, randomValue: 0 })).toBe(- true,- );- expect(- shouldSampleObservation({ samplingRate: 1, randomValue: 0.5 }),- ).toBe(true);- expect(- shouldSampleObservation({ samplingRate: 1, randomValue: 0.999 }),- ).toBe(true);- });-- it("should always return true when samplingRate is greater than 1", () => {- // Values > 1 should be treated as 100% sampling- expect(- shouldSampleObservation({ samplingRate: 1.5, randomValue: 0.999 }),- ).toBe(true);- expect(- shouldSampleObservation({ samplingRate: 100, randomValue: 0.999 }),- ).toBe(true);- });-- it("should always return false when samplingRate is 0", () => {- expect(shouldSampleObservation({ samplingRate: 0, randomValue: 0 })).toBe(- false,- );- expect(- shouldSampleObservation({ samplingRate: 0, randomValue: 0.5 }),- ).toBe(false);- expect(- shouldSampleObservation({ samplingRate: 0, randomValue: 0.001 }),- ).toBe(false);- });-- it("should always return false when samplingRate is negative", () => {- // Negative values should be treated as 0% sampling- expect(- shouldSampleObservation({ samplingRate: -0.5, randomValue: 0 }),- ).toBe(false);- expect(- shouldSampleObservation({ samplingRate: -1, randomValue: 0 }),- ).toBe(false);- });- });-- describe("sampling behavior", () => {- it("should return true when randomValue is less than samplingRate", () => {- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.3 }),- ).toBe(true);- expect(- shouldSampleObservation({ samplingRate: 0.8, randomValue: 0.7 }),- ).toBe(true);- expect(- shouldSampleObservation({ samplingRate: 0.1, randomValue: 0.05 }),- ).toBe(true);- });-- it("should return false when randomValue is greater than or equal to samplingRate", () => {- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.7 }),- ).toBe(false);- expect(- shouldSampleObservation({ samplingRate: 0.3, randomValue: 0.5 }),- ).toBe(false);- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5 }),- ).toBe(false);- });-- it("should handle boundary values correctly", () => {- // Just below the threshold - should pass- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.4999 }),- ).toBe(true);-- // At the threshold - should not pass (using strict less than)- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5 }),- ).toBe(false);-- // Just above the threshold - should not pass- expect(- shouldSampleObservation({ samplingRate: 0.5, randomValue: 0.5001 }),- ).toBe(false);- });- });-- describe("default random value", () => {- it("should use Math.random when randomValue is not provided", () => {- // Run multiple times to verify it uses randomness- // With sampling rate of 1, should always return true- for (let i = 0; i < 10; i++) {- expect(shouldSampleObservation({ samplingRate: 1 })).toBe(true);- }-- // With sampling rate of 0, should always return false- for (let i = 0; i < 10; i++) {- expect(shouldSampleObservation({ samplingRate: 0 })).toBe(false);- }- });- });-- describe("probabilistic correctness", () => {- it("should sample approximately the correct percentage over many iterations", () => {- const samplingRate = 0.3;- const iterations = 1000;- let sampledCount = 0;-- // Use deterministic "random" values spread across [0, 1)- for (let i = 0; i < iterations; i++) {- const randomValue = i / iterations;- if (shouldSampleObservation({ samplingRate, randomValue })) {- sampledCount++;- }- }-- // With evenly distributed random values, exactly 30% should be sampled- // (all values from 0 to 0.299 will pass, which is 300 values)- expect(sampledCount).toBe(Math.floor(iterations * samplingRate));- });- });-});diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.tsindex c74d89b3e5..395edff0d3 100644--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts@@ -3,7 +3,10 @@ import {type ObservationEvalConfig,type ObservationEvalSchedulerDeps,} from "./types";-import { shouldSampleObservation } from "./shouldSampleObservation";+import {+ getDeterministicSamplingValue,+ shouldSampleEvaluation,+} from "../deterministicSampling";import {InMemoryFilterService,LangfuseInternalTraceEnvironment,@@ -88,6 +91,8 @@ export async function scheduleObservationEvals(return;}+ const samplingValue = getDeterministicSamplingValue(observation.span_id);+// Filter configs that match this observation (filter + sampling).// This is done before S3 upload to avoid unnecessary uploads.const matchingConfigs = configs.filter((config) => {@@ -112,7 +117,12 @@ export async function scheduleObservationEvals(// Check samplingconst samplingRate = config.sampling.toNumber();- if (!shouldSampleObservation({ samplingRate })) {+ if (+ !shouldSampleEvaluation({+ samplingValue,+ samplingRate,+ })+ ) {logger.debug("Observation sampled out for eval config", {configId: config.id,observationId: observation.span_id,diff --git a/worker/src/features/evaluation/observationEval/shouldSampleObservation.ts b/worker/src/features/evaluation/observationEval/shouldSampleObservation.tsdeleted file mode 100644index 3a54dfbd90..0000000000--- a/worker/src/features/evaluation/observationEval/shouldSampleObservation.ts+++ /dev/null@@ -1,22 +0,0 @@-interface ShouldSampleParams {- samplingRate: number;- randomValue?: number; // Injectable for testing-}--/**- * Determines whether an observation should be sampled for evaluation.- *- * @param params.samplingRate - A number between 0 and 1 representing the probability- * of sampling. Values >= 1 always sample, values <= 0 never sample.- * @param params.randomValue - Optional injectable random value for testing.- * If not provided, Math.random() is used.- * @returns true if the observation should be sampled, false otherwise.- */-export function shouldSampleObservation(params: ShouldSampleParams): boolean {- const { samplingRate, randomValue = Math.random() } = params;-- if (samplingRate >= 1) return true;- if (samplingRate <= 0) return false;-- return randomValue < samplingRate;-}