πͺ’ 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(scores): add all filter params to v3 scores API (Phase 4) (#14005)
Niklas Semmler9eec10511f12
diff --git a/fern/apis/server/_drafts/scores-v3.yml b/fern/apis/server/_drafts/scores-v3.ymlindex 1c87cde88e..23b48946f4 100644--- a/fern/apis/server/_drafts/scores-v3.yml+++ b/fern/apis/server/_drafts/scores-v3.yml@@ -36,6 +36,66 @@ service:docs: >Comma-separated field groups to include. Allowed: core, details,subject, annotation. Defaults to "core". Unknown names return HTTP 400.+ id:+ type: optional<string>+ docs: Comma-separated list of score IDs to filter by (OR within, AND across filters).+ name:+ type: optional<string>+ docs: Comma-separated list of score names to filter by.+ source:+ type: optional<string>+ docs: Comma-separated list of score sources to filter by (e.g. API, ANNOTATION, EVAL).+ dataType:+ type: optional<string>+ docs: Comma-separated list of data types to filter by (NUMERIC, BOOLEAN, CATEGORICAL, TEXT, CORRECTION). Must be a single value when used with value, valueMin, or valueMax; otherwise the request returns HTTP 400. Must be NUMERIC when used with valueMin or valueMax.+ environment:+ type: optional<string>+ docs: Comma-separated list of environments to filter by.+ configId:+ type: optional<string>+ docs: Comma-separated list of score config IDs to filter by.+ queueId:+ type: optional<string>+ docs: Comma-separated list of annotation queue IDs to filter by.+ authorUserId:+ type: optional<string>+ docs: Comma-separated list of author user IDs to filter by.+ value:+ type: optional<string>+ docs: >+ Comma-separated list of exact values to filter by. Requires a+ single dataType from NUMERIC, BOOLEAN, or CATEGORICAL; any other+ dataType, multiple dataTypes, or omitting dataType returns HTTP+ 400. For BOOLEAN, each value must be "true" or "false"; for+ NUMERIC, each value must be a finite number. Otherwise the+ request returns HTTP 400.+ valueMin:+ type: optional<double>+ docs: Inclusive lower bound on the numeric value. Requires dataType=NUMERIC as a single value; otherwise the request returns HTTP 400.+ valueMax:+ type: optional<double>+ docs: Inclusive upper bound on the numeric value. Requires dataType=NUMERIC as a single value; otherwise the request returns HTTP 400.+ traceId:+ type: optional<string>+ docs: Comma-separated list of trace IDs to filter by. Mutually exclusive with sessionId, experimentId. May be combined with observationId to scope the observation lookup to a specific trace.+ sessionId:+ type: optional<string>+ docs: Comma-separated list of session IDs to filter by. Mutually exclusive with traceId, observationId, experimentId.+ observationId:+ type: optional<string>+ docs: >+ Comma-separated list of observation IDs to filter by. Requires traceId to be specified,+ because observation IDs are scoped to a trace. Mutually exclusive with sessionId, experimentId.+ Returns HTTP 400 when used without traceId.+ experimentId:+ type: optional<string>+ docs: Comma-separated list of dataset run IDs (experiment IDs) to filter by. Mutually exclusive with traceId, sessionId, observationId.+ fromTimestamp:+ type: optional<datetime>+ docs: Inclusive lower bound on the score timestamp.+ toTimestamp:+ type: optional<datetime>+ docs: Exclusive upper bound on the score timestamp.response: GetScoresV3Responsetypes:diff --git a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.tsindex 53b5cd29ad..9ad89dd9eb 100644--- a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts+++ b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts@@ -1,4 +1,8 @@import { z } from "zod";+import {+ ScoreDataTypeArray,+ ScoreSourceArray,+} from "../../../../../domain/scores";import { APIScoreSchemaV3 } from "./schemas";export const SCORE_FIELD_GROUPS_V3 = [@@ -15,10 +19,94 @@ const fieldsParam = z.transform((val) => (val ? val.split(",").map((g) => g.trim()) : ["core"])).pipe(z.array(z.enum(SCORE_FIELD_GROUPS_V3)));-// GET /v3/scores+const csvStringParam = z+ .string()+ .transform((val) =>+ val+ .split(",")+ .map((v) => v.trim())+ .filter((v) => v.length > 0),+ )+ .optional();++const csvEnumParam = <T extends readonly string[]>(+ allowedValues: T,+ label: string,+) =>+ z+ .string()+ .transform((val) =>+ val+ .split(",")+ .map((v) => v.trim())+ .filter((v) => v.length > 0),+ )+ .pipe(+ z.array(z.string()).superRefine((values, ctx) => {+ for (const v of values) {+ if (!allowedValues.includes(v as T[number])) {+ ctx.addIssue({+ code: "custom",+ message: `Invalid ${label} value: "${v}". Allowed: ${allowedValues.join(", ")}`,+ });+ }+ }+ }),+ )+ .optional();++// GET /v3/scores β all filter params optional; superRefine validation lives in the handler.export const GetScoresQueryV3 = z.object({limit: z.coerce.number().int().positive().max(100).default(50),fields: fieldsParam,+ // Identifier filters (multi-value, comma-separated)+ id: csvStringParam,+ name: csvStringParam,+ source: csvEnumParam(ScoreSourceArray, "source"),+ dataType: csvEnumParam(ScoreDataTypeArray, "dataType"),+ environment: csvStringParam,+ configId: csvStringParam,+ queueId: csvStringParam,+ authorUserId: csvStringParam,+ // Value filters+ value: csvStringParam,+ // Treat empty string as absent so `?valueMin=` doesn't silently coerce to 0+ // and narrow results to `value >= 0`. Zod 4 rejects Β±Infinity / NaN out of+ // the box, so `.finite()` is not needed.+ valueMin: z.preprocess(+ (v) => (v === "" ? undefined : v),+ z.coerce.number().optional(),+ ),+ valueMax: z.preprocess(+ (v) => (v === "" ? undefined : v),+ z.coerce.number().optional(),+ ),+ // Entity-bounded filters+ traceId: csvStringParam,+ sessionId: csvStringParam,+ observationId: csvStringParam,+ experimentId: csvStringParam,+ // Timestamp filters β preprocess empty string to undefined so ?fromTimestamp=+ // from a templating system is treated as absent, consistent with valueMin/valueMax.+ fromTimestamp: z.preprocess(+ (v) => (v === "" ? undefined : v),+ z.coerce.date().optional(),+ ),+ toTimestamp: z.preprocess(+ (v) => (v === "" ? undefined : v),+ z.coerce.date().optional(),+ ),+ // Deferred params (always β 400 β require trace JOIN not present in v3).+ // Treat the empty string as absent so a stray `?userId=` from a templating+ // system doesn't trigger the "use v2" 400 spuriously.+ userId: z+ .string()+ .optional()+ .transform((v) => (v === "" ? undefined : v)),+ traceTags: z+ .string()+ .optional()+ .transform((v) => (v === "" ? undefined : v)),});export const GetScoresResponseV3 = z.object({diff --git a/web/src/__tests__/server/scores-api-v3.servertest.ts b/web/src/__tests__/server/scores-api-v3.servertest.tsindex f3354924f5..f6aeaac623 100644--- a/web/src/__tests__/server/scores-api-v3.servertest.ts+++ b/web/src/__tests__/server/scores-api-v3.servertest.ts@@ -5,6 +5,7 @@ import {createScoresCh,createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";+import { transformBooleanValueForFilter } from "@/src/features/public-api/server/scores-api-v3";import {makeAPICall,makeZodVerifiedAPICall,@@ -563,6 +564,7 @@ describe("/api/public/v3/scores API Endpoint", () => {expect(score!.details).toBeDefined();expect(score!.details!.comment).toBe("test comment");expect(score!.details!.configId).toBe("cfg-abc");+ expect(score!.details!.metadata).toEqual({ key: "val" });expect(score).not.toHaveProperty("subject");expect(score).not.toHaveProperty("annotation");});@@ -796,4 +798,970 @@ describe("/api/public/v3/scores API Endpoint", () => {expect(score!.subject!.id).toBe(traceId);});});++ describe("transformBooleanValueForFilter unit", () => {+ it('"true" β 1', () => {+ expect(transformBooleanValueForFilter("true")).toBe(1);+ });+ it('"false" β 0', () => {+ expect(transformBooleanValueForFilter("false")).toBe(0);+ });+ });++ describe("GET /api/public/v3/scores β filter params", () => {+ let auth: string;+ let projectId: string;++ beforeAll(async () => {+ const project = await createOrgProjectAndApiKey();+ auth = project.auth;+ projectId = project.projectId;+ });++ // --- Validation (400) tests ---++ it("userId β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?userId=u1",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("traceTags β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?traceTags=tag1",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value= without dataType β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=0.5",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value= with multi-value dataType β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=0.5&dataType=NUMERIC,BOOLEAN",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value= with dataType=TEXT β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=foo&dataType=TEXT",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value=1 with dataType=BOOLEAN β 400 (must be true/false)", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=1&dataType=BOOLEAN",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("valueMin= with dataType=CATEGORICAL β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?valueMin=0.2&dataType=CATEGORICAL",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("valueMin= without dataType β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?valueMin=0.2",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("two exclusive parent-entity params β 400", async () => {+ const res = await makeAPICall(+ "GET",+ `/api/public/v3/scores?traceId=${v4()}&sessionId=${v4()}`,+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("observationId without traceId β 400", async () => {+ const res = await makeAPICall(+ "GET",+ `/api/public/v3/scores?observationId=${v4()}`,+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ // --- Filter correctness tests ---++ it("id filter (single) returns only matching score", async () => {+ const scoreId = v4();+ const otherId = v4();+ await createScoresCh([+ createTraceScore({ id: scoreId, project_id: projectId }),+ createTraceScore({ id: otherId, project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?id=${scoreId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("id filter (comma-separated) returns both matching scores", async () => {+ const id1 = v4();+ const id2 = v4();+ const id3 = v4();+ await createScoresCh([+ createTraceScore({ id: id1, project_id: projectId }),+ createTraceScore({ id: id2, project_id: projectId }),+ createTraceScore({ id: id3, project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?id=${id1},${id2}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(id1);+ expect(ids).toContain(id2);+ expect(ids).not.toContain(id3);+ });++ it("name filter returns only scores with matching name", async () => {+ const scoreName = `filter-test-name-${v4()}`;+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ name: scoreName,+ }),+ createTraceScore({ project_id: projectId, name: "other-name" }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?name=${encodeURIComponent(scoreName)}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.every((s) => s.name === scoreName)).toBe(true);+ expect(res.body.data.some((s) => s.id === scoreId)).toBe(true);+ });++ it("source filter returns only scores with matching source", async () => {+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ source: "ANNOTATION",+ }),+ createTraceScore({ project_id: projectId, source: "API" }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?source=ANNOTATION",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.every((s) => s.source === "ANNOTATION")).toBe(true);+ expect(res.body.data.some((s) => s.id === scoreId)).toBe(true);+ });++ it("dataType filter returns only scores of that type", async () => {+ const numericId = v4();+ const boolId = v4();+ await createScoresCh([+ createTraceScore({+ id: numericId,+ project_id: projectId,+ data_type: "NUMERIC",+ value: 0.5,+ }),+ createTraceScore({+ id: boolId,+ project_id: projectId,+ data_type: "BOOLEAN",+ value: 1,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?dataType=NUMERIC",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.every((s) => s.dataType === "NUMERIC")).toBe(true);+ expect(res.body.data.some((s) => s.id === numericId)).toBe(true);+ });++ it("traceId filter returns only scores for that trace", async () => {+ const traceId = v4();+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ trace_id: traceId,+ }),+ createTraceScore({ project_id: projectId, trace_id: v4() }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?traceId=${traceId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("observationId + traceId filter returns only the matching observation-level score", async () => {+ const traceId = v4();+ const observationId = v4();+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ trace_id: traceId,+ observation_id: observationId,+ }),+ createTraceScore({ project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?traceId=${traceId}&observationId=${observationId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("traceId + observationId scopes to the correct trace (cross-trace isolation)", async () => {+ const traceId = v4();+ const observationId = v4();+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ trace_id: traceId,+ observation_id: observationId,+ }),+ // same observationId but on a different trace β must not appear+ createTraceScore({+ project_id: projectId,+ trace_id: v4(),+ observation_id: observationId,+ }),+ createTraceScore({ project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?traceId=${traceId}&observationId=${observationId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("sessionId filter returns only session scores", async () => {+ const sessionId = v4();+ const scoreId = v4();+ await createScoresCh([+ createSessionScore({+ id: scoreId,+ project_id: projectId,+ session_id: sessionId,+ }),+ createTraceScore({ project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?sessionId=${sessionId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("experimentId filter returns only dataset run scores", async () => {+ const datasetRunId = v4();+ const scoreId = v4();+ await createScoresCh([+ createDatasetRunScore({+ id: scoreId,+ project_id: projectId,+ dataset_run_id: datasetRunId,+ }),+ createTraceScore({ project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?experimentId=${datasetRunId}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toEqual([scoreId]);+ });++ it("value=0.85 dataType=NUMERIC matches numeric column", async () => {+ const scoreId = v4();+ const otherId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ data_type: "NUMERIC",+ value: 0.85,+ }),+ createTraceScore({+ id: otherId,+ project_id: projectId,+ data_type: "NUMERIC",+ value: 0.5,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?value=0.85&dataType=NUMERIC",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.map((s) => s.id)).toContain(scoreId);+ expect(res.body.data.map((s) => s.id)).not.toContain(otherId);+ });++ it("value=good,bad dataType=CATEGORICAL matches string_value", async () => {+ const goodId = v4();+ const badId = v4();+ const otherId = v4();+ await createScoresCh([+ createTraceScore({+ id: goodId,+ project_id: projectId,+ data_type: "CATEGORICAL",+ value: 0,+ string_value: "good",+ }),+ createTraceScore({+ id: badId,+ project_id: projectId,+ data_type: "CATEGORICAL",+ value: 0,+ string_value: "bad",+ }),+ createTraceScore({+ id: otherId,+ project_id: projectId,+ data_type: "CATEGORICAL",+ value: 0,+ string_value: "neutral",+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?value=good,bad&dataType=CATEGORICAL",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(goodId);+ expect(ids).toContain(badId);+ expect(ids).not.toContain(otherId);+ });++ it("value=true dataType=BOOLEAN matches numeric column = 1", async () => {+ const trueId = v4();+ const falseId = v4();+ await createScoresCh([+ createTraceScore({+ id: trueId,+ project_id: projectId,+ data_type: "BOOLEAN",+ value: 1,+ string_value: "true",+ }),+ createTraceScore({+ id: falseId,+ project_id: projectId,+ data_type: "BOOLEAN",+ value: 0,+ string_value: "false",+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?value=true&dataType=BOOLEAN",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(trueId);+ expect(ids).not.toContain(falseId);+ });++ it("value=true,false dataType=BOOLEAN β 200, returns all boolean scores", async () => {+ const trueId = v4();+ const falseId = v4();+ await createScoresCh([+ createTraceScore({+ id: trueId,+ project_id: projectId,+ data_type: "BOOLEAN",+ value: 1,+ string_value: "true",+ }),+ createTraceScore({+ id: falseId,+ project_id: projectId,+ data_type: "BOOLEAN",+ value: 0,+ string_value: "false",+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?value=true,false&dataType=BOOLEAN",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(trueId);+ expect(ids).toContain(falseId);+ });++ it("valueMin/valueMax filter matches only scores in range", async () => {+ const inRangeId = v4();+ const outOfRangeId = v4();+ await createScoresCh([+ createTraceScore({+ id: inRangeId,+ project_id: projectId,+ data_type: "NUMERIC",+ value: 0.7,+ }),+ createTraceScore({+ id: outOfRangeId,+ project_id: projectId,+ data_type: "NUMERIC",+ value: 0.2,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?valueMin=0.5&valueMax=1.0&dataType=NUMERIC",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(inRangeId);+ expect(ids).not.toContain(outOfRangeId);+ });++ it("fromTimestamp omitted with no entity filter β 200", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores",+ undefined,+ auth,+ );+ expect(res.status).toBe(200);+ });++ it("source=INVALID β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?source=BOGUS",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("dataType=INVALID β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?dataType=NUMRIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value=notanumber&dataType=NUMERIC β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=notanumber&dataType=NUMERIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value=Infinity&dataType=NUMERIC β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=Infinity&dataType=NUMERIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("valueMin=Infinity&dataType=NUMERIC β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?valueMin=Infinity&dataType=NUMERIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("valueMax=-Infinity&dataType=NUMERIC β 400", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?valueMax=-Infinity&dataType=NUMERIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(400);+ });++ it("value= (empty) with dataType=NUMERIC β 200 (not treated as present)", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?value=&dataType=NUMERIC",+ undefined,+ auth,+ );+ expect(res.status).toBe(200);+ });++ it("valueMin= (empty) with dataType=NUMERIC β 200, does not narrow to value>=0", async () => {+ // Regression: z.coerce.number() coerces "" to 0, which would emit+ // `s.value >= 0` and silently drop negative-valued scores.+ const project = await createOrgProjectAndApiKey();+ const negativeId = v4();+ const positiveId = v4();+ await createScoresCh([+ createTraceScore({+ id: negativeId,+ project_id: project.projectId,+ data_type: "NUMERIC",+ value: -1.5,+ }),+ createTraceScore({+ id: positiveId,+ project_id: project.projectId,+ data_type: "NUMERIC",+ value: 0.5,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?valueMin=&dataType=NUMERIC",+ undefined,+ project.auth,+ );+ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(negativeId);+ expect(ids).toContain(positiveId);+ });++ it("valueMax= (empty) with dataType=NUMERIC β 200, does not narrow to value<=0", async () => {+ const project = await createOrgProjectAndApiKey();+ const negativeId = v4();+ const positiveId = v4();+ await createScoresCh([+ createTraceScore({+ id: negativeId,+ project_id: project.projectId,+ data_type: "NUMERIC",+ value: -1.5,+ }),+ createTraceScore({+ id: positiveId,+ project_id: project.projectId,+ data_type: "NUMERIC",+ value: 0.5,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?valueMax=&dataType=NUMERIC",+ undefined,+ project.auth,+ );+ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(negativeId);+ expect(ids).toContain(positiveId);+ });++ it("environment filter returns only scores with matching environment", async () => {+ const scoreId = v4();+ const controlId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ environment: "staging",+ }),+ createTraceScore({+ id: controlId,+ project_id: projectId,+ environment: "production",+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?environment=staging`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(+ res.body.data.length > 0 &&+ res.body.data.every((s) => s.environment === "staging"),+ ).toBe(true);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(scoreId);+ expect(ids).not.toContain(controlId);+ });++ it("configId filter returns only scores with matching configId", async () => {+ const scoreId = v4();+ const controlId = v4();+ const configId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ config_id: configId,+ }),+ createTraceScore({ id: controlId, project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?configId=${configId}&fields=core,details`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(+ res.body.data.length > 0 &&+ res.body.data.every((s) => s.details?.configId === configId),+ ).toBe(true);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(scoreId);+ expect(ids).not.toContain(controlId);+ });++ it("queueId filter returns only scores with matching queueId", async () => {+ const scoreId = v4();+ const controlId = v4();+ const queueId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ queue_id: queueId,+ }),+ createTraceScore({ id: controlId, project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?queueId=${queueId}&fields=core,annotation`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(+ res.body.data.length > 0 &&+ res.body.data.every((s) => s.annotation?.queueId === queueId),+ ).toBe(true);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(scoreId);+ expect(ids).not.toContain(controlId);+ });++ it("authorUserId filter returns only scores with matching authorUserId", async () => {+ const scoreId = v4();+ const controlId = v4();+ const userId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ author_user_id: userId,+ }),+ createTraceScore({ id: controlId, project_id: projectId }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?authorUserId=${userId}&fields=core,annotation`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(+ res.body.data.length > 0 &&+ res.body.data.every((s) => s.annotation?.authorUserId === userId),+ ).toBe(true);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(scoreId);+ expect(ids).not.toContain(controlId);+ });++ it("toTimestamp excludes scores after the cutoff", async () => {+ const oldId = v4();+ const newId = v4();+ const cutoff = new Date("2025-01-01T00:00:00Z");+ await createScoresCh([+ createTraceScore({+ id: oldId,+ project_id: projectId,+ timestamp: new Date("2024-06-01T00:00:00Z").getTime(),+ }),+ createTraceScore({+ id: newId,+ project_id: projectId,+ timestamp: new Date("2025-06-01T00:00:00Z").getTime(),+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ `/api/public/v3/scores?fromTimestamp=2020-01-01&toTimestamp=${cutoff.toISOString()}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.data.some((s) => s.id === oldId)).toBe(true);+ expect(res.body.data.some((s) => s.id === newId)).toBe(false);+ });++ it("combines multiple filters with AND semantics", async () => {+ // Three scores: each matches one filter dimension, only one matches all+ // three. The AND-stacking in buildDynamicFilters' .join(" AND ") must+ // return exactly the all-three-match row.+ const matchId = v4();+ const onlyNameId = v4();+ const onlySourceId = v4();+ const onlyDataTypeId = v4();+ const sharedTs = new Date("2025-04-01T00:00:00Z").getTime();+ await createScoresCh([+ createTraceScore({+ id: matchId,+ project_id: projectId,+ name: "combo-name",+ source: "ANNOTATION",+ data_type: "CATEGORICAL",+ string_value: "x",+ value: 0,+ timestamp: sharedTs,+ }),+ createTraceScore({+ id: onlyNameId,+ project_id: projectId,+ name: "combo-name",+ source: "API",+ data_type: "NUMERIC",+ timestamp: sharedTs,+ }),+ createTraceScore({+ id: onlySourceId,+ project_id: projectId,+ name: "other-name",+ source: "ANNOTATION",+ data_type: "NUMERIC",+ timestamp: sharedTs,+ }),+ createTraceScore({+ id: onlyDataTypeId,+ project_id: projectId,+ name: "other-name",+ source: "API",+ data_type: "CATEGORICAL",+ string_value: "x",+ value: 0,+ timestamp: sharedTs,+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?name=combo-name&source=ANNOTATION&dataType=CATEGORICAL",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ const ids = res.body.data.map((s) => s.id);+ expect(ids).toContain(matchId);+ expect(ids).not.toContain(onlyNameId);+ expect(ids).not.toContain(onlySourceId);+ expect(ids).not.toContain(onlyDataTypeId);+ });++ it("empty fromTimestamp/toTimestamp query params are treated as absent β 200", async () => {+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?fromTimestamp=&toTimestamp=",+ undefined,+ auth,+ );+ expect(res.status).toBe(200);+ });++ it("empty userId/traceTags query params do not trigger the use-v2 400", async () => {+ // ?userId= (empty) and ?traceTags= should be treated as absent rather+ // than tripping the trace-JOIN-not-supported error.+ const res = await makeAPICall(+ "GET",+ "/api/public/v3/scores?userId=&traceTags=",+ undefined,+ auth,+ );+ expect(res.status).toBe(200);+ });++ it("regression: limit and fields still work alongside filters", async () => {+ const scoreId = v4();+ await createScoresCh([+ createTraceScore({+ id: scoreId,+ project_id: projectId,+ comment: "regression-check",+ }),+ ]);++ const res = await makeZodVerifiedAPICall(+ GetScoresResponseV3,+ "GET",+ "/api/public/v3/scores?limit=10&fields=core,details",+ undefined,+ auth,+ );++ expect(res.status).toBe(200);+ expect(res.body.meta.limit).toBe(10);+ const score = res.body.data.find((s) => s.id === scoreId);+ expect(score?.details?.comment).toBe("regression-check");+ });+ });});diff --git a/web/src/features/public-api/server/scores-api-v3.ts b/web/src/features/public-api/server/scores-api-v3.tsindex 50f8075c36..693bfabd70 100644--- a/web/src/features/public-api/server/scores-api-v3.ts+++ b/web/src/features/public-api/server/scores-api-v3.ts@@ -1,10 +1,15 @@import {convertClickhouseScoreToDomain,convertDateToClickhouseDateTime,+ DateTimeFilter,+ FilterList,logger,measureAndReturn,+ NumberFilter,parseClickhouseUTCDateTimeFormat,queryClickhouse,+ clickhouseCompliantRandomCharacters,+ StringOptionsFilter,type ScoreRecordReadType,} from "@langfuse/shared/src/server";import type {@@ -171,7 +176,208 @@ export const buildSelectColumns = (fields: ScoreFieldGroupV3[]): string => {return selected.join(",\n ");};-const buildV3ListQuery = (withCursor: boolean, fields: ScoreFieldGroupV3[]) => `+export function transformBooleanValueForFilter(v: "true" | "false"): number {+ // Belt-and-braces: the route-handler superRefine narrows v to "true"|"false"+ // before this is called, but a regression in that validator would otherwise+ // silently return 0 for any non-"true" input. Throw loud instead.+ if (v === "true") return 1;+ if (v === "false") return 0;+ throw new InternalServerError(+ `transformBooleanValueForFilter received unexpected value: ${v}`,+ );+}++type ListFilterParams = {+ id?: string[];+ name?: string[];+ source?: string[];+ dataType?: string[];+ environment?: string[];+ configId?: string[];+ queueId?: string[];+ authorUserId?: string[];+ value?: string[];+ valueMin?: number;+ valueMax?: number;+ traceId?: string[];+ sessionId?: string[];+ observationId?: string[];+ experimentId?: string[];+ fromTimestamp?: Date;+ toTimestamp?: Date;+};++function buildDynamicFilters(params: ListFilterParams): {+ query: string;+ params: Record<string, unknown>;+} {+ const filterList = new FilterList();++ // Positive union of the string-array filter keys. TypeScript errors if a+ // key is listed here that does not exist in ListFilterParams, catching drift+ // without a manual deny-list that has to grow alongside non-string filters.+ type StringOptionFilterKey = Extract<+ keyof ListFilterParams,+ | "id"+ | "name"+ | "source"+ | "dataType"+ | "environment"+ | "configId"+ | "queueId"+ | "authorUserId"+ | "traceId"+ | "sessionId"+ | "observationId"+ | "experimentId"+ >;++ // Each entry maps a ListFilterParams key to its ClickHouse column. Adding a+ // new identifier filter is a single row here β same operator/table shape.+ const STRING_OPTIONS_FILTERS: ReadonlyArray<{+ key: StringOptionFilterKey;+ field: string;+ }> = [+ { key: "id", field: "id" },+ { key: "name", field: "name" },+ { key: "source", field: "source" },+ { key: "dataType", field: "data_type" },+ { key: "environment", field: "environment" },+ { key: "configId", field: "config_id" },+ { key: "queueId", field: "queue_id" },+ { key: "authorUserId", field: "author_user_id" },+ { key: "traceId", field: "trace_id" },+ { key: "sessionId", field: "session_id" },+ { key: "observationId", field: "observation_id" },+ { key: "experimentId", field: "dataset_run_id" },+ ];++ for (const { key, field } of STRING_OPTIONS_FILTERS) {+ const values = params[key];+ if (values?.length) {+ filterList.push(+ new StringOptionsFilter({+ clickhouseTable: "scores",+ field,+ operator: "any of",+ values,+ tablePrefix: "s",+ }),+ );+ }+ }+ if (params.fromTimestamp !== undefined)+ filterList.push(+ new DateTimeFilter({+ clickhouseTable: "scores",+ field: "timestamp",+ operator: ">=",+ value: params.fromTimestamp,+ tablePrefix: "s",+ }),+ );+ if (params.toTimestamp !== undefined)+ filterList.push(+ new DateTimeFilter({+ clickhouseTable: "scores",+ field: "timestamp",+ operator: "<",+ value: params.toTimestamp,+ tablePrefix: "s",+ }),+ );+ if (params.valueMin !== undefined)+ filterList.push(+ new NumberFilter({+ clickhouseTable: "scores",+ field: "value",+ operator: ">=",+ value: params.valueMin,+ tablePrefix: "s",+ clickhouseTypeOverwrite: "Float64",+ }),+ );+ if (params.valueMax !== undefined)+ filterList.push(+ new NumberFilter({+ clickhouseTable: "scores",+ field: "value",+ operator: "<=",+ value: params.valueMax,+ tablePrefix: "s",+ clickhouseTypeOverwrite: "Float64",+ }),+ );++ const compiled = filterList.apply();++ // value= routes to different columns depending on dataType+ const extraClauses: string[] = [];+ const extraParams: Record<string, unknown> = {};++ if (params.value?.length && params.dataType?.length === 1) {+ // Cast: handler superRefine validates dt is a ScoreDataTypeType member.+ const dt = params.dataType[0] as ScoreDataTypeType;+ const uid = clickhouseCompliantRandomCharacters();+ const varName = `valueFilter${uid}`;++ switch (dt) {+ case ScoreDataTypeEnum.NUMERIC: {+ extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);+ // Belt-and-braces: the route-handler superRefine asserts each value is+ // a finite number before this is called. Re-validate so a regression+ // can't land NaN/Infinity directly in a CH IN-clause parameter.+ extraParams[varName] = params.value.map((v) => {+ const n = Number(v);+ if (!Number.isFinite(n)) {+ throw new InternalServerError(+ `NUMERIC value filter received non-finite value: ${v}`,+ );+ }+ return n;+ });+ break;+ }+ case ScoreDataTypeEnum.BOOLEAN: {+ extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);+ extraParams[varName] = params.value.map((v) =>+ transformBooleanValueForFilter(v as "true" | "false"),+ );+ break;+ }+ case ScoreDataTypeEnum.CATEGORICAL: {+ extraClauses.push(`s.string_value IN ({${varName}: Array(String)})`);+ extraParams[varName] = params.value;+ break;+ }+ case ScoreDataTypeEnum.TEXT:+ case ScoreDataTypeEnum.CORRECTION:+ // Handler superRefine rejects value= with TEXT/CORRECTION; reaching+ // this branch means the validator regressed.+ throw new InternalServerError(+ `value filter with dataType=${dt} should have been rejected by handler validation`,+ );+ default: {+ const _exhaustiveCheck: never = dt;+ throw new InternalServerError(+ `value filter received unknown dataType: ${_exhaustiveCheck as string}`,+ );+ }+ }+ }++ const allClauses = [compiled.query, ...extraClauses]+ .filter(Boolean)+ .join(" AND ");++ return { query: allClauses, params: { ...compiled.params, ...extraParams } };+}++const buildV3ListQuery = (+ withCursor: boolean,+ fields: ScoreFieldGroupV3[],+ filterClause: string,+) => `SELECT${buildSelectColumns(fields)}FROM scores s@@ -181,17 +387,23 @@ const buildV3ListQuery = (withCursor: boolean, fields: ScoreFieldGroupV3[]) => `? "AND (s.timestamp, s.id) < ({lastTimestamp: DateTime64(3)}, {lastId: String})": ""}+ ${filterClause ? `AND ${filterClause}` : ""}ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESCLIMIT 1 BY s.id, s.project_idLIMIT {limit: Int32}`;-export async function listScoresV3ForPublicApi(params: {- projectId: string;- limit: number;- cursor?: ScoresCursorV3Type;- fields: ScoreFieldGroupV3[];-}): Promise<{ data: APIScoreV3[]; cursor?: string }> {+export async function listScoresV3ForPublicApi(+ params: {+ projectId: string;+ limit: number;+ cursor?: ScoresCursorV3Type;+ fields: ScoreFieldGroupV3[];+ } & ListFilterParams,+): Promise<{ data: APIScoreV3[]; cursor?: string }> {+ const { query: filterClause, params: filterParams } =+ buildDynamicFilters(params);+return measureAndReturn({operationName: "listScoresV3ForPublicApi",projectId: params.projectId,@@ -205,6 +417,7 @@ export async function listScoresV3ForPublicApi(params: {),lastId: params.cursor.lastId,}),+ ...filterParams,},tags: {feature: "scoring",@@ -215,7 +428,11 @@ export async function listScoresV3ForPublicApi(params: {},fn: async (input) => {const records = await queryClickhouse<ScoreRecordReadType>({- query: buildV3ListQuery(Boolean(params.cursor), params.fields),+ query: buildV3ListQuery(+ Boolean(params.cursor),+ params.fields,+ filterClause,+ ),params: input.params,tags: input.tags,preferredClickhouseService: "ReadOnly",diff --git a/web/src/pages/api/public/v3/scores/index.ts b/web/src/pages/api/public/v3/scores/index.tsindex 4f73e4b3ab..70c9328cfd 100644--- a/web/src/pages/api/public/v3/scores/index.ts+++ b/web/src/pages/api/public/v3/scores/index.ts@@ -11,6 +11,94 @@ import { env } from "@/src/env.mjs";const GetScoresV3Query = GetScoresQueryV3.extend({cursor: EncodedScoresCursorV3.optional(),+}).superRefine((data, ctx) => {+ if (data.userId !== undefined) {+ ctx.addIssue({+ code: "custom",+ message:+ "userId filter requires a trace JOIN and is not supported in v3 β use v2 or omit this filter",+ });+ }+ if (data.traceTags !== undefined) {+ ctx.addIssue({+ code: "custom",+ message:+ "traceTags filter requires a trace JOIN and is not supported in v3 β use v2 or omit this filter",+ });+ }+ if (data.value !== undefined && data.value.length > 0) {+ if (!data.dataType || data.dataType.length !== 1) {+ ctx.addIssue({+ code: "custom",+ message:+ "value filter requires a single dataType from: NUMERIC, BOOLEAN, CATEGORICAL",+ });+ } else {+ const dt = data.dataType[0];+ if (!["NUMERIC", "BOOLEAN", "CATEGORICAL"].includes(dt)) {+ ctx.addIssue({+ code: "custom",+ message: `value filter requires dataType to be NUMERIC, BOOLEAN, or CATEGORICAL (got "${dt}")`,+ });+ } else if (dt === "NUMERIC") {+ for (const v of data.value) {+ if (!isFinite(Number(v))) {+ ctx.addIssue({+ code: "custom",+ message: `value filter with dataType=NUMERIC requires each value to be a finite number (got "${v}")`,+ });+ }+ }+ } else if (dt === "BOOLEAN") {+ for (const v of data.value) {+ if (v !== "true" && v !== "false") {+ ctx.addIssue({+ code: "custom",+ message: `value filter with dataType=BOOLEAN requires each value to be "true" or "false" (got "${v}")`,+ });+ }+ }+ }+ }+ }+ if (data.valueMin !== undefined || data.valueMax !== undefined) {+ if (+ !data.dataType ||+ data.dataType.length !== 1 ||+ data.dataType[0] !== "NUMERIC"+ ) {+ ctx.addIssue({+ code: "custom",+ message:+ "valueMin and valueMax require dataType=NUMERIC as a single value",+ });+ }+ }+ const hasTraceId = (data.traceId?.length ?? 0) > 0;+ const hasObservationId = (data.observationId?.length ?? 0) > 0;++ if (hasObservationId && !hasTraceId) {+ ctx.addIssue({+ code: "custom",+ message:+ "observationId filter requires traceId β observation IDs are scoped to a trace",+ });+ }++ // traceId, sessionId, experimentId remain mutually exclusive with each other.+ // observationId is allowed alongside traceId (enforced above).+ const exclusiveEntityFilters = [+ data.traceId,+ data.sessionId,+ data.experimentId,+ ].filter((arr) => arr && arr.length > 0);+ if (exclusiveEntityFilters.length > 1) {+ ctx.addIssue({+ code: "custom",+ message:+ "At most one of traceId, sessionId, experimentId may be specified",+ });+ }});export default withMiddlewares({@@ -20,8 +108,10 @@ export default withMiddlewares({responseSchema: GetScoresResponseV3,fn: async ({ query, auth }) => {if (env.LANGFUSE_ENABLE_SCORES_V3_API !== "true") {- // Generic message to avoid disclosing the feature-flag existence to- // unauthenticated probes. Cloud has the flag on; self-hosted gets 404.+ // Returns 404 to authenticated callers when disabled. Note: auth and+ // Zod parsing already ran, so an unauthenticated caller sees 401 here+ // (signalling the endpoint exists). Cloud has the flag on by default;+ // self-hosted instances see 404 until the API graduates from preview.throw new LangfuseNotFoundError("Not Found");}@@ -30,6 +120,23 @@ export default withMiddlewares({limit: query.limit,cursor: query.cursor,fields: query.fields,+ id: query.id,+ name: query.name,+ source: query.source,+ dataType: query.dataType,+ environment: query.environment,+ configId: query.configId,+ queueId: query.queueId,+ authorUserId: query.authorUserId,+ value: query.value,+ valueMin: query.valueMin,+ valueMax: query.valueMax,+ traceId: query.traceId,+ sessionId: query.sessionId,+ observationId: query.observationId,+ experimentId: query.experimentId,+ fromTimestamp: query.fromTimestamp,+ toTimestamp: query.toTimestamp,});return {