Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(evals): fail closed on internal eval targets at eval execution time (#14835)

Hassieb Pakzadb1a3a9a1d97b
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 5909ef37dc..db989392e5 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -79,6 +79,7 @@ import {
completeEvalExecution,
type EvalExecutionResult,
} from "./evalCompletion";
+import { isEvalTargetEnvironmentAllowed } from "./isEvalTargetEnvironmentAllowed";
import {
type EvalExecutionDeps,
createProductionEvalExecutionDeps,
@@ -1135,6 +1136,41 @@ export const evaluate = async ({
`Extracted ${extractedVariables.length} variables for job ${event.jobExecutionId}`,
);
+ const environment =
+ getEnvironmentFromVariables(extractedVariables) ??
+ DEFAULT_TRACE_ENVIRONMENT;
+
+ // Final fail-closed loop safeguard: never execute an eval whose target
+ // lives in an internal Langfuse environment, regardless of which scheduling
+ // path created the job. See isEvalTargetEnvironmentAllowed. The environment
+ // is derived from the extracted trace/observation variables; mappings
+ // without any tracing-data variable fall back to the default environment
+ // and rely on the scheduling-time guards.
+ if (!isEvalTargetEnvironmentAllowed(environment)) {
+ logger.warn(
+ "Cancelling eval job targeting an internal Langfuse environment",
+ {
+ jobExecutionId: event.jobExecutionId,
+ projectId: event.projectId,
+ environment,
+ traceId: job.jobInputTraceId,
+ },
+ );
+ recordIncrement(
+ "langfuse.evaluation-execution.internal_target_blocked",
+ 1,
+ {
+ source: "trace-eval",
+ },
+ );
+ await prisma.jobExecution.update({
+ where: { id: job.id, projectId: event.projectId },
+ data: { status: JobExecutionStatus.CANCELLED, endTime: new Date() },
+ });
+
+ return;
+ }
+
// Execute the shared LLM-as-a-judge evaluation
await executeLLMAsJudgeEvaluation({
projectId: event.projectId,
@@ -1143,9 +1179,7 @@ export const evaluate = async ({
config,
template: template as EvalTemplateLlmAsAJudge,
extractedVariables,
- environment:
- getEnvironmentFromVariables(extractedVariables) ??
- DEFAULT_TRACE_ENVIRONMENT,
+ environment,
});
};
diff --git a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts
new file mode 100644
index 0000000000..98a7abf1ba
--- /dev/null
+++ b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import { isEvalTargetEnvironmentAllowed } from "./isEvalTargetEnvironmentAllowed";
+
+describe("isEvalTargetEnvironmentAllowed", () => {
+ it("allows user environments", () => {
+ expect(isEvalTargetEnvironmentAllowed("default")).toBe(true);
+ expect(isEvalTargetEnvironmentAllowed("production")).toBe(true);
+ });
+
+ it("allows missing environments (defaulted downstream)", () => {
+ expect(isEvalTargetEnvironmentAllowed(undefined)).toBe(true);
+ expect(isEvalTargetEnvironmentAllowed(null)).toBe(true);
+ });
+
+ it("blocks eval-on-eval targets across all internal environments", () => {
+ for (const environment of [
+ "langfuse-llm-as-a-judge",
+ "langfuse-code-eval",
+ "langfuse-natural-language-filter",
+ "langfuse-in-app-agent",
+ "langfuse",
+ ]) {
+ expect(isEvalTargetEnvironmentAllowed(environment)).toBe(false);
+ }
+ });
+
+ it("allows the sanctioned prompt-experiment targets", () => {
+ expect(isEvalTargetEnvironmentAllowed("langfuse-prompt-experiment")).toBe(
+ true,
+ );
+ });
+});
diff --git a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts
new file mode 100644
index 0000000000..f82eed4bd4
--- /dev/null
+++ b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts
@@ -0,0 +1,34 @@
+import { LangfuseInternalTraceEnvironment } from "@langfuse/shared/src/server";
+
+/**
+ * Final, fail-closed loop safeguard at eval EXECUTION time.
+ *
+ * Internal Langfuse executions (LLM-as-a-judge, code evals, natural-language
+ * filters) write their telemetry into reserved `langfuse-*` environments. An
+ * eval whose TARGET lives in such an environment is an eval-of-an-eval: it
+ * would spawn another internal execution, whose telemetry could be evaluated
+ * again — an infinite loop with per-cycle LLM cost.
+ *
+ * Scheduling-time guards exist per entry point (trace-upsert in
+ * createEvalJobs, the OTel queue's observation-eval guard), but every new
+ * ingestion mode or scheduling path must remember to add one. This check runs
+ * where all paths converge — the eval executors, right before any LLM/code
+ * execution — so a missing upstream guard degrades to wasted queue churn, not
+ * recursion.
+ *
+ * Single sanctioned exception: prompt-experiment outputs. Users attach
+ * evaluators to dataset runs, so their run items (environment
+ * `langfuse-prompt-experiment`) are legitimate eval targets. This cannot
+ * re-open a loop: experiments are only ever created by explicit user actions
+ * (never by ingestion), and the evals they trigger execute in
+ * `langfuse-llm-as-a-judge`, which stays blocked here.
+ */
+export function isEvalTargetEnvironmentAllowed(
+ environment: string | null | undefined,
+): boolean {
+ if (!environment?.startsWith("langfuse")) {
+ return true;
+ }
+
+ return environment === LangfuseInternalTraceEnvironment.PromptExperiments;
+}
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
index fbd7a774d7..d172a3c603 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
@@ -810,4 +810,79 @@ describe("processObservationEval", () => {
).rejects.toThrow();
});
});
+
+ describe("internal target loop safeguard", () => {
+ const setupExecutableJob = (environment: string) => {
+ const job = createMockJobExecution({
+ id: jobExecutionId,
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ jobConfigurationId: "config-123",
+ jobInputTraceId: "trace-abc",
+ jobInputObservationId: "obs-xyz",
+ });
+ const template = createMockEvalTemplate({
+ id: "template-456",
+ projectId,
+ prompt: "Evaluate: {{output}}",
+ });
+ const config = createMockJobConfiguration({
+ id: "config-123",
+ projectId,
+ evalTemplateId: "template-456",
+ variableMapping: [
+ { templateVariable: "output", selectedColumnId: "output" },
+ ],
+ evalTemplate: template,
+ });
+ const observation = createTestObservation({
+ span_id: "obs-xyz",
+ project_id: projectId,
+ trace_id: "trace-abc",
+ environment,
+ output: '{"response": "test output"}',
+ });
+
+ (prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
+ (prisma.jobConfiguration.findFirst as Mock).mockResolvedValue(config);
+
+ return createMockProcessorDeps({
+ downloadObservationFromS3: vi
+ .fn()
+ .mockResolvedValue(JSON.stringify(observation)),
+ });
+ };
+
+ it("cancels jobs targeting internal observations instead of executing (eval-on-eval loop guard)", async () => {
+ const deps = setupExecutableJob("langfuse-llm-as-a-judge");
+
+ await processObservationEval({
+ event: baseEvent,
+ executionType: EvalTemplateType.LLM_AS_JUDGE,
+ deps,
+ });
+
+ expect(runLLMAsJudgeEvaluation).not.toHaveBeenCalled();
+ expect(executeCodeBasedEvaluation).not.toHaveBeenCalled();
+ expect(prisma.jobExecution.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ status: JobExecutionStatus.CANCELLED,
+ }),
+ }),
+ );
+ });
+
+ it("executes evals on sanctioned prompt-experiment targets", async () => {
+ const deps = setupExecutableJob("langfuse-prompt-experiment");
+
+ await processObservationEval({
+ event: baseEvent,
+ executionType: EvalTemplateType.LLM_AS_JUDGE,
+ deps,
+ });
+
+ expect(runLLMAsJudgeEvaluation).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
index 650fb77d2f..2a6fbc63be 100644
--- a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
+++ b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
@@ -4,8 +4,10 @@ import {
ObservationEvalExecutionEventSchema,
extractObservationVariables,
logger,
+ recordIncrement,
type ExtractedVariable,
} from "@langfuse/shared/src/server";
+import { isEvalTargetEnvironmentAllowed } from "../isEvalTargetEnvironmentAllowed";
import {
observationForEvalSchema,
observationVariableMappingList,
@@ -204,6 +206,34 @@ export async function processObservationEval(
`Downloaded observation data for job ${job.id}: span_id=${observationData.span_id}`,
);
+ // Final fail-closed loop safeguard: never execute an eval whose target
+ // lives in an internal Langfuse environment, regardless of which scheduling
+ // path created the job. See isEvalTargetEnvironmentAllowed.
+ if (!isEvalTargetEnvironmentAllowed(observationData.environment)) {
+ logger.warn(
+ "Cancelling eval job targeting an internal Langfuse environment",
+ {
+ jobExecutionId: event.jobExecutionId,
+ projectId: event.projectId,
+ environment: observationData.environment,
+ observationId: observationData.span_id,
+ },
+ );
+ recordIncrement(
+ "langfuse.evaluation-execution.internal_target_blocked",
+ 1,
+ {
+ source: "observation-eval",
+ },
+ );
+ await prisma.jobExecution.update({
+ where: { id: job.id, projectId: event.projectId },
+ data: { status: JobExecutionStatus.CANCELLED, endTime: new Date() },
+ });
+
+ return;
+ }
+
// Extract variables from observation
const parsedVariableMapping = observationVariableMappingList.parse(
evalJobConfig.variableMapping,