Skip to content

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

feat(v4): add legacy api usage page (#14558)

Max Deichmann8fd11089d5ba
diff --git a/packages/shared/src/server/clickhouse/queryTracking.ts b/packages/shared/src/server/clickhouse/queryTracking.ts
index b62e1c13e6..5c121fd31a 100644
--- a/packages/shared/src/server/clickhouse/queryTracking.ts
+++ b/packages/shared/src/server/clickhouse/queryTracking.ts
@@ -20,7 +20,7 @@ export function sleep(ms: number): Promise<void> {
* when CH is deployed as a cluster. Single-node deployments (self-hosted) read
* the local table directly.
*/
-function systemTableRef(
+export function systemTableRef(
table: "system.processes" | "system.query_log",
): string {
if (env.CLICKHOUSE_CLUSTER_ENABLED === "true") {
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
new file mode 100644
index 0000000000..963c7282c2
--- /dev/null
+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
@@ -0,0 +1,167 @@
+import type { Session } from "next-auth";
+import type * as SharedServer from "@langfuse/shared/src/server";
+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>();
+
+ return {
+ ...actual,
+ queryClickhouse: vi.fn(),
+ systemTableRef: vi.fn(
+ (table: "system.processes" | "system.query_log") =>
+ `clusterAllReplicas('test-cluster', '${table}')`,
+ ),
+ };
+});
+
+const mockedQueryClickhouse = vi.mocked(queryClickhouse);
+
+const projectId = "project-v4-transition";
+
+const session: Session = {
+ expires: "1",
+ user: {
+ id: "user-v4-transition",
+ name: "V4 Transition User",
+ email: "[email protected]",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: "org-v4-transition",
+ name: "V4 Transition Org",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ aiFeaturesEnabled: true,
+ aiTelemetryEnabled: true,
+ projects: [
+ {
+ id: projectId,
+ name: "V4 Transition Project",
+ role: "ADMIN",
+ deletedAt: null,
+ retentionDays: null,
+ hasTraces: false,
+ metadata: {},
+ createdAt: new Date(0).toISOString(),
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ excludeClickhouseRead: false,
+ observationEvals: false,
+ templateFlag: false,
+ searchBar: false,
+ v4BetaToggleVisible: false,
+ experimentsV4Enabled: false,
+ },
+ admin: false,
+ },
+ environment: {
+ enableExperimentalFeatures: false,
+ selfHostedInstancePlan: "cloud:hobby",
+ },
+};
+
+describe("v4TransitionRouter", () => {
+ beforeEach(() => {
+ mockedQueryClickhouse.mockResolvedValue([
+ {
+ time: "2026-06-25T12:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces/{id}",
+ count: "0.6666666666666666",
+ },
+ ]);
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("queries legacy public API usage with UTC buckets and route classification", async () => {
+ const caller = v4TransitionRouter.createCaller(
+ createInnerTRPCContext({ session, headers: {} }),
+ );
+
+ const rows = await caller.timeSeriesByEntrypoint({
+ projectId,
+ fromTimestamp: new Date("2026-06-24T00:00:00Z"),
+ toTimestamp: new Date("2026-06-25T00:00:00Z"),
+ interval: {
+ count: 1,
+ unit: "day",
+ },
+ });
+
+ expect(rows).toEqual([
+ {
+ time: "2026-06-25T12:00:00Z",
+ entrypoint: "publicapi: GET /api/public/traces/{id}",
+ count: 0.6666666666666666,
+ },
+ ]);
+
+ expect(mockedQueryClickhouse).toHaveBeenCalledTimes(1);
+ const clickhouseQuery = mockedQueryClickhouse.mock.calls[0]?.[0];
+ expect(clickhouseQuery?.query).toContain(
+ "FROM clusterAllReplicas('test-cluster', 'system.query_log')",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "toStartOfInterval(event_time_microseconds, INTERVAL 1 DAY, 'UTC')",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "splitByChar('?', JSONExtractString(log_comment, 'route'))[1]",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "sum(1.0 / clickhouse_queries_per_api_call) AS count",
+ );
+ expect(clickhouseQuery?.query).toContain("AND type = 'QueryFinish'");
+ expect(clickhouseQuery?.query).toContain(
+ "JSONExtractString(log_comment, 'tag_schema_version') = '1'",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "JSONExtractString(log_comment, 'surface') = 'publicapi'",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "JSONExtractString(log_comment, 'projectId') = {projectId: String}",
+ );
+ expect(clickhouseQuery?.clickhouseSettings).toEqual({
+ skip_unavailable_shards: 1,
+ });
+
+ [
+ "GET /api/public/spans",
+ "GET /api/public/generations",
+ "GET /api/public/traces",
+ "GET /api/public/sessions",
+ "GET /api/public/observations",
+ "GET /api/public/scores",
+ "GET /api/public/v2/scores",
+ "GET /api/public/metrics",
+ "GET /api/public/metrics/daily",
+ ].forEach((route) => expect(clickhouseQuery?.query).toContain(route));
+
+ [
+ "GET /api/public/traces/{id}",
+ "GET /api/public/sessions/{id}",
+ "GET /api/public/observations/{id}",
+ "GET /api/public/scores/{id}",
+ "GET /api/public/v2/scores/{id}",
+ ].forEach((route) => expect(clickhouseQuery?.query).toContain(route));
+
+ expect(clickhouseQuery?.query).toContain(
+ "'GET /api/public/traces',\n 'GET /api/public/observations',\n 'GET /api/public/scores',\n 'GET /api/public/v2/scores',\n 'GET /api/public/metrics/daily'\n ), 2",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "'GET /api/public/sessions',\n 'GET /api/public/metrics'\n ), 1",
+ );
+ expect(clickhouseQuery?.query).toContain(
+ "match(route_path, '^GET /api/public/traces/[^/?#]+$'), 3",
+ );
+ });
+});
diff --git a/web/src/features/v4/server/v4TransitionRouter.ts b/web/src/features/v4/server/v4TransitionRouter.ts
new file mode 100644
index 0000000000..3b5136cad3
--- /dev/null
+++ b/web/src/features/v4/server/v4TransitionRouter.ts
@@ -0,0 +1,149 @@
+import { z } from "zod/v4";
+import { type IntervalUnit } from "@/src/utils/date-range-utils";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ convertDateToClickhouseDateTime,
+ queryClickhouse,
+ systemTableRef,
+} from "@langfuse/shared/src/server";
+
+const intervalUnitSchema = z.enum([
+ "second",
+ "minute",
+ "hour",
+ "day",
+ "month",
+ "year",
+] satisfies [IntervalUnit, ...IntervalUnit[]]);
+
+const intervalUnitSql: Record<IntervalUnit, string> = {
+ second: "SECOND",
+ minute: "MINUTE",
+ hour: "HOUR",
+ day: "DAY",
+ month: "MONTH",
+ year: "YEAR",
+};
+
+type LegacyApiUsageRow = {
+ time: string;
+ entrypoint: string;
+ count: string | number;
+};
+
+export const v4TransitionRouter = createTRPCRouter({
+ timeSeriesByEntrypoint: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ fromTimestamp: z.date(),
+ toTimestamp: z.date(),
+ interval: z.object({
+ count: z.number().int().positive().max(10_000),
+ unit: intervalUnitSchema,
+ }),
+ }),
+ )
+ .query(async ({ input }) => {
+ const intervalSql = `${input.interval.count} ${
+ intervalUnitSql[input.interval.unit]
+ }`;
+
+ const rows = await queryClickhouse<LegacyApiUsageRow>({
+ query: `
+WITH selected AS (
+ SELECT
+ toStartOfInterval(event_time_microseconds, INTERVAL ${intervalSql}, 'UTC') AS bucket_time,
+ splitByChar('?', JSONExtractString(log_comment, 'route'))[1] AS route_path
+ FROM ${systemTableRef("system.query_log")}
+ WHERE
+ event_time >= {fromTimestamp: DateTime64(3)}
+ AND event_time <= {toTimestamp: DateTime64(3)}
+ AND event_date >= toDate({fromTimestamp: DateTime64(3)})
+ AND event_date <= toDate({toTimestamp: DateTime64(3)})
+ AND type = 'QueryFinish'
+ AND JSONExtractString(log_comment, 'tag_schema_version') = '1'
+ AND JSONExtractString(log_comment, 'surface') = 'publicapi'
+ AND JSONExtractString(log_comment, 'projectId') = {projectId: String}
+),
+classified AS (
+ SELECT
+ bucket_time,
+ multiIf(
+ route_path IN (
+ 'GET /api/public/spans',
+ 'GET /api/public/generations',
+ 'GET /api/public/traces',
+ 'GET /api/public/sessions',
+ 'GET /api/public/observations',
+ 'GET /api/public/scores',
+ 'GET /api/public/v2/scores',
+ 'GET /api/public/metrics',
+ 'GET /api/public/metrics/daily'
+ ), route_path,
+ match(route_path, '^GET /api/public/traces/[^/?#]+$'), 'GET /api/public/traces/{id}',
+ match(route_path, '^GET /api/public/sessions/[^/?#]+$'), 'GET /api/public/sessions/{id}',
+ match(route_path, '^GET /api/public/observations/[^/?#]+$'), 'GET /api/public/observations/{id}',
+ match(route_path, '^GET /api/public/scores/[^/?#]+$'), 'GET /api/public/scores/{id}',
+ match(route_path, '^GET /api/public/v2/scores/[^/?#]+$'), 'GET /api/public/v2/scores/{id}',
+ NULL
+ ) AS legacy_route,
+ multiIf(
+ route_path IN (
+ 'GET /api/public/spans',
+ 'GET /api/public/generations',
+ 'GET /api/public/traces',
+ 'GET /api/public/observations',
+ 'GET /api/public/scores',
+ 'GET /api/public/v2/scores',
+ 'GET /api/public/metrics/daily'
+ ), 2,
+ route_path IN (
+ 'GET /api/public/sessions',
+ 'GET /api/public/metrics'
+ ), 1,
+ match(route_path, '^GET /api/public/traces/[^/?#]+$'), 3,
+ match(route_path, '^GET /api/public/sessions/[^/?#]+$'), 1,
+ match(route_path, '^GET /api/public/observations/[^/?#]+$'), 1,
+ match(route_path, '^GET /api/public/scores/[^/?#]+$'), 1,
+ match(route_path, '^GET /api/public/v2/scores/[^/?#]+$'), 1,
+ NULL
+ ) AS clickhouse_queries_per_api_call
+ FROM selected
+)
+
+SELECT
+ formatDateTime(bucket_time, '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS time,
+ concat('publicapi: ', legacy_route) AS entrypoint,
+ sum(1.0 / clickhouse_queries_per_api_call) AS count
+FROM classified
+WHERE legacy_route IS NOT NULL
+ AND clickhouse_queries_per_api_call IS NOT NULL
+GROUP BY bucket_time, legacy_route
+ORDER BY bucket_time ASC, legacy_route ASC
+ `,
+ params: {
+ projectId: input.projectId,
+ fromTimestamp: convertDateToClickhouseDateTime(input.fromTimestamp),
+ toTimestamp: convertDateToClickhouseDateTime(input.toTimestamp),
+ },
+ tags: {
+ projectId: input.projectId,
+ route: "v4-legacy-api-usage",
+ },
+ preferredClickhouseService: "ReadOnly",
+ clickhouseSettings: {
+ skip_unavailable_shards: 1,
+ },
+ });
+
+ return rows.map((row) => ({
+ time: row.time,
+ entrypoint: row.entrypoint,
+ count: Number(row.count),
+ }));
+ }),
+});
diff --git a/web/src/pages/project/[projectId]/v4/index.tsx b/web/src/pages/project/[projectId]/v4/index.tsx
new file mode 100644
index 0000000000..d5482285ce
--- /dev/null
+++ b/web/src/pages/project/[projectId]/v4/index.tsx
@@ -0,0 +1,153 @@
+import { useMemo } from "react";
+import { useRouter } from "next/router";
+import { ExternalLink } from "lucide-react";
+import Page from "@/src/components/layouts/page";
+import { TimeRangePicker } from "@/src/components/date-picker";
+import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
+import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
+import { Chart } from "@/src/features/widgets/chart-library/Chart";
+import {
+ DASHBOARD_AGGREGATION_OPTIONS,
+ getOptimalInterval,
+ toAbsoluteTimeRange,
+} from "@/src/utils/date-range-utils";
+import { useDashboardDateRange } from "@/src/hooks/useDashboardDateRange";
+import { api } from "@/src/utils/api";
+
+const UPGRADE_DOCS = [
+ {
+ label: "V4 upgrade guide",
+ href: "https://langfuse.com/docs/v4",
+ },
+ {
+ label: "Observations API v2",
+ href: "https://langfuse.com/docs/api-and-data-platform/features/observations-api#v2",
+ },
+ {
+ label: "Metrics API v2",
+ href: "https://langfuse.com/docs/metrics/features/metrics-api#v2",
+ },
+] as const;
+
+export default function V4Page() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string | undefined;
+ const { timeRange, setTimeRange } = useDashboardDateRange();
+
+ const absoluteTimeRange = useMemo(() => {
+ return (
+ toAbsoluteTimeRange(timeRange) ?? {
+ from: new Date(Date.now() - 24 * 60 * 60 * 1000),
+ to: new Date(),
+ }
+ );
+ }, [timeRange]);
+
+ const interval = useMemo(
+ () => getOptimalInterval(absoluteTimeRange.from, absoluteTimeRange.to),
+ [absoluteTimeRange.from, absoluteTimeRange.to],
+ );
+
+ const legacyApiUsage = api.v4Transition.timeSeriesByEntrypoint.useQuery(
+ {
+ projectId: projectId ?? "",
+ fromTimestamp: absoluteTimeRange.from,
+ toTimestamp: absoluteTimeRange.to,
+ interval,
+ },
+ {
+ enabled: Boolean(projectId),
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const chartData = useMemo(
+ () =>
+ legacyApiUsage.data?.map((row) => ({
+ time_dimension: row.time,
+ dimension: row.entrypoint,
+ metric: row.count,
+ })) ?? [],
+ [legacyApiUsage.data],
+ );
+
+ return (
+ <Page
+ withPadding
+ scrollable
+ headerProps={{
+ title: "V4",
+ breadcrumb: [{ name: "Home", href: `/project/${projectId}` }],
+ actionButtonsLeft: (
+ <TimeRangePicker
+ timeRange={timeRange}
+ onTimeRangeChange={setTimeRange}
+ timeRangePresets={DASHBOARD_AGGREGATION_OPTIONS}
+ className="my-0 max-w-full overflow-x-auto"
+ />
+ ),
+ }}
+ >
+ <div className="mx-auto flex w-full max-w-screen-xl flex-col gap-3">
+ <section className="flex flex-col gap-2">
+ <h4 className="text-base font-semibold">legacy api usage</h4>
+ <div className="flex flex-wrap gap-2">
+ {UPGRADE_DOCS.map((doc) => (
+ <a
+ key={doc.href}
+ href={doc.href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="border-border hover:bg-muted inline-flex h-8 items-center gap-1 rounded-md border px-2 text-sm"
+ >
+ {doc.label}
+ <ExternalLink className="h-3.5 w-3.5" />
+ </a>
+ ))}
+ </div>
+ <p className="text-muted-foreground text-sm">
+ We do not have query-log data for GET /api/public/sessions because
+ that endpoint does not execute ClickHouse queries.
+ </p>
+ </section>
+
+ <DashboardCard
+ title="Legacy API usage by entrypoint over time"
+ description="Estimates ClickHouse-backed legacy public API calls for this project."
+ isLoading={legacyApiUsage.isPending}
+ cardContentClassName="min-h-[32rem]"
+ >
+ {legacyApiUsage.error ? (
+ <div className="border-destructive/30 bg-destructive/10 text-destructive flex min-h-36 items-center rounded-md border p-4 text-sm">
+ Failed to load legacy API usage.
+ </div>
+ ) : chartData.length > 0 ? (
+ <div className="h-[30rem] w-full">
+ <Chart
+ chartType="BAR_TIME_SERIES"
+ data={chartData}
+ rowLimit={1_000}
+ chartConfig={{
+ type: "BAR_TIME_SERIES",
+ unit: "short",
+ }}
+ overrideWarning
+ />
+ </div>
+ ) : (
+ <NoDataOrLoading
+ isLoading={legacyApiUsage.isPending}
+ description="No ClickHouse-backed legacy public API usage was found for this project in the selected time range."
+ href="https://langfuse.com/docs/v4"
+ className="min-h-[30rem]"
+ />
+ )}
+ </DashboardCard>
+ </div>
+ </Page>
+ );
+}
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index ee4da42661..67a4acc23e 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -60,6 +60,7 @@ import { notificationPreferencesRouter } from "@/src/server/api/routers/notifica
import { onboardingRouter } from "@/src/features/onboarding/server/onboardingRouter";
import { webCalloutsRouter } from "@/src/features/web-callouts/server/router";
import { inAppAgentRouter } from "@/src/ee/features/in-app-agent/server/router";
+import { v4TransitionRouter } from "@/src/features/v4/server/v4TransitionRouter";
/**
* This is the primary router for your server.
@@ -128,6 +129,7 @@ export const appRouter = createTRPCRouter({
notificationPreferences: notificationPreferencesRouter,
webCallouts: webCalloutsRouter,
inAppAgent: inAppAgentRouter,
+ v4Transition: v4TransitionRouter,
});
// export type definition of API