Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(scores): add field groups to v3 scores API (Phase 3) (#14001)

Niklas Semmlerfae4acd8f021
diff --git a/fern/apis/server/_drafts/scores-v3.yml b/fern/apis/server/_drafts/scores-v3.yml
index c7b20c1371..1c87cde88e 100644
--- a/fern/apis/server/_drafts/scores-v3.yml
+++ b/fern/apis/server/_drafts/scores-v3.yml
@@ -15,6 +15,9 @@ service:
- `BOOLEAN` β†’ boolean
- `CATEGORICAL`, `TEXT`, `CORRECTION` β†’ string
+ Use the `fields` parameter to include optional field groups beyond the
+ default `core`. Unknown group names return HTTP 400.
+
Currently in preview for Langfuse Cloud v4 users; not yet available on
self-hosted Langfuse.
method: GET
@@ -28,9 +31,81 @@ service:
cursor:
type: optional<string>
docs: URL-safe base64 (base64url) cursor for pagination. Use the cursor from the previous response to get the next page. Absent on the final page.
+ fields:
+ type: optional<string>
+ docs: >
+ Comma-separated field groups to include. Allowed: core, details,
+ subject, annotation. Defaults to "core". Unknown names return HTTP 400.
response: GetScoresV3Response
types:
+ ScoreDetailsV3:
+ docs: Returned when fields includes "details".
+ properties:
+ comment:
+ type: nullable<string>
+ docs: Optional comment attached to the score.
+ configId:
+ type: nullable<string>
+ docs: The score config ID, if this score was created from a config.
+ metadata:
+ type: map<string, unknown>
+ docs: Arbitrary metadata attached to the score.
+
+ ScoreSubjectTraceV3:
+ properties:
+ id:
+ type: string
+ docs: The trace ID.
+
+ ScoreSubjectObservationV3:
+ properties:
+ id:
+ type: string
+ docs: The observation ID.
+ traceId:
+ type: optional<string>
+ docs: The parent trace ID, if available.
+
+ ScoreSubjectSessionV3:
+ properties:
+ id:
+ type: string
+ docs: The session ID.
+
+ ScoreSubjectExperimentV3:
+ properties:
+ id:
+ type: string
+ docs: The dataset run ID (experiment ID).
+
+ ScoreSubjectV3:
+ docs: Returned when fields includes "subject".
+ discriminant: kind
+ union:
+ trace:
+ type: ScoreSubjectTraceV3
+ docs: Subject is a trace-level score.
+ observation:
+ type: ScoreSubjectObservationV3
+ docs: Subject is an observation-level score scoped to a trace.
+ session:
+ type: ScoreSubjectSessionV3
+ docs: Subject is a session-level score.
+ experiment:
+ type: ScoreSubjectExperimentV3
+ docs: Subject is a dataset run (experiment) score.
+
+ ScoreAnnotationV3:
+ docs: Returned when fields includes "annotation".
+ properties:
+ authorUserId:
+ type: nullable<string>
+ docs: The user who created this score, if available.
+ queueId:
+ type: nullable<string>
+ docs: The annotation queue this score belongs to, if any.
+
BaseScoreV3:
properties:
id: string
@@ -43,6 +118,15 @@ types:
docs: The environment from which this score originated.
createdAt: datetime
updatedAt: datetime
+ details:
+ type: optional<ScoreDetailsV3>
+ docs: Present when "details" is included in the fields parameter.
+ subject:
+ type: optional<ScoreSubjectV3>
+ docs: Present when "subject" is included in the fields parameter.
+ annotation:
+ type: optional<ScoreAnnotationV3>
+ docs: Present when "annotation" is included in the fields parameter.
NumericScoreV3:
extends: BaseScoreV3
diff --git a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
index fcd3a35b9a..53b5cd29ad 100644
--- a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
@@ -1,9 +1,24 @@
import { z } from "zod";
import { APIScoreSchemaV3 } from "./schemas";
+export const SCORE_FIELD_GROUPS_V3 = [
+ "core",
+ "details",
+ "subject",
+ "annotation",
+] as const;
+export type ScoreFieldGroupV3 = (typeof SCORE_FIELD_GROUPS_V3)[number];
+
+const fieldsParam = z
+ .string()
+ .optional()
+ .transform((val) => (val ? val.split(",").map((g) => g.trim()) : ["core"]))
+ .pipe(z.array(z.enum(SCORE_FIELD_GROUPS_V3)));
+
// GET /v3/scores
export const GetScoresQueryV3 = z.object({
limit: z.coerce.number().int().positive().max(100).default(50),
+ fields: fieldsParam,
});
export const GetScoresResponseV3 = z.object({
diff --git a/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts
index 63a4e0bee3..f0892743b5 100644
--- a/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts
@@ -1,6 +1,41 @@
import { z } from "zod";
import { ScoreSourceDomain } from "../../../../../domain/scores";
+// Optional group schemas
+export const ScoreDetailsV3 = z.object({
+ comment: z.string().nullable(),
+ configId: z.string().nullable(),
+ metadata: z.record(z.string(), z.unknown()),
+});
+
+// Discriminated on `kind` so the type system enforces that `traceId` is
+// only ever present on the observation arm β€” matches the Fern union and
+// the deriveSubject runtime contract.
+export const ScoreSubjectV3 = z.discriminatedUnion("kind", [
+ z.object({
+ kind: z.literal("trace"),
+ id: z.string(),
+ }),
+ z.object({
+ kind: z.literal("observation"),
+ id: z.string(),
+ traceId: z.string().optional(),
+ }),
+ z.object({
+ kind: z.literal("session"),
+ id: z.string(),
+ }),
+ z.object({
+ kind: z.literal("experiment"),
+ id: z.string(),
+ }),
+]);
+
+export const ScoreAnnotationV3 = z.object({
+ authorUserId: z.string().nullable(),
+ queueId: z.string().nullable(),
+});
+
/**
* Foundation schema for scores API v3.
*
@@ -19,6 +54,10 @@ const ScoreFoundationSchemaV3 = z.object({
environment: z.string(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
+ // optional groups
+ details: ScoreDetailsV3.optional(),
+ subject: ScoreSubjectV3.optional(),
+ annotation: ScoreAnnotationV3.optional(),
});
export const APIScoreSchemaV3 = z.discriminatedUnion("dataType", [
diff --git a/web/src/__tests__/server/scores-api-v3.servertest.ts b/web/src/__tests__/server/scores-api-v3.servertest.ts
index e322bd30ae..f3354924f5 100644
--- a/web/src/__tests__/server/scores-api-v3.servertest.ts
+++ b/web/src/__tests__/server/scores-api-v3.servertest.ts
@@ -1,5 +1,7 @@
import {
createTraceScore,
+ createSessionScore,
+ createDatasetRunScore,
createScoresCh,
createOrgProjectAndApiKey,
} from "@langfuse/shared/src/server";
@@ -60,75 +62,171 @@ describe("/api/public/v3/scores API Endpoint", () => {
expect(res.body.data.length).toBeLessThanOrEqual(2);
});
- it.each([101, 0, -1, "abc"])("limit=%s β†’ 400", async (limit) => {
+ it("limit=101 β†’ 400", async () => {
const res = await makeAPICall(
"GET",
- `/api/public/v3/scores?limit=${limit}`,
+ "/api/public/v3/scores?limit=101",
undefined,
auth,
);
expect(res.status).toBe(400);
});
- it.each([
- ["NUMERIC", { value: 0.75, data_type: "NUMERIC" as const }, 0.75],
- [
- "BOOLEAN",
- { value: 1, string_value: "true", data_type: "BOOLEAN" as const },
- true,
- ],
- [
- "CATEGORICAL",
- {
+ it("limit=0 β†’ 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?limit=0",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("limit=-1 β†’ 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?limit=-1",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("limit=abc β†’ 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?limit=abc",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("NUMERIC score has numeric value", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ value: 0.75,
+ data_type: "NUMERIC",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe(0.75);
+ expect(typeof score!.value).toBe("number");
+ });
+
+ it("BOOLEAN score has boolean value", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ value: 1,
+ string_value: "true",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe(true);
+ expect(typeof score!.value).toBe("boolean");
+ });
+
+ it("CATEGORICAL score has string value", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
value: 0,
string_value: "excellent",
- data_type: "CATEGORICAL" as const,
- },
- "excellent",
- ],
- [
- "TEXT",
- {
- value: 0,
- string_value: "Very detailed feedback",
- data_type: "TEXT" as const,
- },
- "Very detailed feedback",
- ],
- [
- "CORRECTION",
- {
+ data_type: "CATEGORICAL",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe("excellent");
+ });
+
+ it("CORRECTION score has string value from longStringValue", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
value: 0,
long_string_value: "This is the corrected output",
- data_type: "CORRECTION" as const,
- },
- "This is the corrected output",
- ],
- ])(
- "%s score has correct polymorphic value",
- async (_dataType, scoreFields, expected) => {
- const scoreId = v4();
- await createScoresCh([
- createTraceScore({
- id: scoreId,
- project_id: projectId,
- ...scoreFields,
- }),
- ]);
+ data_type: "CORRECTION",
+ }),
+ ]);
- const res = await makeZodVerifiedAPICall(
- GetScoresResponseV3,
- "GET",
- "/api/public/v3/scores",
- undefined,
- auth,
- );
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe("This is the corrected output");
+ });
+
+ it("TEXT score has string value", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ value: 0,
+ string_value: "Very detailed feedback",
+ data_type: "TEXT",
+ }),
+ ]);
- const score = res.body.data.find((s) => s.id === scoreId);
- expect(score).toBeDefined();
- expect(score!.value).toBe(expected);
- },
- );
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe("Very detailed feedback");
+ });
it("tenant isolation: project A cannot see project B scores", async () => {
const projectB = await createOrgProjectAndApiKey();
@@ -175,7 +273,7 @@ describe("/api/public/v3/scores API Endpoint", () => {
auth,
);
expect(page1.status).toBe(200);
- expect(page1.body.data.length).toBe(2);
+ expect(page1.body.data.length).toBeGreaterThanOrEqual(2);
expect(page1.body.meta.limit).toBe(2);
expect(page1.body.meta.cursor).toBeDefined();
@@ -188,7 +286,7 @@ describe("/api/public/v3/scores API Endpoint", () => {
auth,
);
expect(page2.status).toBe(200);
- expect(page2.body.data.length).toBe(1);
+ expect(page2.body.data.length).toBeGreaterThanOrEqual(1);
expect(page2.body.meta.cursor).toBeUndefined();
});
@@ -329,6 +427,45 @@ describe("/api/public/v3/scores API Endpoint", () => {
expect(res.body.meta.cursor).toBeUndefined();
});
+ it("paginates with fields=details preserved across pages", async () => {
+ const project = await createOrgProjectAndApiKey();
+ const count = 3;
+ const scores = Array.from({ length: count }, (_, i) =>
+ createTraceScore({
+ project_id: project.projectId,
+ comment: `c${i}`,
+ metadata: { idx: String(i) },
+ }),
+ );
+ await createScoresCh(scores);
+
+ const seenIds = new Set<string>();
+ let cursor: string | undefined;
+
+ do {
+ const url = cursor
+ ? `/api/public/v3/scores?limit=2&fields=core,details&cursor=${cursor}`
+ : "/api/public/v3/scores?limit=2&fields=core,details";
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ url,
+ undefined,
+ project.auth,
+ );
+ expect(res.status).toBe(200);
+ for (const s of res.body.data) {
+ expect(seenIds.has(s.id)).toBe(false);
+ seenIds.add(s.id);
+ expect(s.details).toBeDefined();
+ expect(s.details!.comment).toMatch(/^c\d$/);
+ }
+ cursor = res.body.meta.cursor;
+ } while (cursor);
+
+ expect(seenIds.size).toBe(count);
+ });
+
it("limit=1 paginates one score at a time", async () => {
const project = await createOrgProjectAndApiKey();
const scores = Array.from({ length: 3 }, () =>
@@ -364,4 +501,299 @@ describe("/api/public/v3/scores API Endpoint", () => {
}
});
});
+
+ describe("GET /api/public/v3/scores β€” field groups", () => {
+ let auth: string;
+ let projectId: string;
+
+ beforeAll(async () => {
+ const project = await createOrgProjectAndApiKey();
+ auth = project.auth;
+ projectId = project.projectId;
+ });
+
+ it("fields omitted β†’ only core keys present", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ comment: "some comment",
+ config_id: "cfg-1",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score).not.toHaveProperty("details");
+ expect(score).not.toHaveProperty("subject");
+ expect(score).not.toHaveProperty("annotation");
+ });
+
+ it("fields=core,details β†’ details present", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ comment: "test comment",
+ config_id: "cfg-abc",
+ metadata: { key: "val" },
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,details",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.details).toBeDefined();
+ expect(score!.details!.comment).toBe("test comment");
+ expect(score!.details!.configId).toBe("cfg-abc");
+ expect(score).not.toHaveProperty("subject");
+ expect(score).not.toHaveProperty("annotation");
+ });
+
+ it("fields=core,annotation β†’ annotation present", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ author_user_id: "user-xyz",
+ queue_id: "queue-abc",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,annotation",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.annotation).toBeDefined();
+ expect(score!.annotation!.authorUserId).toBe("user-xyz");
+ expect(score!.annotation!.queueId).toBe("queue-abc");
+ expect(score).not.toHaveProperty("details");
+ expect(score).not.toHaveProperty("subject");
+ });
+
+ it("fields=core,annotation on a non-annotation source yields null fields", async () => {
+ const scoreId = v4();
+ // createTraceScore defaults source to "API"; author_user_id and queue_id
+ // are left at their column defaults so the annotation group should be
+ // present but with null fields (matching the Fern doc contract).
+ await createScoresCh([
+ createTraceScore({ id: scoreId, project_id: projectId }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,annotation",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.annotation).toBeDefined();
+ expect(score!.annotation!.authorUserId).toBeNull();
+ expect(score!.annotation!.queueId).toBeNull();
+ });
+
+ it("fields=core,subject β†’ trace score has kind=trace", async () => {
+ const scoreId = v4();
+ const traceId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,subject",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.subject).toBeDefined();
+ expect(score!.subject!.kind).toBe("trace");
+ expect(score!.subject!.id).toBe(traceId);
+ expect(score!.subject).not.toHaveProperty("traceId");
+ });
+
+ it("fields=core,subject β†’ session score has kind=session", async () => {
+ const scoreId = v4();
+ const sessionId = v4();
+ await createScoresCh([
+ createSessionScore({
+ id: scoreId,
+ project_id: projectId,
+ session_id: sessionId,
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,subject",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.subject!.kind).toBe("session");
+ expect(score!.subject!.id).toBe(sessionId);
+ });
+
+ it("fields=core,subject β†’ dataset run score has kind=experiment", async () => {
+ const scoreId = v4();
+ const datasetRunId = v4();
+ await createScoresCh([
+ createDatasetRunScore({
+ id: scoreId,
+ project_id: projectId,
+ dataset_run_id: datasetRunId,
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,subject",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.subject!.kind).toBe("experiment");
+ expect(score!.subject!.id).toBe(datasetRunId);
+ });
+
+ it("fields=core,subject β†’ observation score has kind=observation with traceId", async () => {
+ const scoreId = v4();
+ const observationId = v4();
+ const traceId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ observation_id: observationId,
+ trace_id: traceId,
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?fields=core,subject",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.subject!.kind).toBe("observation");
+ expect(score!.subject!.id).toBe(observationId);
+ expect(score!.subject).toHaveProperty("traceId", traceId);
+ });
+
+ it("fields=core,unknown β†’ 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?fields=core,unknown",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("fields=trace β†’ 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?fields=trace",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("fields=core passed explicitly behaves same as omitted", async () => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({ id: scoreId, project_id: projectId }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?fields=core`,
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score).not.toHaveProperty("details");
+ expect(score).not.toHaveProperty("subject");
+ expect(score).not.toHaveProperty("annotation");
+ });
+
+ it("fields=core,details,subject,annotation β†’ all groups present simultaneously", async () => {
+ const scoreId = v4();
+ const traceId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ source: "ANNOTATION",
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?fields=core,details,subject,annotation`,
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score).toHaveProperty("details");
+ expect(score).toHaveProperty("subject");
+ expect(score).toHaveProperty("annotation");
+ expect(score!.subject!.kind).toBe("trace");
+ expect(score!.subject!.id).toBe(traceId);
+ });
+ });
});
diff --git a/web/src/__tests__/server/unit/scores-api-v3.servertest.ts b/web/src/__tests__/server/unit/scores-api-v3.servertest.ts
new file mode 100644
index 0000000000..77f113f2ef
--- /dev/null
+++ b/web/src/__tests__/server/unit/scores-api-v3.servertest.ts
@@ -0,0 +1,73 @@
+import { buildSelectColumns } from "@/src/features/public-api/server/scores-api-v3";
+
+describe("buildSelectColumns", () => {
+ it("core always selects the polymorphic value columns", () => {
+ const sql = buildSelectColumns(["core"]);
+ expect(sql).toContain("s.value as value");
+ expect(sql).toContain("s.string_value as string_value");
+ expect(sql).toContain("s.long_string_value as long_string_value");
+ expect(sql).toContain("s.data_type as data_type");
+ });
+
+ it("core does not select group columns", () => {
+ const sql = buildSelectColumns(["core"]);
+ expect(sql).not.toContain("s.comment");
+ expect(sql).not.toContain("s.metadata");
+ expect(sql).not.toContain("s.config_id");
+ expect(sql).not.toContain("s.trace_id");
+ expect(sql).not.toContain("s.observation_id");
+ expect(sql).not.toContain("s.session_id");
+ expect(sql).not.toContain("s.dataset_run_id");
+ expect(sql).not.toContain("s.author_user_id");
+ expect(sql).not.toContain("s.queue_id");
+ });
+
+ it("details adds comment/metadata/config_id only", () => {
+ const sql = buildSelectColumns(["core", "details"]);
+ expect(sql).toContain("s.comment as comment");
+ expect(sql).toContain("s.metadata as metadata");
+ expect(sql).toContain("s.config_id as config_id");
+ expect(sql).not.toContain("s.trace_id");
+ expect(sql).not.toContain("s.author_user_id");
+ });
+
+ it("subject adds the four entity-id columns only", () => {
+ const sql = buildSelectColumns(["core", "subject"]);
+ expect(sql).toContain("s.trace_id as trace_id");
+ expect(sql).toContain("s.observation_id as observation_id");
+ expect(sql).toContain("s.session_id as session_id");
+ expect(sql).toContain("s.dataset_run_id as dataset_run_id");
+ expect(sql).not.toContain("s.comment");
+ expect(sql).not.toContain("s.author_user_id");
+ });
+
+ it("annotation adds author/queue only", () => {
+ const sql = buildSelectColumns(["core", "annotation"]);
+ expect(sql).toContain("s.author_user_id as author_user_id");
+ expect(sql).toContain("s.queue_id as queue_id");
+ expect(sql).not.toContain("s.comment");
+ expect(sql).not.toContain("s.trace_id");
+ });
+
+ it("all groups select every column", () => {
+ const sql = buildSelectColumns([
+ "core",
+ "details",
+ "subject",
+ "annotation",
+ ]);
+ for (const col of [
+ "s.comment",
+ "s.metadata",
+ "s.config_id",
+ "s.trace_id",
+ "s.observation_id",
+ "s.session_id",
+ "s.dataset_run_id",
+ "s.author_user_id",
+ "s.queue_id",
+ ]) {
+ expect(sql).toContain(col);
+ }
+ });
+});
diff --git a/web/src/features/public-api/server/scores-api-v3.ts b/web/src/features/public-api/server/scores-api-v3.ts
index d3de8ce8fe..50f8075c36 100644
--- a/web/src/features/public-api/server/scores-api-v3.ts
+++ b/web/src/features/public-api/server/scores-api-v3.ts
@@ -11,6 +11,7 @@ import type {
APIScoreV3,
ScoreDataTypeType,
ScoreDomain,
+ ScoreFieldGroupV3,
} from "@langfuse/shared";
import {
filterAndValidateV3GetScoreList,
@@ -57,7 +58,36 @@ export function polymorphicValue(score: {
}
}
-function domainToV3(score: ScoreDomain): APIScoreV3 {
+function deriveSubject(
+ score: ScoreDomain,
+):
+ | { kind: "observation"; id: string; traceId?: string }
+ | { kind: "trace" | "session" | "experiment"; id: string } {
+ if (score.datasetRunId) {
+ return { kind: "experiment", id: score.datasetRunId };
+ }
+ if (score.observationId) {
+ return {
+ kind: "observation",
+ id: score.observationId,
+ ...(score.traceId ? { traceId: score.traceId } : {}),
+ };
+ }
+ if (score.sessionId) {
+ return { kind: "session", id: score.sessionId };
+ }
+ if (!score.traceId) {
+ throw new InternalServerError(
+ `Score ${score.id} has kind=trace but missing traceId`,
+ );
+ }
+ return { kind: "trace", id: score.traceId };
+}
+
+function domainToV3(
+ score: ScoreDomain,
+ fields: ScoreFieldGroupV3[],
+): APIScoreV3 {
// ScoreDomain is a flat type so TypeScript cannot verify that dataType and
// value are a valid discriminated pair; polymorphicValue guarantees it at runtime.
return {
@@ -76,33 +106,74 @@ function domainToV3(score: ScoreDomain): APIScoreV3 {
environment: score.environment,
createdAt: score.createdAt,
updatedAt: score.updatedAt,
+ ...(fields.includes("details")
+ ? {
+ details: {
+ comment: score.comment,
+ configId: score.configId,
+ metadata: score.metadata,
+ },
+ }
+ : {}),
+ ...(fields.includes("subject") ? { subject: deriveSubject(score) } : {}),
+ ...(fields.includes("annotation")
+ ? {
+ annotation: {
+ authorUserId: score.authorUserId,
+ queueId: score.queueId,
+ },
+ }
+ : {}),
} as APIScoreV3;
}
-const buildV3ListQuery = (withCursor: boolean) => `
+// Always-selected columns map to the core APIScoreV3 fields plus the cursor
+// and bookkeeping columns. Optional groups (details/subject/annotation) are
+// only selected when their `fields` group is requested β€” ClickHouse is
+// columnar, so skipping unused columns avoids real I/O cost on large rows
+// (notably `metadata` and `long_string_value`).
+const CORE_COLUMNS = [
+ "s.id as id",
+ "s.project_id as project_id",
+ "s.timestamp as timestamp",
+ "s.environment as environment",
+ "s.name as name",
+ "s.value as value",
+ "s.string_value as string_value",
+ "s.long_string_value as long_string_value",
+ "s.source as source",
+ "s.data_type as data_type",
+ "s.created_at as created_at",
+ "s.updated_at as updated_at",
+ "s.execution_trace_id as execution_trace_id",
+];
+const DETAILS_COLUMNS = [
+ "s.comment as comment",
+ "s.metadata as metadata",
+ "s.config_id as config_id",
+];
+const SUBJECT_COLUMNS = [
+ "s.trace_id as trace_id",
+ "s.observation_id as observation_id",
+ "s.session_id as session_id",
+ "s.dataset_run_id as dataset_run_id",
+];
+const ANNOTATION_COLUMNS = [
+ "s.author_user_id as author_user_id",
+ "s.queue_id as queue_id",
+];
+
+export const buildSelectColumns = (fields: ScoreFieldGroupV3[]): string => {
+ const selected = [...CORE_COLUMNS];
+ if (fields.includes("details")) selected.push(...DETAILS_COLUMNS);
+ if (fields.includes("subject")) selected.push(...SUBJECT_COLUMNS);
+ if (fields.includes("annotation")) selected.push(...ANNOTATION_COLUMNS);
+ return selected.join(",\n ");
+};
+
+const buildV3ListQuery = (withCursor: boolean, fields: ScoreFieldGroupV3[]) => `
SELECT
- s.id as id,
- s.project_id as project_id,
- s.timestamp as timestamp,
- s.environment as environment,
- s.name as name,
- s.value as value,
- s.string_value as string_value,
- s.long_string_value as long_string_value,
- s.author_user_id as author_user_id,
- s.created_at as created_at,
- s.updated_at as updated_at,
- s.source as source,
- s.comment as comment,
- s.metadata as metadata,
- s.data_type as data_type,
- s.config_id as config_id,
- s.queue_id as queue_id,
- s.execution_trace_id as execution_trace_id,
- s.trace_id as trace_id,
- s.observation_id as observation_id,
- s.session_id as session_id,
- s.dataset_run_id as dataset_run_id
+ ${buildSelectColumns(fields)}
FROM scores s
WHERE s.project_id = {projectId: String}
${
@@ -119,6 +190,7 @@ export async function listScoresV3ForPublicApi(params: {
projectId: string;
limit: number;
cursor?: ScoresCursorV3Type;
+ fields: ScoreFieldGroupV3[];
}): Promise<{ data: APIScoreV3[]; cursor?: string }> {
return measureAndReturn({
operationName: "listScoresV3ForPublicApi",
@@ -143,7 +215,7 @@ export async function listScoresV3ForPublicApi(params: {
},
fn: async (input) => {
const records = await queryClickhouse<ScoreRecordReadType>({
- query: buildV3ListQuery(Boolean(params.cursor)),
+ query: buildV3ListQuery(Boolean(params.cursor), params.fields),
params: input.params,
tags: input.tags,
preferredClickhouseService: "ReadOnly",
@@ -165,14 +237,17 @@ export async function listScoresV3ForPublicApi(params: {
// Log+drop bad rows rather than 500ing the whole page β€” domainToV3 can
// throw (e.g. polymorphicValue's stringValue / longStringValue guards
- // for malformed CATEGORICAL / TEXT / CORRECTION rows). Mirrors the
- // row-level graceful-drop semantics of filterAndValidateV3GetScoreList.
+ // for malformed CATEGORICAL / TEXT / CORRECTION rows, or deriveSubject
+ // for a malformed subject record). Mirrors the row-level graceful-drop
+ // semantics of filterAndValidateV3GetScoreList.
const items: ReturnType<typeof domainToV3>[] = [];
for (const row of pageRecords) {
try {
- items.push(domainToV3(convertClickhouseScoreToDomain(row)));
+ items.push(
+ domainToV3(convertClickhouseScoreToDomain(row), params.fields),
+ );
} catch (error) {
- logger.error("v3 score row dropped from response", {
+ logger.error("v3 score row dropped from response: conversion error", {
error,
scoreId: row.id,
projectId: params.projectId,
@@ -181,10 +256,13 @@ export async function listScoresV3ForPublicApi(params: {
}
return {
data: filterAndValidateV3GetScoreList(items, (error) => {
- logger.error("v3 score row dropped from response", {
- issues: error.issues,
- projectId: params.projectId,
- });
+ logger.error(
+ "v3 score row dropped from response: schema validation error",
+ {
+ issues: error.issues,
+ projectId: params.projectId,
+ },
+ );
}),
cursor: nextCursor,
};
diff --git a/web/src/pages/api/public/v3/scores/index.ts b/web/src/pages/api/public/v3/scores/index.ts
index f7887155b8..4f73e4b3ab 100644
--- a/web/src/pages/api/public/v3/scores/index.ts
+++ b/web/src/pages/api/public/v3/scores/index.ts
@@ -29,6 +29,7 @@ export default withMiddlewares({
projectId: auth.scope.projectId,
limit: query.limit,
cursor: query.cursor,
+ fields: query.fields,
});
return {