Skip to content

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

feat(scores): add cursor pagination to v3 scores API (Phase 2) (#13996)

Niklas Semmler36e2085cf5fb
diff --git a/fern/apis/server/_drafts/scores-v3.yml b/fern/apis/server/_drafts/scores-v3.yml
index 99f994becf..c7b20c1371 100644
--- a/fern/apis/server/_drafts/scores-v3.yml
+++ b/fern/apis/server/_drafts/scores-v3.yml
@@ -25,6 +25,9 @@ service:
limit:
type: optional<integer>
docs: Number of items per page. Maximum 100, default 50. Requests with a limit greater than 100 return HTTP 400.
+ 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.
response: GetScoresV3Response
types:
@@ -98,6 +101,9 @@ types:
GetScoresV3Meta:
properties:
limit: integer
+ cursor:
+ type: optional<string>
+ docs: URL-safe base64 (base64url) cursor for the next page. Absent when there are no more results.
GetScoresV3Response:
properties:
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 e3209fc37c..fcd3a35b9a 100644
--- a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
@@ -10,5 +10,6 @@ export const GetScoresResponseV3 = z.object({
data: z.array(APIScoreSchemaV3),
meta: z.object({
limit: z.number(),
+ cursor: z.string().optional(),
}),
});
diff --git a/web/src/__tests__/server/scores-api-v3.servertest.ts b/web/src/__tests__/server/scores-api-v3.servertest.ts
index 642af3ada0..e322bd30ae 100644
--- a/web/src/__tests__/server/scores-api-v3.servertest.ts
+++ b/web/src/__tests__/server/scores-api-v3.servertest.ts
@@ -149,4 +149,219 @@ describe("/api/public/v3/scores API Endpoint", () => {
expect(leaked).toBeUndefined();
});
});
+
+ describe("GET /api/public/v3/scores — cursor pagination", () => {
+ let auth: string;
+ let projectId: string;
+
+ beforeAll(async () => {
+ const project = await createOrgProjectAndApiKey();
+ auth = project.auth;
+ projectId = project.projectId;
+ });
+
+ it("returns cursor when more pages exist and no cursor on last page", async () => {
+ const scores = Array.from({ length: 3 }, () =>
+ createTraceScore({ project_id: projectId }),
+ );
+ await createScoresCh(scores);
+
+ // page 1: limit=2, expect cursor
+ const page1 = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?limit=2",
+ undefined,
+ auth,
+ );
+ expect(page1.status).toBe(200);
+ expect(page1.body.data.length).toBe(2);
+ expect(page1.body.meta.limit).toBe(2);
+ expect(page1.body.meta.cursor).toBeDefined();
+
+ // page 2: use cursor, should return remaining and no cursor
+ const page2 = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?limit=2&cursor=${page1.body.meta.cursor}`,
+ undefined,
+ auth,
+ );
+ expect(page2.status).toBe(200);
+ expect(page2.body.data.length).toBe(1);
+ expect(page2.body.meta.cursor).toBeUndefined();
+ });
+
+ it("paginates without duplicates or skips", async () => {
+ const project = await createOrgProjectAndApiKey();
+ const count = 7;
+ const scores = Array.from({ length: count }, () =>
+ createTraceScore({ project_id: project.projectId }),
+ );
+ await createScoresCh(scores);
+ const scoreIds = new Set(scores.map((s) => s.id));
+
+ const seenIds = new Set<string>();
+ let cursor: string | undefined;
+
+ do {
+ const url = cursor
+ ? `/api/public/v3/scores?limit=3&cursor=${cursor}`
+ : "/api/public/v3/scores?limit=3";
+ 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);
+ }
+ cursor = res.body.meta.cursor;
+ } while (cursor);
+
+ // all inserted scores must appear exactly once
+ for (const id of scoreIds) {
+ expect(seenIds.has(id)).toBe(true);
+ }
+ });
+
+ it("invalid cursor → 400", async () => {
+ const res = await makeAPICall(
+ "GET",
+ "/api/public/v3/scores?cursor=not-valid-base64!!",
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("valid base64url but wrong JSON shape cursor → 400", async () => {
+ const badShapeCursor = Buffer.from(
+ JSON.stringify({ foo: "bar" }),
+ ).toString("base64url");
+ const res = await makeAPICall(
+ "GET",
+ `/api/public/v3/scores?cursor=${badShapeCursor}`,
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("stale cursor (no matching rows) returns empty page with no cursor", async () => {
+ const staleCursor = Buffer.from(
+ JSON.stringify({
+ lastTimestamp: new Date(0).toISOString(),
+ lastId: "00000000-0000-0000-0000-000000000000",
+ }),
+ ).toString("base64url");
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?cursor=${staleCursor}`,
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.data.length).toBe(0);
+ expect(res.body.meta.cursor).toBeUndefined();
+ });
+
+ it("cross-tenant cursor replay returns empty page for project B", async () => {
+ const projectA = await createOrgProjectAndApiKey();
+ const scoresA = Array.from({ length: 3 }, () =>
+ createTraceScore({ project_id: projectA.projectId }),
+ );
+ await createScoresCh(scoresA);
+
+ const page1A = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?limit=2",
+ undefined,
+ projectA.auth,
+ );
+ expect(page1A.body.meta.cursor).toBeDefined();
+ const cursorFromA = page1A.body.meta.cursor!;
+
+ const projectB = await createOrgProjectAndApiKey();
+ const scoresB = Array.from({ length: 3 }, () =>
+ createTraceScore({ project_id: projectB.projectId }),
+ );
+ await createScoresCh(scoresB);
+
+ const replayRes = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?limit=2&cursor=${cursorFromA}`,
+ undefined,
+ projectB.auth,
+ );
+ expect(replayRes.status).toBe(200);
+ const leakedIds = new Set(scoresA.map((s) => s.id));
+ for (const s of replayRes.body.data) {
+ expect(leakedIds.has(s.id)).toBe(false);
+ }
+ });
+
+ it("exact-page-boundary: N rows with limit=N returns no cursor", async () => {
+ const project = await createOrgProjectAndApiKey();
+ const n = 3;
+ const scores = Array.from({ length: n }, () =>
+ createTraceScore({ project_id: project.projectId }),
+ );
+ await createScoresCh(scores);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ `/api/public/v3/scores?limit=${n}`,
+ undefined,
+ project.auth,
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.data.length).toBe(n);
+ expect(res.body.meta.cursor).toBeUndefined();
+ });
+
+ it("limit=1 paginates one score at a time", async () => {
+ const project = await createOrgProjectAndApiKey();
+ const scores = Array.from({ length: 3 }, () =>
+ createTraceScore({ project_id: project.projectId }),
+ );
+ await createScoresCh(scores);
+ const scoreIds = new Set(scores.map((s) => s.id));
+
+ const seenIds = new Set<string>();
+ let cursor: string | undefined;
+
+ do {
+ const url = cursor
+ ? `/api/public/v3/scores?limit=1&cursor=${cursor}`
+ : "/api/public/v3/scores?limit=1";
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ url,
+ undefined,
+ project.auth,
+ );
+ expect(res.status).toBe(200);
+ expect(res.body.data.length).toBe(1);
+ const id = res.body.data[0].id;
+ expect(seenIds.has(id)).toBe(false);
+ seenIds.add(id);
+ cursor = res.body.meta.cursor;
+ } while (cursor);
+
+ for (const id of scoreIds) {
+ expect(seenIds.has(id)).toBe(true);
+ }
+ });
+ });
});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index f6ab607a82..c55c2e7927 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -812,7 +812,7 @@ export const env = createEnv({
SLACK_CLIENT_SECRET: process.env.SLACK_CLIENT_SECRET,
SLACK_STATE_SECRET: process.env.SLACK_STATE_SECRET,
- // AWS Bedrock for Langfuse native AI features
+ // AWS Bedrock for langfuse native AI feature such as natural language filters
LANGFUSE_AWS_BEDROCK_MODEL: process.env.LANGFUSE_AWS_BEDROCK_MODEL,
// Langfuse Tracing AI Features
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 79d1c154c0..d3de8ce8fe 100644
--- a/web/src/features/public-api/server/scores-api-v3.ts
+++ b/web/src/features/public-api/server/scores-api-v3.ts
@@ -1,7 +1,9 @@
import {
convertClickhouseScoreToDomain,
+ convertDateToClickhouseDateTime,
logger,
measureAndReturn,
+ parseClickhouseUTCDateTimeFormat,
queryClickhouse,
type ScoreRecordReadType,
} from "@langfuse/shared/src/server";
@@ -15,6 +17,10 @@ import {
InternalServerError,
ScoreDataTypeEnum,
} from "@langfuse/shared";
+import {
+ encodeCursorV3,
+ type ScoresCursorV3Type,
+} from "@/src/features/public-api/types/scores";
export function polymorphicValue(score: {
dataType: ScoreDataTypeType;
@@ -73,7 +79,7 @@ function domainToV3(score: ScoreDomain): APIScoreV3 {
} as APIScoreV3;
}
-const v3ListQuery = `
+const buildV3ListQuery = (withCursor: boolean) => `
SELECT
s.id as id,
s.project_id as project_id,
@@ -99,6 +105,11 @@ const v3ListQuery = `
s.dataset_run_id as dataset_run_id
FROM scores s
WHERE s.project_id = {projectId: String}
+ ${
+ withCursor
+ ? "AND (s.timestamp, s.id) < ({lastTimestamp: DateTime64(3)}, {lastId: String})"
+ : ""
+ }
ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
LIMIT {limit: Int32}
@@ -107,12 +118,22 @@ const v3ListQuery = `
export async function listScoresV3ForPublicApi(params: {
projectId: string;
limit: number;
-}): Promise<APIScoreV3[]> {
+ cursor?: ScoresCursorV3Type;
+}): Promise<{ data: APIScoreV3[]; cursor?: string }> {
return measureAndReturn({
operationName: "listScoresV3ForPublicApi",
projectId: params.projectId,
input: {
- params: { projectId: params.projectId, limit: params.limit },
+ params: {
+ projectId: params.projectId,
+ limit: params.limit + 1,
+ ...(params.cursor && {
+ lastTimestamp: convertDateToClickhouseDateTime(
+ params.cursor.lastTimestamp,
+ ),
+ lastId: params.cursor.lastId,
+ }),
+ },
tags: {
feature: "scoring",
type: "score",
@@ -122,17 +143,32 @@ export async function listScoresV3ForPublicApi(params: {
},
fn: async (input) => {
const records = await queryClickhouse<ScoreRecordReadType>({
- query: v3ListQuery,
+ query: buildV3ListQuery(Boolean(params.cursor)),
params: input.params,
tags: input.tags,
preferredClickhouseService: "ReadOnly",
});
+
+ const hasMore = records.length > params.limit;
+ const pageRecords = hasMore ? records.slice(0, params.limit) : records;
+
+ let nextCursor: string | undefined;
+ if (hasMore && pageRecords.length > 0) {
+ const last = pageRecords[pageRecords.length - 1];
+ nextCursor = encodeCursorV3({
+ lastTimestamp: parseClickhouseUTCDateTimeFormat(
+ String(last.timestamp),
+ ),
+ lastId: last.id,
+ });
+ }
+
// 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.
const items: ReturnType<typeof domainToV3>[] = [];
- for (const row of records) {
+ for (const row of pageRecords) {
try {
items.push(domainToV3(convertClickhouseScoreToDomain(row)));
} catch (error) {
@@ -143,12 +179,15 @@ export async function listScoresV3ForPublicApi(params: {
});
}
}
- return filterAndValidateV3GetScoreList(items, (error) => {
- logger.error("v3 score row dropped from response", {
- issues: error.issues,
- projectId: params.projectId,
- });
- });
+ return {
+ data: filterAndValidateV3GetScoreList(items, (error) => {
+ logger.error("v3 score row dropped from response", {
+ issues: error.issues,
+ projectId: params.projectId,
+ });
+ }),
+ cursor: nextCursor,
+ };
},
});
}
diff --git a/web/src/features/public-api/types/scores.ts b/web/src/features/public-api/types/scores.ts
new file mode 100644
index 0000000000..b1352657f6
--- /dev/null
+++ b/web/src/features/public-api/types/scores.ts
@@ -0,0 +1,28 @@
+import { z } from "zod";
+import { InvalidRequestError } from "@langfuse/shared";
+
+export const ScoresCursorV3 = z.object({
+ lastTimestamp: z.coerce.date(),
+ lastId: z.string(),
+});
+export type ScoresCursorV3Type = z.infer<typeof ScoresCursorV3>;
+
+export const EncodedScoresCursorV3 = z
+ .string()
+ .transform((val) => {
+ try {
+ const decoded = Buffer.from(val, "base64url").toString("utf-8");
+ return JSON.parse(decoded);
+ } catch (_e) {
+ throw new InvalidRequestError("Invalid cursor format");
+ }
+ })
+ .pipe(ScoresCursorV3);
+
+export const encodeCursorV3 = (cursor: ScoresCursorV3Type): string =>
+ Buffer.from(
+ JSON.stringify({
+ lastTimestamp: cursor.lastTimestamp.toISOString(),
+ lastId: cursor.lastId,
+ }),
+ ).toString("base64url");
diff --git a/web/src/pages/api/public/v3/scores/index.ts b/web/src/pages/api/public/v3/scores/index.ts
index af94c45b53..f7887155b8 100644
--- a/web/src/pages/api/public/v3/scores/index.ts
+++ b/web/src/pages/api/public/v3/scores/index.ts
@@ -6,12 +6,17 @@ import {
LangfuseNotFoundError,
} from "@langfuse/shared";
import { listScoresV3ForPublicApi } from "@/src/features/public-api/server/scores-api-v3";
+import { EncodedScoresCursorV3 } from "@/src/features/public-api/types/scores";
import { env } from "@/src/env.mjs";
+const GetScoresV3Query = GetScoresQueryV3.extend({
+ cursor: EncodedScoresCursorV3.optional(),
+});
+
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
name: "Get Scores V3",
- querySchema: GetScoresQueryV3,
+ querySchema: GetScoresV3Query,
responseSchema: GetScoresResponseV3,
fn: async ({ query, auth }) => {
if (env.LANGFUSE_ENABLE_SCORES_V3_API !== "true") {
@@ -20,15 +25,17 @@ export default withMiddlewares({
throw new LangfuseNotFoundError("Not Found");
}
- const items = await listScoresV3ForPublicApi({
+ const result = await listScoresV3ForPublicApi({
projectId: auth.scope.projectId,
limit: query.limit,
+ cursor: query.cursor,
});
return {
- data: items,
+ data: result.data,
meta: {
limit: query.limit,
+ ...(result.cursor ? { cursor: result.cursor } : {}),
},
};
},