Skip to content

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

feat(v4): add SDK usage timeline (#14741)

Max Deichmann8624bbf82b06
diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.test.ts b/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
index f2c2aaa73f..9716d4bf71 100644
--- a/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
+++ b/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import type { AuthHeaderValidVerificationResult } from "../auth/types";
import {
+ classifyIngestionSdkVersion,
createIngestionAttribution,
createUnknownSdkIngestionAttribution,
UNKNOWN_INGESTION_SDK_VALUE,
@@ -64,4 +65,84 @@ describe("ingestion attribution", () => {
ingestionSdkVersion: UNKNOWN_INGESTION_SDK_VALUE,
});
});
+
+ it.each([
+ {
+ sdkName: "python",
+ sdkVersion: "3.9.0",
+ expected: {
+ canonicalSdkName: "python",
+ latestMajor: 4,
+ major: 3,
+ status: "outdated_major",
+ },
+ },
+ {
+ sdkName: "langfuse-python",
+ sdkVersion: "4.0.0b1",
+ expected: {
+ canonicalSdkName: "python",
+ latestMajor: 4,
+ major: 4,
+ status: "current",
+ },
+ },
+ {
+ sdkName: "javascript",
+ sdkVersion: "4.6.0",
+ expected: {
+ canonicalSdkName: "javascript",
+ latestMajor: 5,
+ major: 4,
+ status: "outdated_major",
+ },
+ },
+ {
+ sdkName: "@langfuse/tracing",
+ sdkVersion: "5.1.2-rc.1",
+ expected: {
+ canonicalSdkName: "javascript",
+ latestMajor: 5,
+ major: 5,
+ status: "current",
+ },
+ },
+ {
+ sdkName: "unknown",
+ sdkVersion: "unknown",
+ expected: {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unknown",
+ },
+ },
+ {
+ sdkName: "ruby",
+ sdkVersion: "1.0.0",
+ expected: {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unsupported_sdk",
+ },
+ },
+ {
+ sdkName: "python",
+ sdkVersion: "not-a-version",
+ expected: {
+ canonicalSdkName: "python",
+ latestMajor: 4,
+ major: null,
+ status: "invalid_version",
+ },
+ },
+ ])(
+ "classifies $sdkName@$sdkVersion SDK upgrade status",
+ ({ sdkName, sdkVersion, expected }) => {
+ expect(classifyIngestionSdkVersion({ sdkName, sdkVersion })).toEqual(
+ expected,
+ );
+ },
+ );
});
diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.ts b/packages/shared/src/server/ingestion/ingestionAttribution.ts
index 073feaa0c6..54c97d7ce9 100644
--- a/packages/shared/src/server/ingestion/ingestionAttribution.ts
+++ b/packages/shared/src/server/ingestion/ingestionAttribution.ts
@@ -1,4 +1,5 @@
import type { AuthHeaderValidVerificationResult } from "../auth/types";
+import { parseVersionString } from "../utils/compareVersions";
type HeaderValue = string | string[] | undefined;
export type IngestionHeaderMap = Record<string, HeaderValue>;
@@ -11,6 +12,27 @@ export type IngestionAttribution = {
export const UNKNOWN_INGESTION_SDK_VALUE = "unknown";
+export const LANGFUSE_SDK_LATEST_MAJOR = {
+ python: 4,
+ javascript: 5,
+} as const;
+
+export type IngestionSdkCanonicalName = keyof typeof LANGFUSE_SDK_LATEST_MAJOR;
+
+export type IngestionSdkUpgradeStatus =
+ | "current"
+ | "outdated_major"
+ | "unknown"
+ | "unsupported_sdk"
+ | "invalid_version";
+
+export type IngestionSdkVersionClassification = {
+ canonicalSdkName: IngestionSdkCanonicalName | null;
+ latestMajor: number | null;
+ major: number | null;
+ status: IngestionSdkUpgradeStatus;
+};
+
const getHeaderValue = (
headers: IngestionHeaderMap | undefined,
name: string,
@@ -31,6 +53,111 @@ const normalizeSdkValue = (value: string | undefined): string =>
export const getLangfuseHeaderValue = getHeaderValue;
+export const normalizeIngestionSdkName = (
+ sdkName: string | null | undefined,
+): IngestionSdkCanonicalName | null => {
+ const normalized = sdkName?.trim().toLowerCase();
+
+ if (!normalized || normalized === UNKNOWN_INGESTION_SDK_VALUE) {
+ return null;
+ }
+
+ if (normalized === "python" || normalized === "langfuse-python") {
+ return "python";
+ }
+
+ if (
+ [
+ "javascript",
+ "js",
+ "typescript",
+ "ts",
+ "langfuse-js",
+ "langfuse-ts",
+ "@langfuse/client",
+ "@langfuse/browser",
+ "@langfuse/core",
+ "@langfuse/langchain",
+ "@langfuse/otel",
+ "@langfuse/openai",
+ "@langfuse/tracing",
+ "@langfuse/vercel-ai-sdk",
+ ].includes(normalized)
+ ) {
+ return "javascript";
+ }
+
+ return null;
+};
+
+export const extractBaseIngestionSdkVersion = (sdkVersion: string): string => {
+ const version = sdkVersion.trim();
+
+ if (/^v?\d+\.\d+\.\d+(?:[-+].+)?$/i.test(version)) {
+ return version.split(/[-+]/)[0] ?? version;
+ }
+
+ const pep440Match = version.match(/^(v?\d+\.\d+\.\d+)(?:a|b|rc)\d+$/i);
+ if (pep440Match?.[1]) {
+ return pep440Match[1];
+ }
+
+ return version;
+};
+
+export const classifyIngestionSdkVersion = (params: {
+ sdkName: string | null | undefined;
+ sdkVersion: string | null | undefined;
+}): IngestionSdkVersionClassification => {
+ const sdkName = params.sdkName?.trim();
+ const sdkVersion = params.sdkVersion?.trim();
+
+ if (
+ !sdkName ||
+ !sdkVersion ||
+ sdkName === UNKNOWN_INGESTION_SDK_VALUE ||
+ sdkVersion === UNKNOWN_INGESTION_SDK_VALUE
+ ) {
+ return {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unknown",
+ };
+ }
+
+ const canonicalSdkName = normalizeIngestionSdkName(sdkName);
+ if (!canonicalSdkName) {
+ return {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unsupported_sdk",
+ };
+ }
+
+ const parsedVersion = parseVersionString(
+ extractBaseIngestionSdkVersion(sdkVersion),
+ );
+ const latestMajor = LANGFUSE_SDK_LATEST_MAJOR[canonicalSdkName];
+
+ if (!parsedVersion) {
+ return {
+ canonicalSdkName,
+ latestMajor,
+ major: null,
+ status: "invalid_version",
+ };
+ }
+
+ return {
+ canonicalSdkName,
+ latestMajor,
+ major: parsedVersion.major,
+ status: parsedVersion.major >= latestMajor ? "current" : "outdated_major",
+ };
+};
+
export const createIngestionAttribution = (params: {
headers?: IngestionHeaderMap;
authCheck: AuthHeaderValidVerificationResult;
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
index 363b0a862d..f71b402457 100644
--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
@@ -1,20 +1,109 @@
import type { Session } from "next-auth";
-import type * as SharedServer from "@langfuse/shared/src/server";
import type { PrismaClient } from "@langfuse/shared/src/db";
import { v4TransitionRouter } from "@/src/features/v4/server/v4TransitionRouter";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { queryClickhouse } from "@langfuse/shared/src/server";
-vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
- const actual = await importOriginal<typeof SharedServer>();
+vi.mock("@/src/server/auth", () => ({
+ getServerAuthSession: vi.fn(),
+}));
+
+const sharedServerMock = vi.hoisted(() => ({
+ queryClickhouse: vi.fn(),
+ convertDateToClickhouseDateTime: (date: Date) =>
+ date.toISOString().replace("T", " ").replace("Z", ""),
+ systemTableRef: (table: "system.processes" | "system.query_log") =>
+ `clusterAllReplicas('test-cluster', '${table}')`,
+ classifyIngestionSdkVersion: ({
+ sdkName,
+ sdkVersion,
+ }: {
+ sdkName: string | null | undefined;
+ sdkVersion: string | null | undefined;
+ }) => {
+ const normalizedSdkName = sdkName?.trim().toLowerCase();
+ const normalizedSdkVersion = sdkVersion?.trim();
+
+ if (
+ !normalizedSdkName ||
+ !normalizedSdkVersion ||
+ normalizedSdkName === "unknown" ||
+ normalizedSdkVersion === "unknown"
+ ) {
+ return {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unknown",
+ };
+ }
+
+ const canonicalSdkName =
+ normalizedSdkName === "python" || normalizedSdkName === "langfuse-python"
+ ? "python"
+ : normalizedSdkName === "javascript" ||
+ normalizedSdkName.startsWith("@langfuse/")
+ ? "javascript"
+ : null;
+
+ if (!canonicalSdkName) {
+ return {
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ status: "unsupported_sdk",
+ };
+ }
+
+ const major = Number(normalizedSdkVersion.match(/^v?(\d+)/)?.[1]);
+ const latestMajor = canonicalSdkName === "python" ? 4 : 5;
+
+ if (!Number.isFinite(major)) {
+ return {
+ canonicalSdkName,
+ latestMajor,
+ major: null,
+ status: "invalid_version",
+ };
+ }
+
+ return {
+ canonicalSdkName,
+ latestMajor,
+ major,
+ status: major >= latestMajor ? "current" : "outdated_major",
+ };
+ },
+}));
+
+vi.mock("@langfuse/shared/src/server", async () => {
+ const { ROOT_CONTEXT } = await import("@opentelemetry/api");
return {
- ...actual,
- queryClickhouse: vi.fn(),
- systemTableRef: vi.fn(
- (table: "system.processes" | "system.query_log") =>
- `clusterAllReplicas('test-cluster', '${table}')`,
- ),
+ ...sharedServerMock,
+ getTraceById: vi.fn(),
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ redis: {
+ status: "end",
+ disconnect: vi.fn(),
+ },
+ ClickHouseClientManager: {
+ getInstance: () => ({
+ closeAllConnections: vi.fn(),
+ }),
+ },
+ addUserToSpan: vi.fn(),
+ contextWithLangfuseProps: () => ROOT_CONTEXT,
+ ClickHouseResourceError: class ClickHouseResourceError extends Error {
+ static ERROR_ADVICE_MESSAGE = "ClickHouse resource limit exceeded.";
+ errorType = "unknown";
+ tags = {};
+ },
};
});
@@ -34,6 +123,8 @@ const createCaller = (
});
type OrganizationRole = Session["user"]["organizations"][number]["role"];
+type ProjectRole =
+ Session["user"]["organizations"][number]["projects"][number]["role"];
const createSessionWithOrgRole = (role: OrganizationRole): Session => ({
...session,
@@ -46,6 +137,20 @@ const createSessionWithOrgRole = (role: OrganizationRole): Session => ({
},
});
+const createSessionWithProjectRole = (role: ProjectRole): Session => ({
+ ...session,
+ user: {
+ ...session.user,
+ organizations: session.user.organizations.map((organization) => ({
+ ...organization,
+ projects: organization.projects.map((project) => ({
+ ...project,
+ role,
+ })),
+ })),
+ },
+});
+
const session: Session = {
expires: "1",
user: {
@@ -437,6 +542,15 @@ describe("v4TransitionRouter", () => {
}),
).rejects.toThrow("30 days");
+ await expect(
+ caller.sdkUsageTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-05-25T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toThrow("30 days");
+
expect(mockedQueryClickhouse).not.toHaveBeenCalled();
expect(mockPrisma.$queryRaw).not.toHaveBeenCalled();
});
@@ -698,6 +812,16 @@ describe("v4TransitionRouter", () => {
orgId,
}),
).resolves.toEqual([]);
+ await expect(
+ createCaller(
+ mockPrisma,
+ createSessionWithOrgRole("OWNER"),
+ ).sdkUsageSummaryByProject({
+ orgId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ }),
+ ).resolves.toEqual([]);
await expect(
createCaller(
@@ -715,6 +839,16 @@ describe("v4TransitionRouter", () => {
orgId,
}),
).resolves.toEqual([]);
+ await expect(
+ createCaller(
+ mockPrisma,
+ createSessionWithOrgRole("ADMIN"),
+ ).sdkUsageSummaryByProject({
+ orgId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ }),
+ ).resolves.toEqual([]);
});
it("forbids organization members from accessing org-level v4 data", async () => {
@@ -746,6 +880,15 @@ describe("v4TransitionRouter", () => {
).rejects.toMatchObject({
code: "FORBIDDEN",
});
+ await expect(
+ caller.sdkUsageSummaryByProject({
+ orgId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
});
it("queries trace-level eval execution counts with the same 2 minute buckets as the legacy API timeline", async () => {
@@ -864,6 +1007,328 @@ describe("v4TransitionRouter", () => {
expect(query?.values?.[0]).toBe("1 hour");
});
+ it("queries SDK usage by exact SDK, version, and API key across event and score ingestion", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-25T12:00:00Z",
+ sdkName: "python",
+ sdkVersion: "3.9.0",
+ publicKey: "pk-lf-old-python",
+ count: "3",
+ firstSeen: "2026-06-25T12:01:00Z",
+ lastSeen: "2026-06-25T12:03:00Z",
+ },
+ {
+ time: "2026-06-25T12:04:00Z",
+ sdkName: "@langfuse/tracing",
+ sdkVersion: "5.1.0",
+ publicKey: "pk-lf-js-current",
+ count: 7,
+ firstSeen: "2026-06-25T12:04:00Z",
+ lastSeen: "2026-06-25T12:05:00Z",
+ },
+ ]);
+ const caller = createCaller();
+
+ const result = await caller.sdkUsageTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T13:00:00Z"),
+ granularity: "auto",
+ });
+ const rows = result.rows;
+
+ expect(result.bucketTimes).toHaveLength(30);
+ expect(result.bucketTimes[0]).toBe("2026-06-25T12:00:00Z");
+ expect(result.bucketTimes.at(-1)).toBe("2026-06-25T12:58:00Z");
+ expect(rows).toHaveLength(2);
+ expect(
+ rows.find(
+ (row) =>
+ row.time === "2026-06-25T12:00:00Z" &&
+ row.sdkName === "python" &&
+ row.sdkVersion === "3.9.0" &&
+ row.publicKey === "pk-lf-old-python",
+ ),
+ ).toEqual({
+ time: "2026-06-25T12:00:00Z",
+ sdkName: "python",
+ sdkVersion: "3.9.0",
+ publicKey: "pk-lf-old-python",
+ count: 3,
+ firstSeen: "2026-06-25T12:01:00Z",
+ lastSeen: "2026-06-25T12:03:00Z",
+ canonicalSdkName: "python",
+ latestMajor: 4,
+ major: 3,
+ upgradeStatus: "outdated_major",
+ });
+ expect(
+ rows.find(
+ (row) =>
+ row.time === "2026-06-25T12:04:00Z" &&
+ row.sdkName === "@langfuse/tracing" &&
+ row.sdkVersion === "5.1.0" &&
+ row.publicKey === "pk-lf-js-current",
+ ),
+ ).toEqual({
+ time: "2026-06-25T12:04:00Z",
+ sdkName: "@langfuse/tracing",
+ sdkVersion: "5.1.0",
+ publicKey: "pk-lf-js-current",
+ count: 7,
+ firstSeen: "2026-06-25T12:04:00Z",
+ lastSeen: "2026-06-25T12:05:00Z",
+ canonicalSdkName: "javascript",
+ latestMajor: 5,
+ major: 5,
+ upgradeStatus: "current",
+ });
+ expect(
+ rows.find(
+ (row) =>
+ row.time === "2026-06-25T12:02:00Z" &&
+ row.sdkName === "python" &&
+ row.sdkVersion === "3.9.0" &&
+ row.publicKey === "pk-lf-old-python",
+ ),
+ ).toBeUndefined();
+
+ expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain("FROM events_core");
+ expect(clickhouseQuery?.query).toContain("UNION ALL");
+ expect(clickhouseQuery?.query).toContain("FROM scores FINAL");
+ expect(
+ clickhouseQuery?.query.match(/project_id = \{projectId: String\}/g),
+ ).toHaveLength(2);
+ expect(clickhouseQuery?.query).not.toContain("system.columns");
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time, INTERVAL 2 MINUTE, 'UTC')",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "if(ingestion_sdk_name = '', 'unknown', ingestion_sdk_name) AS sdk_name",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "if(ingestion_sdk_version = '', 'unknown', ingestion_sdk_version) AS sdk_version",
+ );
+ expect(clickhouseQuery?.query).toContain("ingestion_api_key AS public_key");
+ expect(clickhouseQuery?.query).toContain(
+ "GROUP BY toStartOfInterval(event_time, INTERVAL 2 MINUTE, 'UTC'), sdk_name, sdk_version, public_key",
+ );
+ expect(clickhouseQuery?.params).toMatchObject({
+ projectId,
+ fromTimestamp: "2026-06-25 12:00:00.000",
+ toTimestamp: "2026-06-25 13:00:00.000",
+ });
+ expect(clickhouseQuery?.tags).toEqual({
+ projectId,
+ route: "v4-sdk-usage-timeseries",
+ });
+ expect(clickhouseQuery?.preferredClickhouseService).toBe("EventsReadOnly");
+ });
+
+ it("forbids project members and viewers from accessing project-level v4 data", async () => {
+ const mockPrisma = {
+ posthogIntegration: {
+ findUnique: vi.fn(),
+ },
+ mixpanelIntegration: {
+ findUnique: vi.fn(),
+ },
+ blobStorageIntegration: {
+ findUnique: vi.fn(),
+ },
+ jobConfiguration: {
+ count: vi.fn(),
+ },
+ $queryRaw: vi.fn(),
+ };
+
+ for (const role of ["MEMBER", "VIEWER"] as const) {
+ const caller = createCaller(
+ mockPrisma,
+ createSessionWithProjectRole(role),
+ );
+
+ await expect(caller.summary({ projectId })).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ await expect(
+ caller.traceLevelEvalSummary({ projectId }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ await expect(
+ caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T13:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ await expect(
+ caller.traceLevelEvalExecutionsTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T13:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ await expect(
+ caller.sdkUsageTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T13:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ });
+ }
+
+ expect(mockedQueryClickhouse).not.toHaveBeenCalled();
+ expect(mockPrisma.posthogIntegration.findUnique).not.toHaveBeenCalled();
+ expect(mockPrisma.mixpanelIntegration.findUnique).not.toHaveBeenCalled();
+ expect(mockPrisma.blobStorageIntegration.findUnique).not.toHaveBeenCalled();
+ expect(mockPrisma.jobConfiguration.count).not.toHaveBeenCalled();
+ expect(mockPrisma.$queryRaw).not.toHaveBeenCalled();
+ });
+
+ it("queries SDK usage without a ClickHouse metadata preflight", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ time: "2026-06-25T12:00:00Z",
+ sdkName: "python",
+ sdkVersion: "4.0.0",
+ publicKey: "pk-lf-python",
+ count: 2,
+ firstSeen: "2026-06-25T12:00:00Z",
+ lastSeen: "2026-06-25T12:01:00Z",
+ },
+ ]);
+ const caller = createCaller();
+
+ const result = await caller.sdkUsageTimeSeries({
+ projectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T12:10:00Z"),
+ granularity: "auto",
+ });
+
+ expect(result.bucketTimes).toHaveLength(10);
+ expect(result.rows).toHaveLength(1);
+ expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
+ const usageQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(usageQuery?.query).toContain("FROM events_core");
+ expect(usageQuery?.query).toContain("FROM scores FINAL");
+ expect(usageQuery?.query).toContain("UNION ALL");
+ expect(
+ usageQuery?.query.match(/project_id = \{projectId: String\}/g),
+ ).toHaveLength(2);
+ expect(usageQuery?.query).not.toContain("system.columns");
+ });
+
+ it("rejects SDK usage requests for projects outside the caller session", async () => {
+ const caller = createCaller();
+
+ await expect(
+ caller.sdkUsageTimeSeries({
+ projectId: secondProjectId,
+ fromTimestamp: new Date("2026-06-25T12:00:00Z"),
+ toTimestamp: new Date("2026-06-25T13:00:00Z"),
+ granularity: "auto",
+ }),
+ ).rejects.toThrow("User is not a member of this project");
+
+ expect(mockedQueryClickhouse).not.toHaveBeenCalled();
+ });
+
+ it("summarizes outdated SDK usage series by organization project", async () => {
+ mockedQueryClickhouse.mockResolvedValueOnce([
+ {
+ projectId,
+ sdkName: "python",
+ sdkVersion: "3.9.0",
+ publicKey: "pk-lf-old-python",
+ count: "8",
+ },
+ {
+ projectId,
+ sdkName: "python",
+ sdkVersion: "4.0.0",
+ publicKey: "pk-lf-current-python",
+ count: "13",
+ },
+ {
+ projectId: secondProjectId,
+ sdkName: "@langfuse/tracing",
+ sdkVersion: "4.2.0",
+ publicKey: "pk-lf-old-js",
+ count: "5",
+ },
+ ]);
+ const mockPrisma = {
+ project: {
+ findMany: vi
+ .fn()
+ .mockResolvedValue([{ id: projectId }, { id: secondProjectId }]),
+ },
+ };
+ const caller = createCaller(mockPrisma);
+
+ const rows = await caller.sdkUsageSummaryByProject({
+ orgId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ });
+
+ expect(rows).toEqual([
+ {
+ projectId,
+ outdatedSdkUsageSeriesCount: 1,
+ },
+ {
+ projectId: secondProjectId,
+ outdatedSdkUsageSeriesCount: 1,
+ },
+ ]);
+
+ expect(mockPrisma.project.findMany).toHaveBeenCalledWith({
+ where: {
+ orgId,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ });
+ expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
+ const usageQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(usageQuery?.query).toContain("FROM events_core");
+ expect(usageQuery?.query).toContain("UNION ALL");
+ expect(usageQuery?.query).toContain("FROM scores FINAL");
+ expect(usageQuery?.query).not.toContain("system.columns");
+ expect(
+ usageQuery?.query.match(/project_id IN \{projectIds: Array\(String\)\}/g),
+ ).toHaveLength(2);
+ expect(usageQuery?.query).toContain(
+ "GROUP BY project_id, sdk_name, sdk_version, public_key",
+ );
+ expect(usageQuery?.params).toMatchObject({
+ projectIds: [projectId, secondProjectId],
+ fromTimestamp: "2026-06-24 00:00:00.000",
+ toTimestamp: "2026-06-25 00:00:00.000",
+ });
+ expect(usageQuery?.tags).toEqual({
+ route: "v4-org-sdk-usage-summary",
+ });
+ });
+
it("summarizes legacy public API usage by organization project", async () => {
mockedQueryClickhouse.mockResolvedValue([
{
diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.ts
index c0390cd342..933ab3b9e1 100644
--- a/web/src/features/rbac/constants/projectAccessRights.ts
+++ b/web/src/features/rbac/constants/projectAccessRights.ts
@@ -83,11 +83,16 @@ export const projectScopes = [
"monitors:read",
"monitors:CUD",
+
+ "v4Migration:read",
] as const;
// type string of all Resource:Action, e.g. "members:read"
export type ProjectScope = (typeof projectScopes)[number];
+export const v4MigrationProjectScope =
+ "v4Migration:read" satisfies ProjectScope;
+
export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
OWNER: [
"project:read",
@@ -146,6 +151,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"automations:read",
"monitors:read",
"monitors:CUD",
+ v4MigrationProjectScope,
],
ADMIN: [
"project:read",
@@ -203,6 +209,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"automations:read",
"monitors:read",
"monitors:CUD",
+ v4MigrationProjectScope,
],
MEMBER: [
"project:read",
diff --git a/web/src/features/v4/components/V4MigrationProjectCards.clienttest.tsx b/web/src/features/v4/components/V4MigrationProjectCards.clienttest.tsx
index 5e1605981b..16902b7e38 100644
--- a/web/src/features/v4/components/V4MigrationProjectCards.clienttest.tsx
+++ b/web/src/features/v4/components/V4MigrationProjectCards.clienttest.tsx
@@ -1,10 +1,14 @@
-import { render } from "@testing-library/react";
+import { render, screen } from "@testing-library/react";
import { vi } from "vitest";
-import { UsageStackedBarOverview } from "@/src/features/v4/components/V4MigrationProjectCards";
+import {
+ UsageStackedBarOverview,
+ V4MigrationProjectCards,
+} from "@/src/features/v4/components/V4MigrationProjectCards";
import type { ReactNode } from "react";
const rechartsProps = vi.hoisted(() => ({
barCharts: [] as Array<{ margin?: { left?: number } }>,
+ bars: [] as Array<{ dataKey?: string }>,
yAxes: [] as Array<{
width?: number;
domain?: [number, number];
@@ -45,12 +49,18 @@ vi.mock("recharts", () => ({
return <div data-testid="y-axis" />;
},
Tooltip: () => null,
- Bar: () => <div data-testid="bar" />,
+ Bar: (props: Record<string, unknown>) => {
+ rechartsProps.bars.push({
+ dataKey: typeof props.dataKey === "string" ? props.dataKey : undefined,
+ });
+ return <div data-testid="bar" />;
+ },
}));
describe("UsageStackedBarOverview", () => {
beforeEach(() => {
rechartsProps.barCharts.length = 0;
+ rechartsProps.bars.length = 0;
rechartsProps.yAxes.length = 0;
});
@@ -111,4 +121,106 @@ describe("UsageStackedBarOverview", () => {
expect(rechartsProps.yAxes[0]?.ticks).toEqual([0, 2, 4, 6, 8]);
});
+
+ it("can render every exact usage series without rolling hidden items into other", () => {
+ render(
+ <UsageStackedBarOverview
+ bucketTimes={["2026-06-30T04:00:00.000Z"]}
+ valueLabel="records"
+ seriesLimit={null}
+ series={Array.from({ length: 7 }, (_, index) => ({
+ name: `python@3.${index}.0 - pk-lf-key-${index}`,
+ total: index + 1,
+ points: [index + 1],
+ }))}
+ />,
+ );
+
+ expect(rechartsProps.bars).toHaveLength(7);
+ expect(screen.queryByText("Other")).not.toBeInTheDocument();
+ expect(screen.getByText("[email protected] - pk-lf-key-6")).toBeInTheDocument();
+ });
+});
+
+describe("V4MigrationProjectCards SDK usage", () => {
+ beforeEach(() => {
+ rechartsProps.barCharts.length = 0;
+ rechartsProps.bars.length = 0;
+ rechartsProps.yAxes.length = 0;
+ });
+
+ it("shows SDK usage by exact SDK version and API key", () => {
+ render(
+ <V4MigrationProjectCards
+ projectId="project-v4"
+ legacyIntegrationSummary={{
+ legacyIntegrationCount: 0,
+ legacyIntegrations: {
+ posthog: false,
+ mixpanel: false,
+ blobStorage: false,
+ },
+ }}
+ traceLevelEvalCount={0}
+ legacyApiUsage={[]}
+ traceLevelEvalExecutions={[]}
+ sdkUsage={{
+ bucketTimes: ["2026-06-30T04:00:00.000Z", "2026-06-30T04:02:00.000Z"],
+ rows: [
+ {
+ time: "2026-06-30T04:00:00.000Z",
+ sdkName: "python",
+ sdkVersion: "3.9.0",
+ publicKey: "pk-lf-old-python",
+ count: 5,
+ firstSeen: "2026-06-30T04:02:00.000Z",
+ lastSeen: "2026-06-30T04:04:00.000Z",
+ canonicalSdkName: "python",
+ latestMajor: 4,
+ major: 3,
+ upgradeStatus: "outdated_major",
+ },
+ {
+ time: "2026-06-30T04:00:00.000Z",
+ sdkName: "unknown",
+ sdkVersion: "unknown",
+ publicKey: "",
+ count: 2,
+ firstSeen: "2026-06-30T04:00:00.000Z",
+ lastSeen: "2026-06-30T04:00:00.000Z",
+ canonicalSdkName: null,
+ latestMajor: null,
+ major: null,
+ upgradeStatus: "unknown",
+ },
+ ],
+ }}
+ isLegacyIntegrationSummaryLoading={false}
+ isTraceLevelEvalSummaryLoading={false}
+ isLegacyApiUsageLoading={false}
+ isTraceLevelEvalExecutionsLoading={false}
+ isSdkUsageLoading={false}
+ hasLegacyIntegrationSummaryError={false}
+ hasTraceLevelEvalSummaryError={false}
+ hasLegacyApiUsageError={false}
+ hasTraceLevelEvalExecutionsError={false}
+ hasSdkUsageError={false}
+ />,
+ );
+
+ expect(screen.getByText("SDK usage")).toBeInTheDocument();
+ expect(screen.getByText("[email protected]")).toBeInTheDocument();
+ expect(screen.getByText("pk-lf-old-python")).toBeInTheDocument();
+ expect(screen.queryByText("backend worker")).not.toBeInTheDocument();
+ expect(screen.getAllByText("untracked").length).toBeGreaterThan(0);
+ expect(
+ screen.queryByText("unknown@unknown - No API key"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("Upgrade")).toBeInTheDocument();
+ expect(screen.getByText("Upgrade guide")).toHaveAttribute(
+ "href",
+ "https://langfuse.com/docs/observability/sdk/upgrade-path/python-v3-to-v4",
+ );
+ expect(rechartsProps.bars).toHaveLength(2);
+ });
});
diff --git a/web/src/features/v4/components/V4MigrationProjectCards.tsx b/web/src/features/v4/components/V4MigrationProjectCards.tsx
index 513e898a34..795ec7472a 100644
--- a/web/src/features/v4/components/V4MigrationProjectCards.tsx
+++ b/web/src/features/v4/components/V4MigrationProjectCards.tsx
@@ -44,6 +44,30 @@ export type V4TraceLevelEvalExecutionPoint = {
count: number;
};
+export type V4SdkUsagePoint = {
+ time: string;
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ count: number;
+ firstSeen: string | null;
+ lastSeen: string | null;
+ canonicalSdkName: "python" | "javascript" | null;
+ latestMajor: number | null;
+ major: number | null;
+ upgradeStatus:
+ | "current"
+ | "outdated_major"
+ | "unknown"
+ | "unsupported_sdk"
+ | "invalid_version";
+};
+
+export type V4SdkUsageTimeSeries = {
+ bucketTimes: string[];
+ rows: V4SdkUsagePoint[];
+};
+
type ProductHref = string | { pathname: string; query: Record<string, string> };
type UsageSeries = {
@@ -58,11 +82,29 @@ type StackedUsageChartSeries = UsageSeries & {
color: string;
};
+type SdkUsageSeries = UsageSeries & {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ canonicalSdkName: V4SdkUsagePoint["canonicalSdkName"];
+ firstSeen?: string;
+ upgradeStatus: V4SdkUsagePoint["upgradeStatus"];
+ latestMajor: number | null;
+ major: number | null;
+};
+
const V4_DOCS_LINK = {
label: "Docs",
href: "https://langfuse.com/docs/v4",
} as const;
+const SDK_UPGRADE_LINKS = {
+ python:
+ "https://langfuse.com/docs/observability/sdk/upgrade-path/python-v3-to-v4",
+ javascript:
+ "https://langfuse.com/docs/observability/sdk/upgrade-path/js-v4-to-v5",
+} as const;
+
const MAX_STACKED_CHART_SERIES = 6;
const STACKED_CHART_Y_AXIS_TICK_COUNT = 5;
const STACKED_CHART_COLORS = [
@@ -179,6 +221,173 @@ const groupUsageSeries = <T extends { time: string; count: number }>({
});
};
+const getSdkUsageSeriesKey = (row: {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+}): string => `${row.sdkName}\u0000${row.sdkVersion}\u0000${row.publicKey}`;
+
+const getCompactPublicKey = (publicKey: string) =>
+ publicKey.length > 16
+ ? `${publicKey.slice(0, 9)}...${publicKey.slice(-6)}`
+ : publicKey || "No API key";
+
+const isUntrackedSdkUsage = (row: {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+}) =>
+ row.publicKey === "" &&
+ (row.sdkName || "unknown") === "unknown" &&
+ (row.sdkVersion || "unknown") === "unknown";
+
+const getSdkPackageLabel = (row: { sdkName: string; sdkVersion: string }) =>
+ `${row.sdkName || "unknown"}@${row.sdkVersion || "unknown"}`;
+
+const getSdkUsageSeriesName = (row: {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+}) =>
+ isUntrackedSdkUsage(row)
+ ? "untracked"
+ : `${getSdkPackageLabel(row)} - ${getCompactPublicKey(row.publicKey)}`;
+
+const getSdkUpgradeStatusLabel = (status: V4SdkUsagePoint["upgradeStatus"]) => {
+ switch (status) {
+ case "current":
+ return "Current";
+ case "outdated_major":
+ return "Upgrade";
+ case "unknown":
+ return "Unknown";
+ case "unsupported_sdk":
+ return "Other";
+ case "invalid_version":
+ return "Invalid";
+ default: {
+ const exhaustiveCheck: never = status;
+ return exhaustiveCheck;
+ }
+ }
+};
+
+const getSdkUpgradeStatusBadgeVariant = (
+ status: V4SdkUsagePoint["upgradeStatus"],
+): "success" | "warning" | "outline-solid" =>
+ status === "current"
+ ? "success"
+ : status === "outdated_major"
+ ? "warning"
+ : "outline-solid";
+
+const groupSdkUsageSeries = ({
+ rows,
+ bucketTimes,
+}: {
+ rows: V4SdkUsagePoint[] | undefined;
+ bucketTimes: string[];
+}): SdkUsageSeries[] => {
+ const groups = new Map<
+ string,
+ {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ canonicalSdkName: V4SdkUsagePoint["canonicalSdkName"];
+ upgradeStatus: V4SdkUsagePoint["upgradeStatus"];
+ latestMajor: number | null;
+ major: number | null;
+ total: number;
+ countsByTime: Map<string, number>;
+ firstSeen?: string;
+ lastSeen?: string;
+ }
+ >();
+
+ for (const row of rows ?? []) {
+ const key = getSdkUsageSeriesKey(row);
+ const group =
+ groups.get(key) ??
+ ({
+ sdkName: row.sdkName,
+ sdkVersion: row.sdkVersion,
+ publicKey: row.publicKey,
+ canonicalSdkName: row.canonicalSdkName,
+ upgradeStatus: row.upgradeStatus,
+ latestMajor: row.latestMajor,
+ major: row.major,
+ total: 0,
+ countsByTime: new Map<string, number>(),
+ } satisfies {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ canonicalSdkName: V4SdkUsagePoint["canonicalSdkName"];
+ upgradeStatus: V4SdkUsagePoint["upgradeStatus"];
+ latestMajor: number | null;
+ major: number | null;
+ total: number;
+ countsByTime: Map<string, number>;
+ firstSeen?: string;
+ lastSeen?: string;
+ });
+
+ group.total += row.count;
+ group.countsByTime.set(
+ row.time,
+ (group.countsByTime.get(row.time) ?? 0) + row.count,
+ );
+
+ if (row.count > 0) {
+ if (
+ row.firstSeen &&
+ (!group.firstSeen || row.firstSeen < group.firstSeen)
+ ) {
+ group.firstSeen = row.firstSeen;
+ }
+ if (row.lastSeen && (!group.lastSeen || row.lastSeen > group.lastSeen)) {
+ group.lastSeen = row.lastSeen;
+ }
+ }
+
+ groups.set(key, group);
+ }
+
+ return Array.from(groups.values())
+ .map((group) => ({
+ name: getSdkUsageSeriesName(group),
+ sdkName: group.sdkName,
+ sdkVersion: group.sdkVersion,
+ publicKey: group.publicKey,
+ canonicalSdkName: group.canonicalSdkName,
+ upgradeStatus: group.upgradeStatus,
+ latestMajor: group.latestMajor,
+ major: group.major,
+ total: group.total,
+ points: bucketTimes.map((time) => group.countsByTime.get(time) ?? 0),
+ firstSeen: group.firstSeen,
+ lastSeen: group.lastSeen,
+ }))
+ .filter((series) => series.total > 0)
+ .sort((left, right) => {
+ if (
+ left.upgradeStatus === "outdated_major" &&
+ right.upgradeStatus !== "outdated_major"
+ ) {
+ return -1;
+ }
+ if (
+ right.upgradeStatus === "outdated_major" &&
+ left.upgradeStatus !== "outdated_major"
+ ) {
+ return 1;
+ }
+ if (right.total !== left.total) return right.total - left.total;
+ return left.name.localeCompare(right.name);
+ });
+};
+
const Notice = ({ children }: { children: ReactNode }) => (
<Alert>
<AlertDescription>{children}</AlertDescription>
@@ -263,9 +472,11 @@ const Section = ({
const getStackedChartSeries = (
series: UsageSeries[],
+ seriesLimit: number | null = MAX_STACKED_CHART_SERIES,
): StackedUsageChartSeries[] => {
- const visibleSeries = series.slice(0, MAX_STACKED_CHART_SERIES);
- const hiddenSeries = series.slice(MAX_STACKED_CHART_SERIES);
+ const visibleSeries =
+ seriesLimit === null ? series : series.slice(0, seriesLimit);
+ const hiddenSeries = seriesLimit === null ? [] : series.slice(seriesLimit);
const stackSeries =
hiddenSeries.length === 0
? visibleSeries
@@ -326,12 +537,17 @@ export const UsageStackedBarOverview = ({
bucketTimes,
series,
valueLabel,
+ seriesLimit,
}: {
bucketTimes: string[];
series: UsageSeries[];
valueLabel: string;
+ seriesLimit?: number | null;
}) => {
- const chartSeries = useMemo(() => getStackedChartSeries(series), [series]);
+ const chartSeries = useMemo(
+ () => getStackedChartSeries(series, seriesLimit),
+ [series, seriesLimit],
+ );
const yAxisTicks = useMemo(
() => getStackedYAxisTicks(chartSeries),
[chartSeries],
@@ -452,6 +668,111 @@ export const UsageStackedBarOverview = ({
);
};
+const SdkUsageDetails = ({
+ bucketTimes,
+ series,
+}: {
+ bucketTimes: string[];
+ series: SdkUsageSeries[];
+}) => {
+ const total = series.reduce((sum, item) => sum + item.total, 0);
+
+ return (
+ <div className="flex flex-col gap-2">
+ <UsageStackedBarOverview
+ bucketTimes={bucketTimes}
+ series={series}
+ valueLabel="records"
+ seriesLimit={null}
+ />
+ <div className="overflow-hidden rounded-md border">
+ <div className="bg-muted/30 text-muted-foreground hidden grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_7rem_7rem] gap-3 border-b px-3 py-2 text-xs font-medium md:grid">
+ <span>SDK</span>
+ <span>API key</span>
+ <span className="text-right">Last seen</span>
+ <span className="text-right">Records</span>
+ </div>
+ <div className="max-h-80 overflow-y-auto">
+ {series.map((item) => {
+ const upgradeHref =
+ item.upgradeStatus === "outdated_major" && item.canonicalSdkName
+ ? SDK_UPGRADE_LINKS[item.canonicalSdkName]
+ : null;
+ const publicKeyLabel = item.publicKey || "No API key";
+ const detail = [
+ item.latestMajor ? `latest major: ${item.latestMajor}` : null,
+ ]
+ .filter(Boolean)
+ .join(" - ");
+
+ return (
+ <div
+ key={getSdkUsageSeriesKey(item)}
+ className="grid gap-3 border-b px-3 py-2 last:border-b-0 md:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_7rem_7rem] md:items-center"
+ >
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <Badge
+ variant={getSdkUpgradeStatusBadgeVariant(
+ item.upgradeStatus,
+ )}
+ size="sm"
+ className="shrink-0"
+ >
+ {getSdkUpgradeStatusLabel(item.upgradeStatus)}
+ </Badge>
+ <span
+ className="truncate text-sm font-medium"
+ title={
+ isUntrackedSdkUsage(item)
+ ? "untracked"
+ : getSdkPackageLabel(item)
+ }
+ >
+ {isUntrackedSdkUsage(item)
+ ? "untracked"
+ : getSdkPackageLabel(item)}
+ </span>
+ </div>
+ <div
+ className="text-muted-foreground mt-0.5 truncate text-xs"
+ title={detail}
+ >
+ {upgradeHref ? (
+ <InlineLink href={upgradeHref} external>
+ Upgrade guide
+ </InlineLink>
+ ) : (
+ detail || "No upgrade guidance"
+ )}
+ </div>
+ </div>
+ <div className="min-w-0 md:block">
+ <div
+ className="truncate font-mono text-xs"
+ title={publicKeyLabel}
+ >
+ {publicKeyLabel}
+ </div>
+ </div>
+ <div className="text-muted-foreground text-xs md:text-right">
+ {item.lastSeen ? getBucketLabel(item.lastSeen) : "-"}
+ </div>
+ <div className="text-sm font-medium md:text-right">
+ {numberFormatter(item.total, 0, 2)}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ <div className="bg-muted/20 text-muted-foreground border-t px-3 py-2 text-right text-xs">
+ {numberFormatter(total, 0, 2)} records
+ </div>
+ </div>
+ </div>
+ );
+};
+
const ActionRow = ({
title,
titleClassName,
@@ -504,14 +825,17 @@ export const V4MigrationProjectCards = ({
traceLevelEvalCount: configuredTraceLevelEvalCount,
legacyApiUsage,
traceLevelEvalExecutions,
+ sdkUsage,
isLegacyIntegrationSummaryLoading,
isTraceLevelEvalSummaryLoading,
isLegacyApiUsageLoading,
isTraceLevelEvalExecutionsLoading,
+ isSdkUsageLoading,
hasLegacyIntegrationSummaryError,
hasTraceLevelEvalSummaryError,
hasLegacyApiUsageError,
hasTraceLevelEvalExecutionsError,
+ hasSdkUsageError,
}: {
projectId: string;
projectName?: string;
@@ -519,14 +843,17 @@ export const V4MigrationProjectCards = ({
traceLevelEvalCount: number | undefined;
legacyApiUsage: V4LegacyApiUsagePoint[] | undefined;
traceLevelEvalExecutions: V4TraceLevelEvalExecutionPoint[] | undefined;
+ sdkUsage: V4SdkUsageTimeSeries | undefined;
isLegacyIntegrationSummaryLoading: boolean;
isTraceLevelEvalSummaryLoading: boolean;
isLegacyApiUsageLoading: boolean;
isTraceLevelEvalExecutionsLoading: boolean;
+ isSdkUsageLoading: boolean;
hasLegacyIntegrationSummaryError: boolean;
hasTraceLevelEvalSummaryError: boolean;
hasLegacyApiUsageError: boolean;
hasTraceLevelEvalExecutionsError: boolean;
+ hasSdkUsageError: boolean;
}) => {
const traceLevelEvalsHref = useMemo(
() => getTraceLevelEvalsHref(projectId),
@@ -559,6 +886,27 @@ export const V4MigrationProjectCards = ({
[evalExecutionBucketTimes, traceLevelEvalExecutions],
);
+ const sdkUsageBucketTimes = useMemo(
+ () => sdkUsage?.bucketTimes ?? [],
+ [sdkUsage?.bucketTimes],
+ );
+ const sdkUsageRows = sdkUsage?.rows;
+ const sdkUsageSeries = useMemo(
+ () =>
+ groupSdkUsageSeries({
+ rows: sdkUsageRows,
+ bucketTimes: sdkUsageBucketTimes,
+ }),
+ [sdkUsageBucketTimes, sdkUsageRows],
+ );
+ const outdatedSdkUsageSeries = useMemo(
+ () =>
+ sdkUsageSeries.filter(
+ (series) => series.upgradeStatus === "outdated_major",
+ ),
+ [sdkUsageSeries],
+ );
+
const legacyIntegrationLinks = useMemo(
() =>
INTEGRATION_LINKS.filter(
@@ -572,18 +920,22 @@ export const V4MigrationProjectCards = ({
hasLegacyIntegrationSummaryError ||
hasTraceLevelEvalSummaryError ||
hasLegacyApiUsageError ||
- hasTraceLevelEvalExecutionsError;
+ hasTraceLevelEvalExecutionsError ||
+ hasSdkUsageError;
const traceLevelEvalCount =
configuredTraceLevelEvalCount ?? evalExecutionSeries.length;
const activeTaskCount =
legacyApiSeries.length +
traceLevelEvalCount +
- legacyIntegrationLinks.length;
+ legacyIntegrationLinks.length +
+ outdatedSdkUsageSeries.length;
const migrationStatus = getV4MigrationStatus(activeTaskCount);
const isSummaryLoading =
isLegacyIntegrationSummaryLoading || isTraceLevelEvalSummaryLoading;
const isTimelineLoading =
- isLegacyApiUsageLoading || isTraceLevelEvalExecutionsLoading;
+ isLegacyApiUsageLoading ||
+ isTraceLevelEvalExecutionsLoading ||
+ isSdkUsageLoading;
return (
<DashboardCard
@@ -648,6 +1000,26 @@ export const V4MigrationProjectCards = ({
)}
</Section>
+ <Section
+ title="SDK usage"
+ count={sdkUsageSeries.length}
+ isCountLoading={isSdkUsageLoading}
+ detailsHref={`/project/${projectId}/settings/api-keys`}
+ >
+ {isSdkUsageLoading ? (
+ <SectionLoading />
+ ) : hasSdkUsageError ? (
+ <Notice>Failed to load SDK usage.</Notice>
+ ) : sdkUsageSeries.length ? (
+ <SdkUsageDetails
+ bucketTimes={sdkUsageBucketTimes}
+ series={sdkUsageSeries}
+ />
+ ) : (
+ <Notice>No SDK usage detected in this range.</Notice>
+ )}
+ </Section>
+
<Section
title="Trace-level evals"
count={traceLevelEvalCount}
diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.ts
index 66abc5a18b..c7449ab102 100644
--- a/web/src/features/v4/server/v4TransitionRouter.ts
+++ b/web/src/features/v4/server/v4TransitionRouter.ts
@@ -5,15 +5,19 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { v4MigrationOrgScope } from "@/src/features/rbac/constants/organizationAccessRights";
+import { v4MigrationProjectScope } from "@/src/features/rbac/constants/projectAccessRights";
import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import {
AnalyticsIntegrationExportSource,
Prisma,
} from "@langfuse/shared/src/db";
import {
+ classifyIngestionSdkVersion,
convertDateToClickhouseDateTime,
queryClickhouse,
systemTableRef,
+ type IngestionSdkUpgradeStatus,
} from "@langfuse/shared/src/server";
import {
addTimelineBucket,
@@ -110,6 +114,48 @@ type LegacyApiUsageSummaryByProjectResultRow = {
count: number;
};
+type SdkUsageTimeSeriesRow = {
+ time: string;
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ count: string | number;
+ firstSeen: string;
+ lastSeen: string;
+};
+
+type SdkUsageTimeSeriesResultRow = {
+ time: string;
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ count: number;
+ firstSeen: string | null;
+ lastSeen: string | null;
+ canonicalSdkName: "python" | "javascript" | null;
+ latestMajor: number | null;
+ major: number | null;
+ upgradeStatus: IngestionSdkUpgradeStatus;
+};
+
+type SdkUsageTimeSeriesResult = {
+ bucketTimes: string[];
+ rows: SdkUsageTimeSeriesResultRow[];
+};
+
+type SdkUsageSummaryByProjectRow = {
+ projectId: string;
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+ count: string | number;
+};
+
+type SdkUsageSummaryByProjectResultRow = {
+ projectId: string;
+ outdatedSdkUsageSeriesCount: number;
+};
+
const getEmptyTimelineBuckets = (
fromTimestamp: Date,
toTimestamp: Date,
@@ -144,6 +190,72 @@ const compareTimelineRows = (
return left.entrypoint.localeCompare(right.entrypoint);
};
+const getTimelineBucketTimes = (
+ fromTimestamp: Date,
+ toTimestamp: Date,
+ granularity: ResolvedTimelineGranularity,
+): string[] => {
+ const buckets: string[] = [];
+
+ for (
+ let bucket = floorTimelineBucket(fromTimestamp, granularity);
+ bucket.getTime() < toTimestamp.getTime();
+ bucket = addTimelineBucket(bucket, granularity)
+ ) {
+ buckets.push(formatTimelineBucket(bucket));
+ }
+
+ return buckets;
+};
+
+const getSdkUsageSeriesKey = (row: {
+ sdkName: string;
+ sdkVersion: string;
+ publicKey: string;
+}): string => `${row.sdkName}\u0000${row.sdkVersion}\u0000${row.publicKey}`;
+
+const compareSdkUsageRows = (
+ left: SdkUsageTimeSeriesResultRow,
+ right: SdkUsageTimeSeriesResultRow,
+): number => {
+ if (left.time < right.time) return -1;
+ if (left.time > right.time) return 1;
+
+ const leftSeries = getSdkUsageSeriesKey(left);
+ const rightSeries = getSdkUsageSeriesKey(right);
+
+ return leftSeries.localeCompare(rightSeries);
+};
+
+const decorateSdkUsageRows = ({
+ rows,
+}: {
+ rows: SdkUsageTimeSeriesRow[];
+}): SdkUsageTimeSeriesResultRow[] => {
+ return rows
+ .map((row) => {
+ const classification = classifyIngestionSdkVersion({
+ sdkName: row.sdkName,
+ sdkVersion: row.sdkVersion,
+ });
+
+ return {
+ time: row.time,
+ sdkName: row.sdkName,
+ sdkVersion: row.sdkVersion,
+ publicKey: row.publicKey,
+ count: Number(row.count),
+ firstSeen: row.firstSeen,
+ lastSeen: row.lastSeen,
+ canonicalSdkName: classification.canonicalSdkName,
+ latestMajor: classification.latestMajor,
+ major: classification.major,
+ upgradeStatus: classification.status,
+ };
+ })
+ .sort(compareSdkUsageRows);
+};
+
type TraceLevelEvalExecutionTimeSeriesRow = {
time: string;
scoreName: string;
@@ -219,6 +331,17 @@ const protectedV4MigrationOrgProcedure = protectedOrganizationProcedure.use(
},
);
+const protectedV4MigrationProjectProcedure = protectedProjectProcedure.use(
+ ({ ctx, next }) => {
+ throwIfNoProjectAccess({
+ role: ctx.session.projectRole,
+ admin: ctx.session.user.admin,
+ scope: v4MigrationProjectScope,
+ });
+ return next();
+ },
+);
+
const getLegacyIntegrations = ({
posthogIntegration,
mixpanelIntegration,
@@ -243,7 +366,7 @@ const getLegacyIntegrations = ({
});
export const v4TransitionRouter = createTRPCRouter({
- summary: protectedProjectProcedure
+ summary: protectedV4MigrationProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
const [posthogIntegration, mixpanelIntegration, blobStorageIntegration] =
@@ -275,7 +398,7 @@ export const v4TransitionRouter = createTRPCRouter({
};
}),
- traceLevelEvalSummary: protectedProjectProcedure
+ traceLevelEvalSummary: protectedV4MigrationProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {
const traceLevelEvalCount = await ctx.prisma.jobConfiguration.count({
@@ -410,7 +533,7 @@ export const v4TransitionRouter = createTRPCRouter({
);
}),
- traceLevelEvalExecutionsTimeSeries: protectedProjectProcedure
+ traceLevelEvalExecutionsTimeSeries: protectedV4MigrationProjectProcedure
.input(timelineInputSchema)
.query(async ({ input, ctx }) => {
const granularity = resolveTimelineGranularity(
@@ -462,6 +585,188 @@ ORDER BY bucket_time ASC, score_name ASC
});
}),
+ sdkUsageTimeSeries: protectedV4MigrationProjectProcedure
+ .input(timelineInputSchema)
+ .query(async ({ input }) => {
+ const granularity = resolveTimelineGranularity(
+ input.fromTimestamp,
+ input.toTimestamp,
+ );
+ const bucketTimeSql = getTimelineBucketSql("event_time", granularity);
+
+ const scoresUnionSql = `
+ UNION ALL
+
+ SELECT
+ timestamp AS event_time,
+ if(ingestion_sdk_name = '', 'unknown', ingestion_sdk_name) AS sdk_name,
+ if(ingestion_sdk_version = '', 'unknown', ingestion_sdk_version) AS sdk_version,
+ ingestion_api_key AS public_key
+ FROM scores FINAL
+ WHERE
+ project_id = {projectId: String}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND toDate(timestamp) >= toDate({fromTimestamp: DateTime64(3)})
+ AND toDate(timestamp) <= toDate({toTimestamp: DateTime64(3)})
+ AND is_deleted = 0`;
+
+ const rows = await queryClickhouse<SdkUsageTimeSeriesRow>({
+ query: `
+WITH selected AS (
+ SELECT
+ start_time AS event_time,
+ if(ingestion_sdk_name = '', 'unknown', ingestion_sdk_name) AS sdk_name,
+ if(ingestion_sdk_version = '', 'unknown', ingestion_sdk_version) AS sdk_version,
+ ingestion_api_key AS public_key
+ FROM events_core
+ WHERE
+ project_id = {projectId: String}
+ AND start_time >= {fromTimestamp: DateTime64(3)}
+ AND start_time <= {toTimestamp: DateTime64(3)}
+ AND toDate(start_time) >= toDate({fromTimestamp: DateTime64(3)})
+ AND toDate(start_time) <= toDate({toTimestamp: DateTime64(3)})
+ AND is_deleted = 0
+ ${scoresUnionSql}
+)
+
+SELECT
+ formatDateTime(${bucketTimeSql}, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS time,
+ sdk_name AS sdkName,
+ sdk_version AS sdkVersion,
+ public_key AS publicKey,
+ count() AS count,
+ formatDateTime(min(event_time), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS firstSeen,
+ formatDateTime(max(event_time), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS lastSeen
+FROM selected
+GROUP BY ${bucketTimeSql}, sdk_name, sdk_version, public_key
+ORDER BY ${bucketTimeSql} ASC, sdk_name ASC, sdk_version ASC, public_key ASC
+ `,
+ params: {
+ projectId: input.projectId,
+ fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),
+ toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),
+ },
+ tags: {
+ projectId: input.projectId,
+ route: "v4-sdk-usage-timeseries",
+ },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+
+ return {
+ bucketTimes: getTimelineBucketTimes(
+ input.fromTimestamp,
+ input.toTimestamp,
+ granularity,
+ ),
+ rows: decorateSdkUsageRows({
+ rows,
+ }),
+ } satisfies SdkUsageTimeSeriesResult;
+ }),
+
+ sdkUsageSummaryByProject: protectedV4MigrationOrgProcedure
+ .input(organizationTimeRangeInputSchema)
+ .query(async ({ input, ctx }) => {
+ const projects = await ctx.prisma.project.findMany({
+ where: {
+ orgId: input.orgId,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ });
+ const projectIds = projects.map((project) => project.id);
+
+ if (projectIds.length === 0) return [];
+
+ const scoresUnionSql = `
+ UNION ALL
+
+ SELECT
+ project_id,
+ if(ingestion_sdk_name = '', 'unknown', ingestion_sdk_name) AS sdk_name,
+ if(ingestion_sdk_version = '', 'unknown', ingestion_sdk_version) AS sdk_version,
+ ingestion_api_key AS public_key
+ FROM scores FINAL
+ WHERE
+ project_id IN {projectIds: Array(String)}
+ AND timestamp >= {fromTimestamp: DateTime64(3)}
+ AND timestamp <= {toTimestamp: DateTime64(3)}
+ AND toDate(timestamp) >= toDate({fromTimestamp: DateTime64(3)})
+ AND toDate(timestamp) <= toDate({toTimestamp: DateTime64(3)})
+ AND is_deleted = 0`;
+
+ const rows = await queryClickhouse<SdkUsageSummaryByProjectRow>({
+ query: `
+WITH selected AS (
+ SELECT
+ project_id,
+ if(ingestion_sdk_name = '', 'unknown', ingestion_sdk_name) AS sdk_name,
+ if(ingestion_sdk_version = '', 'unknown', ingestion_sdk_version) AS sdk_version,
+ ingestion_api_key AS public_key
+ FROM events_core
+ WHERE
+ project_id IN {projectIds: Array(String)}
+ AND start_time >= {fromTimestamp: DateTime64(3)}
+ AND start_time <= {toTimestamp: DateTime64(3)}
+ AND toDate(start_time) >= toDate({fromTimestamp: DateTime64(3)})
+ AND toDate(start_time) <= toDate({toTimestamp: DateTime64(3)})
+ AND is_deleted = 0
+ ${scoresUnionSql}
+)
+
+SELECT
+ project_id AS projectId,
+ sdk_name AS sdkName,
+ sdk_version AS sdkVersion,
+ public_key AS publicKey,
+ count() AS count
+FROM selected
+GROUP BY project_id, sdk_name, sdk_version, public_key
+ORDER BY project_id ASC, sdk_name ASC, sdk_version ASC, public_key ASC
+ `,
+ params: {
+ projectIds,
+ fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),
+ toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),
+ },
+ tags: {
+ route: "v4-org-sdk-usage-summary",
+ },
+ preferredClickhouseService: "EventsReadOnly",
+ });
+
+ const outdatedCountsByProjectId = new Map<string, number>();
+
+ for (const row of rows) {
+ const classification = classifyIngestionSdkVersion({
+ sdkName: row.sdkName,
+ sdkVersion: row.sdkVersion,
+ });
+
+ if (
+ classification.status === "outdated_major" &&
+ Number(row.count) > 0
+ ) {
+ outdatedCountsByProjectId.set(
+ row.projectId,
+ (outdatedCountsByProjectId.get(row.projectId) ?? 0) + 1,
+ );
+ }
+ }
+
+ return projectIds.map(
+ (projectId): SdkUsageSummaryByProjectResultRow => ({
+ projectId,
+ outdatedSdkUsageSeriesCount:
+ outdatedCountsByProjectId.get(projectId) ?? 0,
+ }),
+ );
+ }),
+
legacyApiUsageSummaryByProject: protectedV4MigrationOrgProcedure
.input(organizationTimeRangeInputSchema)
.query(async ({ input, ctx }) => {
@@ -575,7 +880,7 @@ SETTINGS skip_unavailable_shards = 1
);
}),
- timeSeriesByEntrypoint: protectedProjectProcedure
+ timeSeriesByEntrypoint: protectedV4MigrationProjectProcedure
.input(timelineInputSchema)
.query(async ({ input }) => {
const granularity = resolveTimelineGranularity(
diff --git a/web/src/pages/organization/[organizationId]/v4/index.tsx b/web/src/pages/organization/[organizationId]/v4/index.tsx
index 8ee75227fb..feff6a0ded 100644
--- a/web/src/pages/organization/[organizationId]/v4/index.tsx
+++ b/web/src/pages/organization/[organizationId]/v4/index.tsx
@@ -53,6 +53,11 @@ type ProjectTraceLevelEvalSummary = {
traceLevelEvalCount: number;
};
+type ProjectSdkUsageSummary = {
+ projectId: string;
+ outdatedSdkUsageSeriesCount: number;
+};
+
const groupByProjectId = <T extends { projectId: string }>(
rows: T[] | undefined,
): Map<string, T[]> => {
@@ -75,10 +80,12 @@ const getProjectActionCount = (
project: ProjectSummary,
traceLevelEvalCount: number,
legacyApiEntrypointCount: number,
+ outdatedSdkUsageSeriesCount: number,
): number =>
traceLevelEvalCount +
project.legacyIntegrationCount +
- legacyApiEntrypointCount;
+ legacyApiEntrypointCount +
+ outdatedSdkUsageSeriesCount;
export default function OrganizationV4Page() {
const router = useRouter();
@@ -143,6 +150,23 @@ export default function OrganizationV4Page() {
},
);
+ const sdkUsageSummaryByProject =
+ api.v4Transition.sdkUsageSummaryByProject.useQuery(
+ {
+ orgId: organizationId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ },
+ {
+ enabled: Boolean(organizationId) && canViewOrgV4Page,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
const legacyApiUsageRowsByProjectId = useMemo(
() =>
groupByProjectId<ProjectScopedLegacyApiUsageSummary>(
@@ -162,6 +186,18 @@ export default function OrganizationV4Page() {
),
[traceLevelEvalSummaryByProject.data],
);
+ const outdatedSdkUsageSeriesCountsByProjectId = useMemo(
+ () =>
+ new Map(
+ (sdkUsageSummaryByProject.data ?? []).map(
+ (row: ProjectSdkUsageSummary) => [
+ row.projectId,
+ row.outdatedSdkUsageSeriesCount,
+ ],
+ ),
+ ),
+ [sdkUsageSummaryByProject.data],
+ );
const projects = useMemo(
() =>
@@ -172,6 +208,7 @@ export default function OrganizationV4Page() {
countLegacyApiEntrypoints(
legacyApiUsageRowsByProjectId.get(b.projectId),
),
+ outdatedSdkUsageSeriesCountsByProjectId.get(b.projectId) ?? 0,
);
const aActionCount = getProjectActionCount(
a,
@@ -179,6 +216,7 @@ export default function OrganizationV4Page() {
countLegacyApiEntrypoints(
legacyApiUsageRowsByProjectId.get(a.projectId),
),
+ outdatedSdkUsageSeriesCountsByProjectId.get(a.projectId) ?? 0,
);
if (bActionCount !== aActionCount) return bActionCount - aActionCount;
@@ -187,6 +225,7 @@ export default function OrganizationV4Page() {
[
summaryByProject.data?.projects,
legacyApiUsageRowsByProjectId,
+ outdatedSdkUsageSeriesCountsByProjectId,
traceLevelEvalCountsByProjectId,
],
);
@@ -236,6 +275,23 @@ export default function OrganizationV4Page() {
},
);
+ const selectedProjectSdkUsage = api.v4Transition.sdkUsageTimeSeries.useQuery(
+ {
+ projectId: selectedProject?.projectId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ granularity: "auto",
+ },
+ {
+ enabled: Boolean(selectedProject?.projectId) && canViewOrgV4Page,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
const migrationSummary = useMemo(() => {
return projects.reduce(
(summary, project) => {
@@ -246,6 +302,7 @@ export default function OrganizationV4Page() {
project,
traceLevelEvalCountsByProjectId.get(project.projectId) ?? 0,
countLegacyApiEntrypoints(legacyApiRows),
+ outdatedSdkUsageSeriesCountsByProjectId.get(project.projectId) ?? 0,
);
return {
@@ -258,6 +315,7 @@ export default function OrganizationV4Page() {
);
}, [
legacyApiUsageRowsByProjectId,
+ outdatedSdkUsageSeriesCountsByProjectId,
projects,
traceLevelEvalCountsByProjectId,
]);
@@ -265,10 +323,12 @@ export default function OrganizationV4Page() {
const isProjectReadinessLoading =
summaryByProject.isPending ||
legacyApiUsageSummaryByProject.isPending ||
+ sdkUsageSummaryByProject.isPending ||
traceLevelEvalSummaryByProject.isPending;
const hasProjectReadinessError =
Boolean(summaryByProject.error) ||
Boolean(legacyApiUsageSummaryByProject.error) ||
+ Boolean(sdkUsageSummaryByProject.error) ||
Boolean(traceLevelEvalSummaryByProject.error);
useEffect(() => {
@@ -338,7 +398,7 @@ export default function OrganizationV4Page() {
<div className="min-h-40" />
) : projects.length > 0 ? (
<div className="overflow-x-auto">
- <Table className="min-w-[60rem] table-auto">
+ <Table className="min-w-[68rem] table-auto">
<TableHeader>
<TableRow>
<TableHead>Project</TableHead>
@@ -352,6 +412,7 @@ export default function OrganizationV4Page() {
<TableHead className="w-44 text-right">
Public API
</TableHead>
+ <TableHead className="w-32 text-right">SDKs</TableHead>
<TableHead className="w-32" />
</TableRow>
</TableHeader>
@@ -369,15 +430,24 @@ export default function OrganizationV4Page() {
traceLevelEvalCountsByProjectId.get(project.projectId) ??
0,
legacyApiEntrypointCount,
+ outdatedSdkUsageSeriesCountsByProjectId.get(
+ project.projectId,
+ ) ?? 0,
);
const traceLevelEvalCount =
traceLevelEvalCountsByProjectId.get(project.projectId) ??
0;
+ const outdatedSdkUsageSeriesCount =
+ outdatedSdkUsageSeriesCountsByProjectId.get(
+ project.projectId,
+ ) ?? 0;
const isStatusPending =
legacyApiUsageSummaryByProject.isPending ||
+ sdkUsageSummaryByProject.isPending ||
traceLevelEvalSummaryByProject.isPending;
const hasStatusError =
Boolean(legacyApiUsageSummaryByProject.error) ||
+ Boolean(sdkUsageSummaryByProject.error) ||
Boolean(traceLevelEvalSummaryByProject.error);
const migrationStatus =
isStatusPending || hasStatusError
@@ -437,6 +507,18 @@ export default function OrganizationV4Page() {
)} calls`
: "0"}
</TableCell>
+ <TableCell density="comfortable" className="text-right">
+ {sdkUsageSummaryByProject.isPending
+ ? "Loading..."
+ : sdkUsageSummaryByProject.error
+ ? "Failed"
+ : outdatedSdkUsageSeriesCount > 0
+ ? `${numberFormatter(
+ outdatedSdkUsageSeriesCount,
+ 0,
+ )} outdated`
+ : "0"}
+ </TableCell>
<TableCell density="comfortable">
<Button
variant={isSelected ? "secondary" : "outline"}
@@ -476,6 +558,7 @@ export default function OrganizationV4Page() {
traceLevelEvalExecutions={
selectedProjectTraceLevelEvalExecutions.data
}
+ sdkUsage={selectedProjectSdkUsage.data}
isLegacyIntegrationSummaryLoading={summaryByProject.isPending}
isTraceLevelEvalSummaryLoading={
traceLevelEvalSummaryByProject.isPending
@@ -484,6 +567,7 @@ export default function OrganizationV4Page() {
isTraceLevelEvalExecutionsLoading={
selectedProjectTraceLevelEvalExecutions.isPending
}
+ isSdkUsageLoading={selectedProjectSdkUsage.isPending}
hasLegacyIntegrationSummaryError={Boolean(summaryByProject.error)}
hasTraceLevelEvalSummaryError={Boolean(
traceLevelEvalSummaryByProject.error,
@@ -494,6 +578,7 @@ export default function OrganizationV4Page() {
hasTraceLevelEvalExecutionsError={Boolean(
selectedProjectTraceLevelEvalExecutions.error,
)}
+ hasSdkUsageError={Boolean(selectedProjectSdkUsage.error)}
/>
) : null}
</div>
diff --git a/web/src/pages/project/[projectId]/v4/index.tsx b/web/src/pages/project/[projectId]/v4/index.tsx
index d74340fcf8..25f4eb0fa3 100644
--- a/web/src/pages/project/[projectId]/v4/index.tsx
+++ b/web/src/pages/project/[projectId]/v4/index.tsx
@@ -87,6 +87,23 @@ export default function V4Page() {
},
);
+ const sdkUsage = api.v4Transition.sdkUsageTimeSeries.useQuery(
+ {
+ projectId: projectId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ granularity: "auto",
+ },
+ {
+ enabled: Boolean(projectId),
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
return (
<Page
withPadding
@@ -113,16 +130,19 @@ export default function V4Page() {
traceLevelEvalCount={traceLevelEvalSummary.data?.traceLevelEvalCount}
legacyApiUsage={legacyApiUsage.data}
traceLevelEvalExecutions={traceLevelEvalExecutions.data}
+ sdkUsage={sdkUsage.data}
isLegacyIntegrationSummaryLoading={summary.isPending}
isTraceLevelEvalSummaryLoading={traceLevelEvalSummary.isPending}
isLegacyApiUsageLoading={legacyApiUsage.isPending}
isTraceLevelEvalExecutionsLoading={traceLevelEvalExecutions.isPending}
+ isSdkUsageLoading={sdkUsage.isPending}
hasLegacyIntegrationSummaryError={Boolean(summary.error)}
hasTraceLevelEvalSummaryError={Boolean(traceLevelEvalSummary.error)}
hasLegacyApiUsageError={Boolean(legacyApiUsage.error)}
hasTraceLevelEvalExecutionsError={Boolean(
traceLevelEvalExecutions.error,
)}
+ hasSdkUsageError={Boolean(sdkUsage.error)}
/>
</div>
</Page>