Skip to content

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

feat(v4): attribute deprecated API callers (#16670)

Hassieb Pakzad80685e703f6a
diff --git a/packages/shared/src/server/clickhouse/queryTags.ts b/packages/shared/src/server/clickhouse/queryTags.ts
index cac6e6c24a..d98998c3d2 100644
--- a/packages/shared/src/server/clickhouse/queryTags.ts
+++ b/packages/shared/src/server/clickhouse/queryTags.ts
@@ -16,6 +16,9 @@ export type ClickHouseQueryTags = {
surface?: ClickHouseQuerySurface | (string & {});
route?: string;
projectId?: string;
+ sdkName?: "python" | "javascript";
+ sdkVersion?: string;
+ userAgent?: string;
};
export type NormalizedClickHouseQueryTags = {
@@ -23,12 +26,18 @@ export type NormalizedClickHouseQueryTags = {
surface: ClickHouseQuerySurface | typeof UNKNOWN_CLICKHOUSE_QUERY_TAG_VALUE;
route?: string;
projectId?: string;
+ sdkName?: "python" | "javascript";
+ sdkVersion?: string;
+ userAgent?: string;
};
export const CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS = {
surface: "langfuse.clickhouse.surface",
route: "langfuse.clickhouse.route",
projectId: "langfuse.project.id",
+ sdkName: "langfuse.clickhouse.sdk_name",
+ sdkVersion: "langfuse.clickhouse.sdk_version",
+ userAgent: "langfuse.clickhouse.user_agent",
} as const;
const surfaceSet = new Set<string>(clickHouseQuerySurfaces);
@@ -52,7 +61,23 @@ export function normalizeClickHouseQueryTags(
const projectId =
providedTags?.projectId ??
baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.projectId)?.value;
+ const sdkName =
+ providedTags?.sdkName ??
+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkName)?.value;
+ const sdkVersion =
+ providedTags?.sdkVersion ??
+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkVersion)?.value;
+ const userAgent =
+ providedTags?.userAgent ??
+ baggage?.getEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.userAgent)?.value;
const normalizedRoute = typeof route === "string" ? route.trim() : "";
+ const normalizedSdkName =
+ sdkName === "python" || sdkName === "javascript" ? sdkName : undefined;
+ const normalizedSdkVersion =
+ typeof sdkVersion === "string" ? sdkVersion.trim() : "";
+ const normalizedUserAgent =
+ typeof userAgent === "string" ? userAgent.trim() : "";
+ const isPublicApi = surface === "publicapi";
return {
tag_schema_version: CLICKHOUSE_QUERY_TAG_SCHEMA_VERSION,
@@ -61,6 +86,13 @@ export function normalizeClickHouseQueryTags(
: UNKNOWN_CLICKHOUSE_QUERY_TAG_VALUE,
...(normalizedRoute ? { route: normalizedRoute } : {}),
...(projectId ? { projectId } : {}),
+ ...(isPublicApi && normalizedSdkName ? { sdkName: normalizedSdkName } : {}),
+ ...(isPublicApi && normalizedSdkVersion
+ ? { sdkVersion: normalizedSdkVersion }
+ : {}),
+ ...(isPublicApi && normalizedUserAgent
+ ? { userAgent: normalizedUserAgent }
+ : {}),
};
}
diff --git a/packages/shared/src/server/headerPropagation.ts b/packages/shared/src/server/headerPropagation.ts
index 2c663f8694..e76756b924 100644
--- a/packages/shared/src/server/headerPropagation.ts
+++ b/packages/shared/src/server/headerPropagation.ts
@@ -5,6 +5,7 @@ import {
CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS,
type ClickHouseQuerySurface,
} from "./clickhouse/queryTags";
+import { extractPublicApiCallerAttribution } from "./ingestion/ingestionAttribution";
export type LangfuseContextProps = {
headers?: IncomingHttpHeaders;
@@ -30,6 +31,16 @@ export const contextWithLangfuseProps = (
opentelemetry.propagation.getBaggage(ctx) ??
opentelemetry.propagation.createBaggage();
+ if (props.clickhouse?.surface === "publicapi") {
+ [
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkName,
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkVersion,
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.userAgent,
+ ].forEach((key) => {
+ baggage = baggage.removeEntry(key);
+ });
+ }
+
if (props.headers) {
(env.LANGFUSE_LOG_PROPAGATED_HEADERS as string[]).forEach((name) => {
const value = props.headers![name];
@@ -54,6 +65,31 @@ export const contextWithLangfuseProps = (
});
}
});
+
+ if (props.clickhouse?.surface === "publicapi") {
+ const callerAttribution = extractPublicApiCallerAttribution(
+ props.headers,
+ );
+ if (callerAttribution.sdkName) {
+ baggage = baggage.setEntry(CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkName, {
+ value: callerAttribution.sdkName,
+ });
+ }
+ if (callerAttribution.sdkVersion) {
+ baggage = baggage.setEntry(
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkVersion,
+ { value: callerAttribution.sdkVersion },
+ );
+ }
+ if (callerAttribution.userAgent) {
+ baggage = baggage.setEntry(
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.userAgent,
+ {
+ value: callerAttribution.userAgent,
+ },
+ );
+ }
+ }
}
if (props.userId) {
baggage = baggage.setEntry("langfuse.user.id", { value: props.userId });
diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.test.ts b/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
index d81affdb00..ed74bcc8d2 100644
--- a/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
+++ b/packages/shared/src/server/ingestion/ingestionAttribution.test.ts
@@ -6,6 +6,7 @@ import {
classifyIngestionSdkVersion,
createIngestionAttribution,
createUnknownSdkIngestionAttribution,
+ extractPublicApiCallerAttribution,
UNKNOWN_INGESTION_SDK_VALUE,
} from "./ingestionAttribution";
@@ -19,6 +20,47 @@ const authCheck = {
} as AuthHeaderValidVerificationResult;
describe("ingestion attribution", () => {
+ it("reuses ingestion SDK normalization for public API caller attribution", () => {
+ expect(
+ extractPublicApiCallerAttribution({
+ x_langfuse_sdk_name: "langfuse-python",
+ x_langfuse_sdk_version: "4.8.1rc1",
+ "user-agent": "Codex CLI/1.2.3\nignored",
+ }),
+ ).toEqual({
+ sdkName: "python",
+ sdkVersion: "4.8.1rc1",
+ userAgent: "Codex CLI/1.2.3ignored",
+ });
+ });
+
+ it("bounds caller-controlled attribution and drops invalid SDK metadata", () => {
+ expect(
+ extractPublicApiCallerAttribution({
+ "x-langfuse-sdk-name": "ruby",
+ "x-langfuse-sdk-version": "1.0.0",
+ "user-agent": `curl/${"x".repeat(300)}`,
+ }),
+ ).toEqual({
+ userAgent: `curl/${"x".repeat(251)}`,
+ });
+
+ expect(
+ extractPublicApiCallerAttribution({
+ "x-langfuse-sdk-name": "python",
+ "x-langfuse-sdk-version": "not-a-version",
+ }),
+ ).toEqual({ sdkName: "python" });
+ });
+
+ it("does not split a Unicode code point at the attribution length bound", () => {
+ expect(
+ extractPublicApiCallerAttribution({
+ "user-agent": `${"x".repeat(255)}😀truncated`,
+ }),
+ ).toEqual({ userAgent: `${"x".repeat(255)}😀` });
+ });
+
it("reads SDK attribution from Langfuse request headers", () => {
expect(
createIngestionAttribution({
@@ -35,6 +77,22 @@ describe("ingestion attribution", () => {
});
});
+ it("matches Langfuse request header names case-insensitively", () => {
+ expect(
+ createIngestionAttribution({
+ headers: {
+ "X-Langfuse-Sdk-Name": "python",
+ "X-Langfuse-Sdk-Version": "4.8.1",
+ },
+ authCheck,
+ }),
+ ).toEqual({
+ ingestionApiKey: "pk-lf-public",
+ ingestionSdkName: "python",
+ ingestionSdkVersion: "4.8.1",
+ });
+ });
+
it("reads SDK attribution from underscore header variants", () => {
expect(
createIngestionAttribution({
diff --git a/packages/shared/src/server/ingestion/ingestionAttribution.ts b/packages/shared/src/server/ingestion/ingestionAttribution.ts
index 0fe180c21c..681fd2fd72 100644
--- a/packages/shared/src/server/ingestion/ingestionAttribution.ts
+++ b/packages/shared/src/server/ingestion/ingestionAttribution.ts
@@ -44,6 +44,15 @@ export type IngestionSdkAttributionStatus =
| "missing_version"
| "missing_name_and_version";
+export type PublicApiCallerAttribution = {
+ sdkName?: IngestionSdkCanonicalName;
+ sdkVersion?: string;
+ userAgent?: string;
+};
+
+export const PUBLIC_API_SDK_VERSION_MAX_LENGTH = 64;
+export const PUBLIC_API_USER_AGENT_MAX_LENGTH = 256;
+
const getHeaderValue = (
headers: IngestionHeaderMap | undefined,
name: string,
@@ -56,6 +65,14 @@ const getHeaderValue = (
const underscoreValue = headers[name.replaceAll("-", "_")];
if (typeof underscoreValue === "string") return underscoreValue;
+ const normalizedName = name.toLowerCase().replaceAll("_", "-");
+ const matchedValue = Object.entries(headers).find(
+ ([headerName, value]) =>
+ typeof value === "string" &&
+ headerName.toLowerCase().replaceAll("_", "-") === normalizedName,
+ )?.[1];
+ if (typeof matchedValue === "string") return matchedValue;
+
return "";
};
@@ -185,6 +202,57 @@ export const classifyIngestionSdkAttribution = (params: {
return "attributed";
};
+const sanitizeCallerAttributionValue = (
+ value: string,
+ maxLength: number,
+): string | undefined => {
+ const sanitized = Array.from(value)
+ .filter((character) => {
+ const codePoint = character.codePointAt(0) ?? 0;
+ return codePoint > 31 && codePoint !== 127;
+ })
+ .join("")
+ .trim();
+ const bounded = Array.from(sanitized).slice(0, maxLength).join("");
+ return bounded || undefined;
+};
+
+/**
+ * Extracts the bounded, allowlisted caller metadata shared by public API
+ * telemetry and ClickHouse query attribution. SDK parsing intentionally
+ * reuses the ingestion pipeline's header and version normalization.
+ */
+export const extractPublicApiCallerAttribution = (
+ headers: IngestionHeaderMap | undefined,
+): PublicApiCallerAttribution => {
+ const sdkName = normalizeIngestionSdkName(
+ getHeaderValue(headers, "x-langfuse-sdk-name"),
+ );
+ const rawSdkVersion = sanitizeCallerAttributionValue(
+ getHeaderValue(headers, "x-langfuse-sdk-version"),
+ PUBLIC_API_SDK_VERSION_MAX_LENGTH,
+ );
+ const sdkVersionClassification = classifyIngestionSdkVersion({
+ sdkName,
+ sdkVersion: rawSdkVersion,
+ });
+ const sdkVersion =
+ sdkVersionClassification.status === "current" ||
+ sdkVersionClassification.status === "outdated_major"
+ ? rawSdkVersion
+ : undefined;
+ const userAgent = sanitizeCallerAttributionValue(
+ getHeaderValue(headers, "user-agent"),
+ PUBLIC_API_USER_AGENT_MAX_LENGTH,
+ );
+
+ return {
+ ...(sdkName ? { sdkName } : {}),
+ ...(sdkVersion ? { sdkVersion } : {}),
+ ...(userAgent ? { userAgent } : {}),
+ };
+};
+
export const createIngestionAttribution = (params: {
headers?: IngestionHeaderMap;
authCheck: AuthHeaderValidVerificationResult;
diff --git a/packages/shared/src/server/instrumentation/bootstrap/sdkName.test.ts b/packages/shared/src/server/instrumentation/bootstrap/sdkName.test.ts
index 27536a5eac..e4f3caae76 100644
--- a/packages/shared/src/server/instrumentation/bootstrap/sdkName.test.ts
+++ b/packages/shared/src/server/instrumentation/bootstrap/sdkName.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
-import { SDK_NAME_HEADER, extractSdkName } from "./sdkName";
+import {
+ SDK_NAME_HEADER,
+ SDK_VERSION_HEADER,
+ extractSdkAttributes,
+ extractSdkName,
+} from "./sdkName";
describe("extractSdkName", () => {
it("canonicalizes first-party SDK names to the ingestion closed set", () => {
@@ -25,4 +30,22 @@ describe("extractSdkName", () => {
extractSdkName({ [SDK_NAME_HEADER]: "python, javascript" }),
).toBeUndefined();
});
+
+ it("returns canonical SDK name and validated version attributes", () => {
+ expect(
+ extractSdkAttributes({
+ [SDK_NAME_HEADER]: "langfuse-python",
+ [SDK_VERSION_HEADER]: "4.8.1rc1",
+ }),
+ ).toEqual({ sdkName: "python", sdkVersion: "4.8.1rc1" });
+ });
+
+ it("keeps a recognized SDK name when its version is invalid", () => {
+ expect(
+ extractSdkAttributes({
+ [SDK_NAME_HEADER]: "javascript",
+ [SDK_VERSION_HEADER]: "unbounded-cardinality",
+ }),
+ ).toEqual({ sdkName: "javascript" });
+ });
});
diff --git a/packages/shared/src/server/instrumentation/bootstrap/sdkName.ts b/packages/shared/src/server/instrumentation/bootstrap/sdkName.ts
index 41d3b45423..2c232f9043 100644
--- a/packages/shared/src/server/instrumentation/bootstrap/sdkName.ts
+++ b/packages/shared/src/server/instrumentation/bootstrap/sdkName.ts
@@ -1,21 +1,31 @@
import { type IncomingHttpHeaders } from "http";
-import {
- getLangfuseHeaderValue,
- normalizeIngestionSdkName,
-} from "../../ingestion/ingestionAttribution";
+import { extractPublicApiCallerAttribution } from "../../ingestion/ingestionAttribution";
export const SDK_NAME_HEADER = "x-langfuse-sdk-name";
+export const SDK_VERSION_HEADER = "x-langfuse-sdk-version";
export const SDK_NAME_ATTRIBUTE = "sdk_name";
+export const SDK_VERSION_ATTRIBUTE = "sdk_version";
+
+export type SdkAttributes = {
+ sdkName?: "python" | "javascript";
+ sdkVersion?: string;
+};
+
+export function extractSdkAttributes(
+ headers: IncomingHttpHeaders,
+): SdkAttributes {
+ const { sdkName, sdkVersion } = extractPublicApiCallerAttribution(headers);
+ return {
+ ...(sdkName ? { sdkName } : {}),
+ ...(sdkVersion ? { sdkVersion } : {}),
+ };
+}
/** extractSdkName canonicalizes the request's SDK-name header to the ingestion closed set, or undefined. */
export function extractSdkName(
headers: IncomingHttpHeaders,
): string | undefined {
- return (
- normalizeIngestionSdkName(
- getLangfuseHeaderValue(headers, SDK_NAME_HEADER),
- ) ?? undefined
- );
+ return extractSdkAttributes(headers).sdkName;
}
diff --git a/packages/shared/src/server/instrumentation/index.test.ts b/packages/shared/src/server/instrumentation/index.test.ts
index e7f1cb316c..69019cdb77 100644
--- a/packages/shared/src/server/instrumentation/index.test.ts
+++ b/packages/shared/src/server/instrumentation/index.test.ts
@@ -6,7 +6,10 @@ import {
} from "@opentelemetry/api";
import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
-import { normalizeClickHouseQueryTags } from "../clickhouse/queryTags";
+import {
+ CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS,
+ normalizeClickHouseQueryTags,
+} from "../clickhouse/queryTags";
import { contextWithLangfuseProps } from "../headerPropagation";
import { addUserToSpan, instrumentAsync, instrumentSync } from ".";
@@ -62,6 +65,74 @@ describe("instrumentation baggage propagation", () => {
});
});
+ it("propagates bounded public API caller attribution into ClickHouse tags", () => {
+ const publicApiContext = contextWithLangfuseProps({
+ headers: {
+ "x-langfuse-sdk-name": "langfuse-python",
+ "x-langfuse-sdk-version": "4.8.1",
+ "user-agent": "Codex CLI/1.2.3",
+ },
+ projectId: "project-1",
+ clickhouse: {
+ surface: "publicapi",
+ route: "GET /api/public/traces",
+ },
+ });
+
+ const tags = context.with(publicApiContext, () =>
+ normalizeClickHouseQueryTags(),
+ );
+
+ expect(tags).toMatchObject({
+ surface: "publicapi",
+ route: "GET /api/public/traces",
+ projectId: "project-1",
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "Codex CLI/1.2.3",
+ });
+ expect(tags).not.toHaveProperty("apiKeyId");
+ });
+
+ it("rejects public API caller attribution inherited from inbound baggage", () => {
+ const inboundContext = propagation.setBaggage(
+ ROOT_CONTEXT,
+ propagation.createBaggage({
+ [CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkName]: { value: "python" },
+ [CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.sdkVersion]: {
+ value: "attacker-controlled-version",
+ },
+ [CLICKHOUSE_QUERY_TAG_BAGGAGE_KEYS.userAgent]: {
+ value: "attacker-controlled-user-agent",
+ },
+ }),
+ );
+
+ const tags = context.with(inboundContext, () => {
+ const publicApiContext = contextWithLangfuseProps({
+ headers: {},
+ projectId: "project-1",
+ clickhouse: {
+ surface: "publicapi",
+ route: "GET /api/public/traces",
+ },
+ });
+
+ return context.with(publicApiContext, () =>
+ normalizeClickHouseQueryTags(),
+ );
+ });
+
+ expect(tags).toMatchObject({
+ surface: "publicapi",
+ route: "GET /api/public/traces",
+ projectId: "project-1",
+ });
+ expect(tags).not.toHaveProperty("sdkName");
+ expect(tags).not.toHaveProperty("sdkVersion");
+ expect(tags).not.toHaveProperty("userAgent");
+ });
+
it("does not add user emails to span attributes or baggage", () => {
const span = {
setAttribute: vi.fn(),
diff --git a/packages/shared/src/server/v4/legacyApiUsage.test.ts b/packages/shared/src/server/v4/legacyApiUsage.test.ts
index 7a5d40a879..edc79157cb 100644
--- a/packages/shared/src/server/v4/legacyApiUsage.test.ts
+++ b/packages/shared/src/server/v4/legacyApiUsage.test.ts
@@ -1,9 +1,66 @@
import { describe, expect, it } from "vitest";
import {
+ aggregateV4LegacyApiHourBuckets,
+ MAX_V4_LEGACY_API_CALLERS_PER_ENDPOINT,
+ mergeV4LegacyApiCallers,
V4_LEGACY_API_HOUR_BUCKET_TTL_SECONDS,
v4LegacyApiHourBucketTtlSeconds,
} from "./legacyApiUsage";
+describe("mergeV4LegacyApiCallers", () => {
+ it("bounds caller cardinality and preserves the overflow total", () => {
+ const callers = Array.from({ length: 25 }, (_, index) => ({
+ userAgent: `caller-${index}`,
+ count: index + 1,
+ lastSeen: `2026-07-23T${String(index % 24).padStart(2, "0")}:00:00Z`,
+ }));
+
+ const merged = mergeV4LegacyApiCallers(callers);
+
+ expect(merged).toHaveLength(MAX_V4_LEGACY_API_CALLERS_PER_ENDPOINT);
+ expect(merged.at(-1)).toMatchObject({ isOther: true });
+ expect(merged.reduce((sum, caller) => sum + caller.count, 0)).toBe(325);
+ });
+
+ it("can retain raw hour-bucket callers until the final rollup", () => {
+ const callers = Array.from({ length: 25 }, (_, index) => ({
+ userAgent: `caller-${index}`,
+ count: 1,
+ lastSeen: "2026-07-23T10:00:00Z",
+ }));
+
+ expect(mergeV4LegacyApiCallers(callers, { maxCallers: null })).toHaveLength(
+ 25,
+ );
+ });
+
+ it("keeps one overflow bucket when a capped rollup is merged again", () => {
+ const callers = [
+ ...Array.from({ length: 20 }, (_, index) => ({
+ userAgent: `caller-${index}`,
+ count: 1,
+ lastSeen: "2026-07-23T10:00:00Z",
+ })),
+ {
+ isOther: true as const,
+ count: 4,
+ lastSeen: "2026-07-23T11:00:00Z",
+ },
+ ];
+
+ const merged = mergeV4LegacyApiCallers(callers);
+
+ expect(merged).toHaveLength(20);
+ expect(merged.filter((caller) => caller.isOther)).toEqual([
+ {
+ isOther: true,
+ count: 5,
+ lastSeen: "2026-07-23T11:00:00Z",
+ },
+ ]);
+ });
+});
+
describe("v4LegacyApiHourBucketTtlSeconds", () => {
const HOUR_MS = 60 * 60 * 1000;
const nowMs = Date.parse("2026-06-25T00:30:00.000Z");
@@ -31,3 +88,114 @@ describe("v4LegacyApiHourBucketTtlSeconds", () => {
expect(v4LegacyApiHourBucketTtlSeconds(hourStartMs, nowMs)).toBe(1);
});
});
+
+describe("aggregateV4LegacyApiHourBuckets", () => {
+ it("applies the caller cap only after all hour buckets are merged", () => {
+ const rollup = aggregateV4LegacyApiHourBuckets(
+ Array.from({ length: 3 }, (_, hour) => ({
+ version: 1 as const,
+ computedAt: `2026-06-24T0${hour}:30:00.000Z`,
+ apiRows: [
+ {
+ projectId: "project-1",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 209,
+ lastSeen: `2026-06-24T0${hour}:15:00.000Z`,
+ callers: [
+ ...Array.from({ length: 20 }, (_, index) => ({
+ userAgent: `hour-${hour}-caller-${index}`,
+ count: 10,
+ lastSeen: `2026-06-24T0${hour}:10:00.000Z`,
+ })),
+ {
+ userAgent: "steady-caller",
+ count: 9,
+ lastSeen: `2026-06-24T0${hour}:15:00.000Z`,
+ },
+ ],
+ },
+ ],
+ experimentPostRows: [],
+ })),
+ );
+
+ const callers = rollup.apiRowsByProjectId.get("project-1")?.[0]?.callers;
+ expect(callers).toHaveLength(MAX_V4_LEGACY_API_CALLERS_PER_ENDPOINT);
+ expect(callers).toContainEqual(
+ expect.objectContaining({ userAgent: "steady-caller", count: 27 }),
+ );
+ expect(callers?.filter((caller) => caller.isOther)).toHaveLength(1);
+ expect(callers?.reduce((sum, caller) => sum + caller.count, 0)).toBe(627);
+ });
+
+ it("keeps one endpoint total while preserving attributed and historical callers", () => {
+ const rollup = aggregateV4LegacyApiHourBuckets([
+ {
+ version: 1,
+ computedAt: "2026-06-24T00:00:00.000Z",
+ apiRows: [
+ {
+ projectId: "project-1",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 2,
+ lastSeen: "2026-06-24T10:00:00.000Z",
+ },
+ ],
+ experimentPostRows: [],
+ },
+ {
+ version: 1,
+ computedAt: "2026-06-25T00:00:00.000Z",
+ apiRows: [
+ {
+ projectId: "project-1",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 3,
+ lastSeen: "2026-06-25T10:00:00.000Z",
+ callers: [
+ {
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ lastSeen: "2026-06-25T10:00:00.000Z",
+ },
+ {
+ userAgent: "Codex CLI/1.2.3",
+ count: 1,
+ lastSeen: "2026-06-25T09:00:00.000Z",
+ },
+ ],
+ },
+ ],
+ experimentPostRows: [],
+ },
+ ]);
+
+ expect(rollup.apiRowsByProjectId.get("project-1")).toEqual([
+ expect.objectContaining({
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 5,
+ lastSeen: "2026-06-25T10:00:00.000Z",
+ callers: expect.arrayContaining([
+ {
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ lastSeen: "2026-06-25T10:00:00.000Z",
+ },
+ {
+ userAgent: "Codex CLI/1.2.3",
+ count: 1,
+ lastSeen: "2026-06-25T09:00:00.000Z",
+ },
+ {
+ count: 2,
+ lastSeen: "2026-06-24T10:00:00.000Z",
+ },
+ ]),
+ }),
+ ]);
+ });
+});
diff --git a/packages/shared/src/server/v4/legacyApiUsage.ts b/packages/shared/src/server/v4/legacyApiUsage.ts
index 9ec1d1ac49..1d72cf2be1 100644
--- a/packages/shared/src/server/v4/legacyApiUsage.ts
+++ b/packages/shared/src/server/v4/legacyApiUsage.ts
@@ -113,10 +113,24 @@ export const v4LegacyApiUsageProjectKey = (projectId: string): string =>
export const v4ExperimentPostUsageProjectKey = (projectId: string): string =>
`langfuse:v4:experiment-post-usage:v1:${projectId}`;
+const legacyApiCallerSchema = z.object({
+ sdkName: z.enum(["python", "javascript"]).optional(),
+ sdkVersion: z.string().optional(),
+ userAgent: z.string().optional(),
+ count: z.number(),
+ lastSeen: z.string(),
+ isOther: z.literal(true).optional(),
+});
+
+export type V4LegacyApiCaller = z.infer<typeof legacyApiCallerSchema>;
+
+export const MAX_V4_LEGACY_API_CALLERS_PER_ENDPOINT = 20;
+
const legacyApiUsageRowSchema = z.object({
entrypoint: z.string(),
count: z.number(),
lastSeen: z.string(),
+ callers: z.array(legacyApiCallerSchema).optional(),
});
export type V4LegacyApiUsageRow = z.infer<typeof legacyApiUsageRowSchema>;
@@ -213,6 +227,82 @@ export type V4LegacyApiUsageRollup = {
experimentPostLastSeenByProjectId: Map<string, string | null>;
};
+const legacyApiCallerKey = (caller: V4LegacyApiCaller): string =>
+ caller.isOther
+ ? "other"
+ : [
+ caller.sdkName ?? "",
+ caller.sdkVersion ?? "",
+ caller.userAgent ?? "",
+ ].join("\u0000");
+
+export const mergeV4LegacyApiCallers = (
+ callers: V4LegacyApiCaller[],
+ options: { maxCallers?: number | null } = {},
+): V4LegacyApiCaller[] => {
+ const merged = new Map<string, V4LegacyApiCaller>();
+ let otherCaller: V4LegacyApiCaller | undefined;
+ for (const caller of callers) {
+ if (caller.isOther) {
+ otherCaller = otherCaller
+ ? {
+ isOther: true,
+ count: otherCaller.count + caller.count,
+ lastSeen:
+ otherCaller.lastSeen > caller.lastSeen
+ ? otherCaller.lastSeen
+ : caller.lastSeen,
+ }
+ : caller;
+ continue;
+ }
+ const key = legacyApiCallerKey(caller);
+ const existing = merged.get(key);
+ merged.set(
+ key,
+ existing
+ ? {
+ ...existing,
+ count: existing.count + caller.count,
+ lastSeen:
+ existing.lastSeen > caller.lastSeen
+ ? existing.lastSeen
+ : caller.lastSeen,
+ }
+ : caller,
+ );
+ }
+
+ const sorted = Array.from(merged.values()).sort(
+ (left, right) =>
+ right.count - left.count ||
+ right.lastSeen.localeCompare(left.lastSeen) ||
+ legacyApiCallerKey(left).localeCompare(legacyApiCallerKey(right)),
+ );
+ const maxCallers =
+ options.maxCallers === null
+ ? null
+ : (options.maxCallers ?? MAX_V4_LEGACY_API_CALLERS_PER_ENDPOINT);
+ if (maxCallers === null) {
+ return otherCaller ? [...sorted, otherCaller] : sorted;
+ }
+ if (!otherCaller && sorted.length <= maxCallers) return sorted;
+
+ const kept = sorted.slice(0, maxCallers - 1);
+ const overflow = sorted.slice(maxCallers - 1);
+ kept.push({
+ isOther: true,
+ count:
+ (otherCaller?.count ?? 0) +
+ overflow.reduce((sum, caller) => sum + caller.count, 0),
+ lastSeen: [
+ ...(otherCaller ? [otherCaller.lastSeen] : []),
+ ...overflow.map((caller) => caller.lastSeen),
+ ].reduce((latest, lastSeen) => (latest > lastSeen ? latest : lastSeen), ""),
+ });
+ return kept;
+};
+
/**
* Aggregates hour buckets into the per-project trailing-window answer:
* counts add per entrypoint, `lastSeen` takes the maximum. Buckets carry raw
@@ -233,6 +323,10 @@ export const aggregateV4LegacyApiHourBuckets = (
rowsByProjectAndEntrypoint.get(row.projectId) ??
new Map<string, V4LegacyApiUsageRow>();
const existing = rowsByEntrypoint.get(row.entrypoint);
+ const callers =
+ row.callers && row.callers.length > 0
+ ? row.callers
+ : [{ count: row.count, lastSeen: row.lastSeen }];
rowsByEntrypoint.set(
row.entrypoint,
existing
@@ -243,11 +337,16 @@ export const aggregateV4LegacyApiHourBuckets = (
existing.lastSeen > row.lastSeen
? existing.lastSeen
: row.lastSeen,
+ callers: mergeV4LegacyApiCallers(
+ [...(existing.callers ?? []), ...callers],
+ { maxCallers: null },
+ ),
}
: {
entrypoint: row.entrypoint,
count: row.count,
lastSeen: row.lastSeen,
+ callers: mergeV4LegacyApiCallers(callers, { maxCallers: null }),
},
);
rowsByProjectAndEntrypoint.set(row.projectId, rowsByEntrypoint);
@@ -276,9 +375,12 @@ export const aggregateV4LegacyApiHourBuckets = (
for (const [projectId, rowsByEntrypoint] of rowsByProjectAndEntrypoint) {
apiRowsByProjectId.set(
projectId,
- Array.from(rowsByEntrypoint.values()).sort((left, right) =>
- left.entrypoint.localeCompare(right.entrypoint),
- ),
+ Array.from(rowsByEntrypoint.values())
+ .map((row) => ({
+ ...row,
+ callers: mergeV4LegacyApiCallers(row.callers ?? []),
+ }))
+ .sort((left, right) => left.entrypoint.localeCompare(right.entrypoint)),
);
}
diff --git a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
index 6a355ba9e5..bb452f5bcb 100644
--- a/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
+++ b/web/src/__tests__/server/unit/v4TransitionRouter.servertest.ts
@@ -485,7 +485,19 @@ const experimentPostBlob = (
});
const legacyApiBlob = (
- rows: { entrypoint: string; count: number; lastSeen: string }[],
+ rows: {
+ entrypoint: string;
+ count: number;
+ lastSeen: string;
+ callers?: {
+ sdkName?: "python" | "javascript";
+ sdkVersion?: string;
+ userAgent?: string;
+ isOther?: true;
+ count: number;
+ lastSeen: string;
+ }[];
+ }[],
) =>
JSON.stringify({
version: 1,
@@ -565,6 +577,15 @@ describe("v4TransitionRouter", () => {
entrypoint: "publicapi: GET /api/public/traces/{id}",
count: 2,
lastSeen: "2026-06-24T15:00:00.000000Z",
+ callers: [
+ {
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ lastSeen: "2026-06-24T15:00:00.000000Z",
+ },
+ ],
},
]),
});
@@ -586,6 +607,15 @@ describe("v4TransitionRouter", () => {
entrypoint: "publicapi: GET /api/public/traces/{id}",
count: 2,
lastSeen: "2026-06-24T15:00:00.000000Z",
+ callers: [
+ {
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ lastSeen: "2026-06-24T15:00:00.000000Z",
+ },
+ ],
},
]);
expect(mockedQueryClickhouse).not.toHaveBeenCalled();
diff --git a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
index 000c1757fe..0394de6cd8 100644
--- a/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.clienttest.tsx
@@ -151,7 +151,19 @@ const mocks = vi.hoisted(() => ({
count: 42,
lastSeen: "2026-07-23T10:37:00Z",
},
- ],
+ ] as {
+ endpoint: string;
+ count: number;
+ lastSeen: string;
+ callers?: {
+ sdkName?: "python" | "javascript";
+ sdkVersion?: string;
+ userAgent?: string;
+ isOther?: true;
+ count: number;
+ lastSeen: string;
+ }[];
+ }[],
legacyIntegrations: ["PostHog", "Mixpanel", "Blob Storage"],
},
canToggleV4: true,
@@ -332,10 +344,9 @@ describe("V4MigrationDetailsContent", () => {
"href",
"https://langfuse.com/faq/all/deprecated-api-migration",
);
- expect(screen.getByText(/42 calls · last seen/)).toHaveAttribute(
- "title",
- "Last seen at 2026-07-23T10:37:00Z",
- );
+ expect(
+ screen.getByTitle("Last seen at 2026-07-23T10:37:00Z"),
+ ).toHaveTextContent(/42 calls · last seen/);
const expectedIntegrationGuides = {
PostHog:
@@ -381,9 +392,78 @@ describe("V4MigrationDetailsContent", () => {
render(<V4MigrationDetailsContent projectId="project-1" />);
- expect(screen.getByText(/57 calls · last seen/)).toBeInTheDocument();
- expect(screen.getByText(/5 calls · last seen/)).toBeInTheDocument();
- expect(screen.getByText(/1 call · last seen/)).toBeInTheDocument();
+ expect(
+ screen.getByTitle("Last seen at 2026-07-23T10:37:00Z"),
+ ).toHaveTextContent(/57 calls · last seen/);
+ expect(
+ screen.getByTitle("Last seen at 2026-07-22T10:37:00Z"),
+ ).toHaveTextContent(/5 calls · last seen/);
+ expect(
+ screen.getByTitle("Last seen at 2026-07-21T10:37:00Z"),
+ ).toHaveTextContent(/1 call · last seen/);
+ });
+
+ it("shows the caller and exact SDK migration action", () => {
+ mocks.migrationData.apiUsage = [
+ {
+ endpoint: "GET /api/public/traces/{id}",
+ count: 4,
+ lastSeen: "2026-07-23T10:37:00Z",
+ callers: [
+ {
+ sdkName: "python" as const,
+ sdkVersion: "3.9.0",
+ userAgent: "langfuse-python/3.9.0",
+ count: 3,
+ lastSeen: "2026-07-23T10:37:00Z",
+ },
+ {
+ userAgent: "codex-cli/1.2.3",
+ count: 1,
+ lastSeen: "2026-07-23T10:30:00Z",
+ },
+ ],
+ },
+ ];
+
+ render(<V4MigrationDetailsContent projectId="project-1" />);
+
+ expect(screen.getByText("Langfuse Python SDK 3.9.0")).toBeInTheDocument();
+ expect(screen.getByText("client.api.trace.get(...)")).toBeInTheDocument();
+ expect(
+ screen.getByText("client.api.observations.get_many(trace_id=trace_id)"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("4.0.0 or newer")).toBeInTheDocument();
+ expect(screen.getByText("Codex")).toBeInTheDocument();
+ expect(screen.getByText(/traffic from a coding agent/)).toBeInTheDocument();
+ expect(screen.queryByText("User-Agent:")).not.toBeInTheDocument();
+ expect(
+ screen.queryByTitle("Last seen at 2026-07-23T10:37:00Z"),
+ ).not.toBeInTheDocument();
+
+ for (const callerName of ["Langfuse Python SDK 3.9.0", "Codex"]) {
+ const caller = screen.getByText(callerName).closest("li");
+ expect(caller).toHaveClass("bg-muted/50", "border-l-4", "p-2");
+ expect(caller?.firstElementChild).toHaveTextContent(callerName);
+ expect(caller?.firstElementChild).toHaveTextContent(/calls? · last seen/);
+ expect(
+ within(caller?.firstElementChild as HTMLElement).queryByRole("link"),
+ ).not.toBeInTheDocument();
+ const docsLink = within(caller!).getByRole("link", {
+ name: "See docs.",
+ });
+ expect(docsLink).toHaveAttribute(
+ "href",
+ "https://langfuse.com/faq/all/deprecated-api-migration",
+ );
+ expect(docsLink.parentElement).toHaveTextContent(/See docs\.$/);
+ }
+
+ fireEvent.click(screen.getAllByRole("link", { name: "See docs." })[0]!);
+ expect(mocks.capture).toHaveBeenCalledWith(
+ "v4_migration:section_link_clicked",
+ { section: "apis", link: "deprecated_api_caller_docs" },
+ );
});
it("collapses clean sections into one up-to-date summary", () => {
diff --git a/web/src/features/v4-migration/V4MigrationContent.tsx b/web/src/features/v4-migration/V4MigrationContent.tsx
index 20aab90152..e15a9aa9e9 100644
--- a/web/src/features/v4-migration/V4MigrationContent.tsx
+++ b/web/src/features/v4-migration/V4MigrationContent.tsx
@@ -66,6 +66,11 @@ import { api } from "@/src/utils/api";
import { encodeFiltersGeneric, type FilterState } from "@langfuse/shared";
import { EvaluatorMigrationDialog } from "@/src/features/v4-migration/EvaluatorMigrationDialog";
import { buildDeprecatedRulesUrl } from "@/src/features/v4-migration/evaluatorMigrationUrls";
+import {
+ getApiMigrationGuidance,
+ getCodingAgentName,
+ type MigrationSdkName,
+} from "@/src/features/v4-migration/apiMigrationGuidance";
// Single source of truth for the v4-migration copy and content. Both surfaces
// (side panel and modal) render these components — edit copy here only.
@@ -868,7 +873,19 @@ export function V4MigrationApisSection({
defaultOpen,
}: {
state: MigrationCountState;
- usage: { endpoint: string; count: number; lastSeen: string }[];
+ usage: {
+ endpoint: string;
+ count: number;
+ lastSeen: string;
+ callers?: {
+ sdkName?: MigrationSdkName;
+ sdkVersion?: string;
+ userAgent?: string;
+ isOther?: true;
+ count: number;
+ lastSeen: string;
+ }[];
+ }[];
defaultOpen?: boolean;
}) {
return (
@@ -907,33 +924,144 @@ export function V4MigrationApisSection({
</ExternalLink>{" "}
maps each endpoint to its replacement.
</p>
- <div className="flex flex-col">
+ <div className="flex flex-col gap-3">
{usage.map((row) => {
const roundedCount = Math.max(1, Math.round(row.count));
+ const callers = row.callers ?? [];
return (
- <div
- key={row.endpoint}
- className="text-muted-foreground flex flex-wrap items-baseline justify-between gap-x-2 py-0.5"
- >
- <ExternalLink
- href={DEPRECATED_API_MIGRATION_URL}
- className="text-sm"
- analytics={{
- section: "apis",
- link: "deprecated_api_docs",
- }}
- >
- {row.endpoint}
- </ExternalLink>
- <span
- className="text-muted-foreground text-sm whitespace-nowrap"
- title={`Last seen at ${row.lastSeen}`}
- >
- {numberFormatter(roundedCount, 0)}{" "}
- {roundedCount === 1 ? "call" : "calls"} · last seen{" "}
- {formatCompactRelativeTime(new Date(row.lastSeen))}
- </span>
+ <div key={row.endpoint} className="rounded-md border p-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-2">
+ <ExternalLink
+ href={DEPRECATED_API_MIGRATION_URL}
+ className="text-sm font-bold"
+ analytics={{
+ section: "apis",
+ link: "deprecated_api_docs",
+ }}
+ >
+ {row.endpoint}
+ </ExternalLink>
+ {callers.length === 0 ? (
+ <span
+ className="text-muted-foreground text-sm whitespace-nowrap"
+ title={`Last seen at ${row.lastSeen}`}
+ >
+ {numberFormatter(roundedCount, 0)}{" "}
+ {roundedCount === 1 ? "call" : "calls"} · last seen{" "}
+ {formatCompactRelativeTime(new Date(row.lastSeen))}
+ </span>
+ ) : null}
+ </div>
+ {callers.length > 0 ? (
+ <ul className="mt-2 flex flex-col gap-2">
+ {callers.map((caller, index) => {
+ const codingAgent = getCodingAgentName(
+ caller.userAgent,
+ );
+ const guidance = getApiMigrationGuidance(
+ row.endpoint,
+ caller.sdkName,
+ caller.sdkVersion,
+ );
+ const callerName = caller.isOther
+ ? "Unknown callers"
+ : caller.sdkName
+ ? `Langfuse ${caller.sdkName === "python" ? "Python" : "JavaScript"} SDK${caller.sdkVersion ? ` ${caller.sdkVersion}` : ""}`
+ : codingAgent
+ ? codingAgent
+ : caller.userAgent || "Unknown caller";
+ const callerCount = Math.max(
+ 1,
+ Math.round(caller.count),
+ );
+
+ return (
+ <li
+ key={`${callerName}-${index}`}
+ className="bg-muted/50 border-border rounded-md border-l-4 p-2 text-sm"
+ >
+ <div className="flex flex-wrap items-baseline justify-between gap-x-2">
+ <div className="text-muted-foreground flex items-center gap-1.5">
+ <span aria-hidden="true">⚠️</span>
+ <MonoValue>{callerName}</MonoValue>
+ </div>
+ <div className="text-muted-foreground flex flex-wrap items-baseline gap-x-1.5 pl-5 sm:pl-0">
+ <span>
+ {numberFormatter(callerCount, 0)}{" "}
+ {callerCount === 1 ? "call" : "calls"} · last
+ seen{" "}
+ {formatCompactRelativeTime(
+ new Date(caller.lastSeen),
+ )}
+ </span>
+ </div>
+ </div>
+ {codingAgent && !caller.sdkName ? (
+ <p className="text-muted-foreground mt-1 pl-5 text-xs">
+ This looks like traffic from a coding agent. If
+ the call was only exploratory and is not part of
+ a running service, you may not need to migrate
+ application code.{" "}
+ <ExternalLink
+ href={DEPRECATED_API_MIGRATION_URL}
+ analytics={{
+ section: "apis",
+ link: "deprecated_api_caller_docs",
+ }}
+ >
+ See docs.
+ </ExternalLink>
+ </p>
+ ) : guidance.currentMethod &&
+ guidance.replacementMethod ? (
+ <p className="text-muted-foreground mt-1 pl-5 text-xs">
+ Replace{" "}
+ <MonoValue>{guidance.currentMethod}</MonoValue>{" "}
+ with{" "}
+ <MonoValue>
+ {guidance.replacementMethod}
+ </MonoValue>
+ {guidance.requiresUpgrade &&
+ guidance.minimumVersion ? (
+ <>
+ . First upgrade to SDK version{" "}
+ <MonoValue>
+ {guidance.minimumVersion} or newer
+ </MonoValue>
+ </>
+ ) : null}
+ .{" "}
+ <ExternalLink
+ href={DEPRECATED_API_MIGRATION_URL}
+ analytics={{
+ section: "apis",
+ link: "deprecated_api_caller_docs",
+ }}
+ >
+ See docs.
+ </ExternalLink>
+ </p>
+ ) : (
+ <p className="text-muted-foreground mt-1 pl-5 text-xs">
+ Migrate calls to{" "}
+ <MonoValue>{guidance.replacement}</MonoValue>.{" "}
+ <ExternalLink
+ href={DEPRECATED_API_MIGRATION_URL}
+ analytics={{
+ section: "apis",
+ link: "deprecated_api_caller_docs",
+ }}
+ >
+ See docs.
+ </ExternalLink>
+ </p>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ ) : null}
</div>
);
})}
diff --git a/web/src/features/v4-migration/V4MigrationSections.stories.tsx b/web/src/features/v4-migration/V4MigrationSections.stories.tsx
index 4a1adf5909..33095d4b1d 100644
--- a/web/src/features/v4-migration/V4MigrationSections.stories.tsx
+++ b/web/src/features/v4-migration/V4MigrationSections.stories.tsx
@@ -224,14 +224,42 @@ const combinedState = makeSdkState({
const apiUsage = [
{
- endpoint: "GET /api/public/traces",
- count: 1284,
+ endpoint: "GET /api/public/traces/{id}",
+ count: 1296,
lastSeen: new Date(Date.now() - 2 * HOUR_MS).toISOString(),
+ callers: [
+ {
+ sdkName: "python" as const,
+ sdkVersion: "3.9.0",
+ userAgent: "langfuse-python/3.9.0",
+ count: 1281,
+ lastSeen: new Date(Date.now() - 2 * HOUR_MS).toISOString(),
+ },
+ {
+ userAgent: "codex-cli/1.2.3",
+ count: 3,
+ lastSeen: new Date(Date.now() - 5 * HOUR_MS).toISOString(),
+ },
+ {
+ isOther: true as const,
+ count: 12,
+ lastSeen: new Date(Date.now() - 6 * HOUR_MS).toISOString(),
+ },
+ ],
},
{
- endpoint: "POST /api/public/scores",
+ endpoint: "GET /api/public/v2/scores",
count: 42,
lastSeen: new Date(Date.now() - 26 * HOUR_MS).toISOString(),
+ callers: [
+ {
+ sdkName: "javascript" as const,
+ sdkVersion: "5.4.0",
+ userAgent: "langfuse-js/5.4.0",
+ count: 42,
+ lastSeen: new Date(Date.now() - 26 * HOUR_MS).toISOString(),
+ },
+ ],
},
];
diff --git a/web/src/features/v4-migration/apiMigrationGuidance.clienttest.ts b/web/src/features/v4-migration/apiMigrationGuidance.clienttest.ts
new file mode 100644
index 0000000000..6a7875b794
--- /dev/null
+++ b/web/src/features/v4-migration/apiMigrationGuidance.clienttest.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it } from "vitest";
+import {
+ getApiMigrationGuidance,
+ getCodingAgentName,
+} from "./apiMigrationGuidance";
+
+describe("getApiMigrationGuidance", () => {
+ it("provides exact Python trace migration methods", () => {
+ expect(
+ getApiMigrationGuidance("GET /api/public/traces/{id}", "python", "3.9.0"),
+ ).toEqual({
+ currentMethod: "client.api.trace.get(...)",
+ replacementMethod: "client.api.observations.get_many(trace_id=trace_id)",
+ replacement: "GET /api/public/v2/observations",
+ minimumVersion: "4.0.0",
+ requiresUpgrade: true,
+ });
+ });
+
+ it("uses the language-specific Scores v3 client and version", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/v2/scores",
+ "javascript",
+ "5.4.0",
+ ),
+ ).toMatchObject({
+ currentMethod: "client.api.scores.getMany(...)",
+ replacementMethod: "client.api.scoresV3.getManyV3(...)",
+ minimumVersion: "5.5.0",
+ requiresUpgrade: true,
+ });
+ });
+
+ it("preserves the score ID when migrating the legacy score endpoint", () => {
+ expect(
+ getApiMigrationGuidance("GET /api/public/scores/{id}", "python", "4.8.1"),
+ ).toMatchObject({
+ currentMethod: "client.api.scores.get_by_id(...)",
+ replacementMethod: "client.api.scores_v3.get_many_v3(id=score_id)",
+ replacement: "GET /api/public/v3/scores?id=<score id>",
+ });
+ });
+
+ it("preserves the score ID when migrating the v2 score endpoint", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/v2/scores/{id}",
+ undefined,
+ undefined,
+ ),
+ ).toEqual({
+ replacement: "GET /api/public/v3/scores?id=<score id>",
+ });
+ });
+
+ it("bounds the observation ID lookup by time", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/observations/{id}",
+ "javascript",
+ "5.5.0",
+ ),
+ ).toMatchObject({
+ replacementMethod:
+ 'client.api.observations.getMany({ filter: "<id filter>", fromStartTime, toStartTime })',
+ replacement:
+ "GET /api/public/v2/observations?filter=<id filter>&fromStartTime=<from>&toStartTime=<to>",
+ });
+ });
+
+ it("includes the required v2 query when migrating daily metrics", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/metrics/daily",
+ undefined,
+ undefined,
+ ),
+ ).toEqual({
+ replacement:
+ "GET /api/public/v2/metrics?query=<URL-encoded JSON with view, metrics, fromTimestamp, and toTimestamp>",
+ });
+ });
+
+ it("warns that trace metrics have no drop-in v2 replacement", () => {
+ expect(
+ getApiMigrationGuidance("GET /api/public/metrics", "python", "4.8.1"),
+ ).toMatchObject({
+ replacementMethod: expect.stringContaining(
+ "traces view has no drop-in v2 replacement",
+ ),
+ replacement: expect.stringContaining(
+ "traces view has no drop-in v2 replacement",
+ ),
+ });
+ });
+
+ it("uses a bounded observation scan when migrating session listing", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/sessions",
+ "javascript",
+ "5.5.0",
+ ),
+ ).toMatchObject({
+ currentMethod: "client.api.sessions.list(...)",
+ replacementMethod:
+ "client.api.observations.getMany({ fromStartTime, toStartTime }) // group by sessionId",
+ replacement:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>, then group rows by sessionId",
+ });
+ });
+
+ it("preserves the session ID and time bounds when migrating session lookup", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/sessions/{id}",
+ "python",
+ "4.8.1",
+ ),
+ ).toMatchObject({
+ currentMethod: "client.api.sessions.get(...)",
+ replacementMethod:
+ 'client.api.observations.get_many(filter="<sessionId filter>", from_start_time=..., to_start_time=...)',
+ replacement:
+ "GET /api/public/v2/observations?filter=<sessionId filter>&fromStartTime=<from>&toStartTime=<to>",
+ });
+ });
+
+ it("recognizes a v-prefixed outdated SDK version", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/traces/{id}",
+ "python",
+ "v3.9.0",
+ ),
+ ).toMatchObject({ requiresUpgrade: true, minimumVersion: "4.0.0" });
+ });
+
+ it("shows the minimum SDK version when the attributed version is unknown", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/v2/scores",
+ "javascript",
+ undefined,
+ ),
+ ).toMatchObject({ requiresUpgrade: true, minimumVersion: "5.5.0" });
+ });
+
+ it("returns REST guidance without inventing an SDK method", () => {
+ expect(
+ getApiMigrationGuidance("GET /api/public/traces", undefined, undefined),
+ ).toEqual({
+ replacement: "GET /api/public/v2/observations",
+ });
+ });
+
+ it.each([
+ "GET /api/public/dataset-run-items",
+ "GET /api/public/datasets/{datasetName}/runs/{runName}",
+ ])(
+ "preserves dataset and renamed experiment filters for %s",
+ (entrypoint) => {
+ expect(
+ getApiMigrationGuidance(entrypoint, "javascript", "5.5.0"),
+ ).toMatchObject({
+ replacementMethod:
+ "client.api.experiments.listItems({ datasetId, experimentName: runName, fromStartTime })",
+ });
+ },
+ );
+
+ it("preserves the dataset filter when listing experiments", () => {
+ expect(
+ getApiMigrationGuidance(
+ "GET /api/public/datasets/{datasetName}/runs",
+ "python",
+ "4.8.1",
+ ),
+ ).toMatchObject({
+ replacementMethod:
+ "client.api.experiments.list(dataset_id=dataset_id, from_start_time=from_start_time)",
+ });
+ });
+});
+
+describe("getCodingAgentName", () => {
+ it.each([
+ ["codex-cli/1.2.3", "Codex"],
+ ["claude-code/1.0", "Claude Code"],
+ ["cursor-agent/0.9", "Cursor"],
+ ])("recognizes %s", (userAgent, expected) => {
+ expect(getCodingAgentName(userAgent)).toBe(expected);
+ });
+});
diff --git a/web/src/features/v4-migration/apiMigrationGuidance.ts b/web/src/features/v4-migration/apiMigrationGuidance.ts
new file mode 100644
index 0000000000..127b342d84
--- /dev/null
+++ b/web/src/features/v4-migration/apiMigrationGuidance.ts
@@ -0,0 +1,290 @@
+export type MigrationSdkName = "python" | "javascript";
+
+export type ApiMigrationGuidance = {
+ currentMethod?: string;
+ replacementMethod?: string;
+ replacement: string;
+ minimumVersion?: string;
+ requiresUpgrade?: boolean;
+};
+
+type SdkMethods = Record<
+ MigrationSdkName,
+ { current: string; replacement: string; minimumVersion?: string }
+>;
+
+const observationsMethods = (current: SdkMethods): SdkMethods => current;
+
+const guidanceByEndpoint: Record<
+ string,
+ { replacement: string; methods?: SdkMethods }
+> = {
+ "GET /api/public/traces": {
+ replacement: "GET /api/public/v2/observations",
+ methods: observationsMethods({
+ python: {
+ current: "client.api.trace.list(...)",
+ replacement:
+ "client.api.observations.get_many(from_start_time=..., to_start_time=...)",
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.trace.list(...)",
+ replacement:
+ "client.api.observations.getMany({ fromStartTime, toStartTime })",
+ minimumVersion: "4.0.0",
+ },
+ }),
+ },
+ "GET /api/public/traces/{id}": {
+ replacement: "GET /api/public/v2/observations",
+ methods: observationsMethods({
+ python: {
+ current: "client.api.trace.get(...)",
+ replacement: "client.api.observations.get_many(trace_id=trace_id)",
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.trace.get(...)",
+ replacement: "client.api.observations.getMany({ traceId })",
+ minimumVersion: "4.0.0",
+ },
+ }),
+ },
+ "GET /api/public/observations": {
+ replacement: "GET /api/public/v2/observations",
+ methods: {
+ python: {
+ current: "client.api.legacy.observations_v1.get_many(...)",
+ replacement:
+ "client.api.observations.get_many(from_start_time=..., to_start_time=...)",
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.legacy.observationsV1.getMany(...)",
+ replacement:
+ "client.api.observations.getMany({ fromStartTime, toStartTime })",
+ minimumVersion: "4.0.0",
+ },
+ },
+ },
+ "GET /api/public/observations/{id}": {
+ replacement:
+ "GET /api/public/v2/observations?filter=<id filter>&fromStartTime=<from>&toStartTime=<to>",
+ methods: {
+ python: {
+ current: "client.api.legacy.observations_v1.get(...)",
+ replacement:
+ 'client.api.observations.get_many(filter="<id filter>", from_start_time=..., to_start_time=...)',
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.legacy.observationsV1.get(...)",
+ replacement:
+ 'client.api.observations.getMany({ filter: "<id filter>", fromStartTime, toStartTime })',
+ minimumVersion: "4.0.0",
+ },
+ },
+ },
+ "GET /api/public/v2/scores": {
+ replacement: "GET /api/public/v3/scores",
+ methods: {
+ python: {
+ current: "client.api.scores.get_many(...)",
+ replacement: "client.api.scores_v3.get_many_v3(...)",
+ minimumVersion: "4.8.1",
+ },
+ javascript: {
+ current: "client.api.scores.getMany(...)",
+ replacement: "client.api.scoresV3.getManyV3(...)",
+ minimumVersion: "5.5.0",
+ },
+ },
+ },
+ "GET /api/public/v2/scores/{id}": {
+ replacement: "GET /api/public/v3/scores?id=<score id>",
+ methods: {
+ python: {
+ current: "client.api.scores.get_by_id(...)",
+ replacement: "client.api.scores_v3.get_many_v3(id=score_id)",
+ minimumVersion: "4.8.1",
+ },
+ javascript: {
+ current: "client.api.scores.getById(...)",
+ replacement: "client.api.scoresV3.getManyV3({ id: scoreId })",
+ minimumVersion: "5.5.0",
+ },
+ },
+ },
+ "GET /api/public/scores/{id}": {
+ replacement: "GET /api/public/v3/scores?id=<score id>",
+ methods: {
+ python: {
+ current: "client.api.scores.get_by_id(...)",
+ replacement: "client.api.scores_v3.get_many_v3(id=score_id)",
+ minimumVersion: "4.8.1",
+ },
+ javascript: {
+ current: "client.api.scores.getById(...)",
+ replacement: "client.api.scoresV3.getManyV3({ id: scoreId })",
+ minimumVersion: "5.5.0",
+ },
+ },
+ },
+ "GET /api/public/sessions": {
+ replacement:
+ "GET /api/public/v2/observations?fromStartTime=<from>&toStartTime=<to>, then group rows by sessionId",
+ methods: observationsMethods({
+ python: {
+ current: "client.api.sessions.list(...)",
+ replacement:
+ "client.api.observations.get_many(from_start_time=..., to_start_time=...) # group by session_id",
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.sessions.list(...)",
+ replacement:
+ "client.api.observations.getMany({ fromStartTime, toStartTime }) // group by sessionId",
+ minimumVersion: "4.0.0",
+ },
+ }),
+ },
+ "GET /api/public/sessions/{id}": {
+ replacement:
+ "GET /api/public/v2/observations?filter=<sessionId filter>&fromStartTime=<from>&toStartTime=<to>",
+ methods: {
+ python: {
+ current: "client.api.sessions.get(...)",
+ replacement:
+ 'client.api.observations.get_many(filter="<sessionId filter>", from_start_time=..., to_start_time=...)',
+ minimumVersion: "4.0.0",
+ },
+ javascript: {
+ current: "client.api.sessions.get(...)",
+ replacement:
+ 'client.api.observations.getMany({ filter: "<sessionId filter>", fromStartTime, toStartTime })',
+ minimumVersion: "4.0.0",
+ },
+ },
+ },
+ "GET /api/public/metrics": {
+ replacement:
+ "GET /api/public/v2/metrics with a supported observations or scores query; the traces view has no drop-in v2 replacement",
+ methods: {
+ python: {
+ current: "client.api.legacy.metrics_v1.metrics(...)",
+ replacement:
+ "client.api.metrics.metrics(...) with an observations or scores view; the traces view has no drop-in v2 replacement",
+ },
+ javascript: {
+ current: "client.api.legacy.metricsV1.metrics(...)",
+ replacement:
+ "client.api.metrics.metrics(...) with an observations or scores view; the traces view has no drop-in v2 replacement",
+ },
+ },
+ },
+ "GET /api/public/dataset-run-items": {
+ replacement:
+ "GET /api/public/experiment-items?datasetId=<dataset id>&experimentName=<run name>&fromStartTime=<ISO timestamp>",
+ methods: {
+ python: {
+ current: "client.api.dataset_run_items.list(...)",
+ replacement:
+ "client.api.experiments.list_items(dataset_id=dataset_id, experiment_name=run_name, from_start_time=from_start_time)",
+ },
+ javascript: {
+ current: "client.api.datasetRunItems.list(...)",
+ replacement:
+ "client.api.experiments.listItems({ datasetId, experimentName: runName, fromStartTime })",
+ },
+ },
+ },
+ "GET /api/public/datasets/{datasetName}/runs": {
+ replacement:
+ "GET /api/public/experiments?datasetId=<dataset id>&fromStartTime=<ISO timestamp>",
+ methods: {
+ python: {
+ current: "client.api.datasets.get_runs(...)",
+ replacement:
+ "client.api.experiments.list(dataset_id=dataset_id, from_start_time=from_start_time)",
+ },
+ javascript: {
+ current: "client.api.datasets.getRuns(...)",
+ replacement:
+ "client.api.experiments.list({ datasetId, fromStartTime })",
+ },
+ },
+ },
+ "GET /api/public/datasets/{datasetName}/runs/{runName}": {
+ replacement:
+ "GET /api/public/experiment-items?datasetId=<dataset id>&experimentName=<run name>&fromStartTime=<ISO timestamp>",
+ methods: {
+ python: {
+ current: "client.api.datasets.get_run(...)",
+ replacement:
+ "client.api.experiments.list_items(dataset_id=dataset_id, experiment_name=run_name, from_start_time=from_start_time)",
+ },
+ javascript: {
+ current: "client.api.datasets.getRun(...)",
+ replacement:
+ "client.api.experiments.listItems({ datasetId, experimentName: runName, fromStartTime })",
+ },
+ },
+ },
+};
+
+const genericReplacements: Record<string, string> = {
+ "GET /api/public/spans": "GET /api/public/v2/observations?type=SPAN",
+ "GET /api/public/generations":
+ "GET /api/public/v2/observations?type=GENERATION",
+ "GET /api/public/scores": "GET /api/public/v3/scores",
+ "GET /api/public/metrics/daily":
+ "GET /api/public/v2/metrics?query=<URL-encoded JSON with view, metrics, fromTimestamp, and toTimestamp>",
+};
+
+const isVersionBefore = (version: string, minimum: string): boolean => {
+ const parts = version
+ .match(/^v?\d+(?:\.\d+){0,2}/i)?.[0]
+ .replace(/^v/i, "")
+ .split(".")
+ .map(Number);
+ if (!parts) return false;
+ const minimumParts = minimum.split(".").map(Number);
+ for (const [index, minimumPart] of minimumParts.entries()) {
+ const part = parts[index] ?? 0;
+ if (part !== minimumPart) return part < minimumPart;
+ }
+ return false;
+};
+
+export const getApiMigrationGuidance = (
+ endpoint: string,
+ sdkName?: MigrationSdkName,
+ sdkVersion?: string,
+): ApiMigrationGuidance => {
+ const endpointGuidance = guidanceByEndpoint[endpoint];
+ const replacement =
+ endpointGuidance?.replacement ??
+ genericReplacements[endpoint] ??
+ "the replacement API in the migration guide";
+ const methods = sdkName ? endpointGuidance?.methods?.[sdkName] : undefined;
+ if (!methods) return { replacement };
+
+ return {
+ currentMethod: methods.current,
+ replacementMethod: methods.replacement,
+ replacement,
+ minimumVersion: methods.minimumVersion,
+ requiresUpgrade: methods.minimumVersion
+ ? !sdkVersion || isVersionBefore(sdkVersion, methods.minimumVersion)
+ : false,
+ };
+};
+
+export const getCodingAgentName = (userAgent?: string): string | undefined => {
+ if (!userAgent) return undefined;
+ if (/codex/i.test(userAgent)) return "Codex";
+ if (/claude[- /]?code/i.test(userAgent)) return "Claude Code";
+ if (/cursor/i.test(userAgent)) return "Cursor";
+ return undefined;
+};
diff --git a/web/src/features/v4-migration/hooks/useV4MigrationData.ts b/web/src/features/v4-migration/hooks/useV4MigrationData.ts
index 6be2acc074..c98c4c87d7 100644
--- a/web/src/features/v4-migration/hooks/useV4MigrationData.ts
+++ b/web/src/features/v4-migration/hooks/useV4MigrationData.ts
@@ -232,6 +232,12 @@ export function useProjectV4MigrationData(params: {
endpoint: normalizeLegacyApiEntrypoint(row.entrypoint),
count: row.count,
lastSeen: row.lastSeen,
+ callers: row.callers ?? [
+ {
+ count: row.count,
+ lastSeen: row.lastSeen,
+ },
+ ],
}))
.sort(
(left, right) =>
diff --git a/web/src/features/v4/server/v4TransitionQueryLogUsage.ts b/web/src/features/v4/server/v4TransitionQueryLogUsage.ts
index 03c3ece75d..4cc4e666d9 100644
--- a/web/src/features/v4/server/v4TransitionQueryLogUsage.ts
+++ b/web/src/features/v4/server/v4TransitionQueryLogUsage.ts
@@ -18,6 +18,7 @@ export type LegacyApiUsageSummaryByProjectResultRow = {
entrypoint: string;
count: number;
lastSeen: string;
+ callers?: CachedLegacyApiUsageRow["callers"];
};
/**
diff --git a/web/src/observability.config.ts b/web/src/observability.config.ts
index 9d9c91c7e6..170a489c9e 100644
--- a/web/src/observability.config.ts
+++ b/web/src/observability.config.ts
@@ -21,7 +21,8 @@ import { AwsInstrumentation } from "@opentelemetry/instrumentation-aws-sdk";
import { BullMQInstrumentation } from "@appsignal/opentelemetry-instrumentation-bullmq";
import {
SDK_NAME_ATTRIBUTE,
- extractSdkName,
+ SDK_VERSION_ATTRIBUTE,
+ extractSdkAttributes,
ioredisRequestHook,
} from "@langfuse/shared/instrumentation/bootstrap";
import { envDetector, resourceFromAttributes } from "@opentelemetry/resources";
@@ -142,8 +143,11 @@ const sdk = new NodeSDK({
// Incoming requests (IncomingMessage) carry headers; outgoing
// ClientRequests expose `path` instead.
if (!("path" in req) && req?.headers) {
- const sdkName = extractSdkName(req.headers);
+ const { sdkName, sdkVersion } = extractSdkAttributes(req.headers);
if (sdkName) span.setAttribute(SDK_NAME_ATTRIBUTE, sdkName);
+ if (sdkVersion) {
+ span.setAttribute(SDK_VERSION_ATTRIBUTE, sdkVersion);
+ }
}
},
}),
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 34ebafc0f1..618af7df63 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -27,6 +27,11 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";
import * as opentelemetry from "@opentelemetry/api";
import { env } from "@/src/env.mjs";
+import {
+ SDK_NAME_ATTRIBUTE,
+ SDK_VERSION_ATTRIBUTE,
+ extractSdkAttributes,
+} from "@langfuse/shared/instrumentation/bootstrap";
export const config = {
api: {
@@ -64,7 +69,9 @@ export default async function handler(
// add context of api call to the span
const currentSpan = getCurrentSpan();
- // get x-langfuse-xxx headers and add them to the span
+ // Preserve the raw x-langfuse-* attributes consumed by existing ingestion
+ // dashboards. The canonical attributes below are shared by all public API
+ // routes and intentionally use a bounded SDK name/version vocabulary.
Object.keys(req.headers).forEach((header) => {
if (
header.toLowerCase().startsWith("x-langfuse") ||
@@ -77,6 +84,14 @@ export default async function handler(
}
});
+ const { sdkName, sdkVersion } = extractSdkAttributes(req.headers);
+ if (sdkName) {
+ currentSpan?.setAttribute(SDK_NAME_ATTRIBUTE, sdkName);
+ }
+ if (sdkVersion) {
+ currentSpan?.setAttribute(SDK_VERSION_ATTRIBUTE, sdkVersion);
+ }
+
if (req.method !== "POST") throw new MethodNotAllowedError();
// CHECK AUTH FOR ALL EVENTS
diff --git a/worker/src/features/v4/__tests__/handleV4LegacyApiUsageJob.test.ts b/worker/src/features/v4/__tests__/handleV4LegacyApiUsageJob.test.ts
index 2184187c70..531834c358 100644
--- a/worker/src/features/v4/__tests__/handleV4LegacyApiUsageJob.test.ts
+++ b/worker/src/features/v4/__tests__/handleV4LegacyApiUsageJob.test.ts
@@ -120,12 +120,20 @@ const usageRow = (overrides: {
hourStart?: string;
projectId?: string;
route?: string;
+ sdkName?: string;
+ sdkVersion?: string;
+ userAgent?: string;
+ isOther?: number;
count?: string | number;
lastSeen?: string;
}) => ({
hourStart: overrides.hourStart ?? "2026-06-25T09:00:00Z",
projectId: overrides.projectId ?? "project-a",
route: overrides.route ?? "GET /api/public/traces",
+ sdkName: overrides.sdkName ?? "",
+ sdkVersion: overrides.sdkVersion ?? "",
+ userAgent: overrides.userAgent ?? "",
+ isOther: overrides.isOther ?? 0,
count: overrides.count ?? "4",
lastSeen: overrides.lastSeen ?? "2026-06-25T09:15:00.000000Z",
});
@@ -297,6 +305,101 @@ describe("handleV4LegacyApiUsageJob", () => {
});
});
+ it("keeps one endpoint total with separate SDK and user-agent callers", async () => {
+ const rows = [
+ usageRow({
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ }),
+ usageRow({
+ userAgent: "Codex CLI/1.2.3",
+ count: 1,
+ lastSeen: "2026-06-25T09:20:00.000000Z",
+ }),
+ ];
+ mocks.queryClickhouse.mockResolvedValue(rows);
+
+ await handleV4LegacyApiUsageJob();
+
+ const query = mocks.queryClickhouse.mock.calls[0]?.[0].query as string;
+ expect(query).toContain("JSONExtractString(log_comment, 'sdkName')");
+ expect(query).toContain("JSONExtractString(log_comment, 'sdkVersion')");
+ expect(query).toContain("JSONExtractString(log_comment, 'userAgent')");
+ expect(query).toContain(
+ "topK(20)(tuple(sdk_name, sdk_version, user_agent))",
+ );
+ expect(query).toContain("ANY INNER JOIN caller_candidates");
+ expect(query).toContain(
+ "GROUP BY hourStart, projectId, route, sdkName, sdkVersion, userAgent, isOther",
+ );
+
+ expect(
+ readJson(v4LegacyApiHourBucketKey(Date.parse("2026-06-25T09:00:00Z"))),
+ ).toMatchObject({
+ apiRows: [
+ {
+ projectId: "project-a",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 3,
+ lastSeen: "2026-06-25T09:20:00.000000Z",
+ callers: expect.arrayContaining([
+ {
+ sdkName: "python",
+ sdkVersion: "4.8.1",
+ userAgent: "langfuse-python/4.8.1",
+ count: 2,
+ lastSeen: "2026-06-25T09:15:00.000000Z",
+ },
+ {
+ userAgent: "Codex CLI/1.2.3",
+ count: 1,
+ lastSeen: "2026-06-25T09:20:00.000000Z",
+ },
+ ]),
+ },
+ ],
+ });
+ expect(readJson(v4LegacyApiUsageProjectKey("project-a"))).toMatchObject({
+ rows: [
+ {
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 3,
+ callers: expect.arrayContaining([
+ expect.objectContaining({ sdkName: "python", count: 2 }),
+ expect.objectContaining({
+ userAgent: "Codex CLI/1.2.3",
+ count: 1,
+ }),
+ ]),
+ },
+ ],
+ });
+ });
+
+ it("retains hour callers until the bounded project rollup", async () => {
+ mocks.queryClickhouse.mockResolvedValue([
+ ...Array.from({ length: 25 }, (_, index) =>
+ usageRow({ userAgent: `caller-${index}`, count: 1 }),
+ ),
+ usageRow({ isOther: 1, count: 3 }),
+ ]);
+
+ await handleV4LegacyApiUsageJob();
+
+ const hourBucket = readJson(
+ v4LegacyApiHourBucketKey(Date.parse("2026-06-25T09:00:00Z")),
+ );
+ const projectBlob = readJson(v4LegacyApiUsageProjectKey("project-a"));
+ expect(hourBucket.apiRows[0].callers).toHaveLength(26);
+ expect(projectBlob.rows[0].callers).toHaveLength(20);
+ expect(projectBlob.rows[0].callers.at(-1)).toMatchObject({
+ isOther: true,
+ count: 9,
+ });
+ });
+
it("incremental run: re-scans only the trailing margin and merges with existing buckets", async () => {
redisState.store.set(
V4_LEGACY_API_USAGE_CURSOR_KEY,
@@ -475,6 +578,38 @@ describe("handleV4LegacyApiUsageJob", () => {
});
});
+ it("deduplicates overlapping services with different tied caller partitions", async () => {
+ mocks.queryClickhouse
+ .mockResolvedValueOnce([
+ usageRow({ userAgent: "caller-a", count: 1 }),
+ usageRow({ isOther: 1, count: 99 }),
+ ])
+ .mockResolvedValueOnce([
+ usageRow({ userAgent: "caller-b", count: 1 }),
+ usageRow({ isOther: 1, count: 99 }),
+ ]);
+
+ await handleV4LegacyApiUsageJob();
+
+ expect(
+ readJson(v4LegacyApiHourBucketKey(Date.parse("2026-06-25T09:00:00Z"))),
+ ).toMatchObject({
+ apiRows: [
+ {
+ projectId: "project-a",
+ entrypoint: "publicapi: GET /api/public/traces",
+ count: 100,
+ },
+ ],
+ });
+ expect(
+ loggedInfo("v4 legacy API usage: merged query_log rows"),
+ ).toMatchObject({
+ inputServiceCount: 2,
+ uniqueResultSetCount: 1,
+ });
+ });
+
it("skips the run when another worker holds the lock", async () => {
redisState.store.set(V4_LEGACY_API_USAGE_LOCK_KEY, "someone-else");
diff --git a/worker/src/features/v4/handleV4LegacyApiUsageJob.ts b/worker/src/features/v4/handleV4LegacyApiUsageJob.ts
index ab7d823658..29ca0d5c9c 100644
--- a/worker/src/features/v4/handleV4LegacyApiUsageJob.ts
+++ b/worker/src/features/v4/handleV4LegacyApiUsageJob.ts
@@ -3,6 +3,7 @@ import {
convertDateToClickhouseDateTime,
listV4LegacyApiHourStarts,
logger,
+ mergeV4LegacyApiCallers,
queryClickhouse,
redis,
safeMultiDel,
@@ -27,6 +28,7 @@ import {
V4_LEGACY_API_USAGE_LOCK_KEY,
V4_LEGACY_API_USAGE_WINDOW_MS,
type PreferredClickhouseService,
+ type V4LegacyApiCaller,
type V4LegacyApiHourBucket,
} from "@langfuse/shared/src/server";
import { env } from "@langfuse/shared/src/env";
@@ -56,6 +58,7 @@ const HOUR_MS = 60 * 60 * 1000;
* the shared 30s default.
*/
const V4_LEGACY_API_USAGE_QUERY_TIMEOUT_MS = 10 * 60 * 1000;
+const V4_LEGACY_API_MAX_QUERY_CALLERS_PER_ENDPOINT = 20;
const EXPERIMENT_POST_ROUTE = "POST /api/public/dataset-run-items";
@@ -75,6 +78,10 @@ type HourUsageRow = {
hourStart: string;
projectId: string;
route: string;
+ sdkName: string;
+ sdkVersion: string;
+ userAgent: string;
+ isOther: number;
count: string | number;
lastSeen: string;
};
@@ -83,6 +90,10 @@ type MergedHourUsageRow = {
hourStart: string;
projectId: string;
route: string;
+ sdkName: string;
+ sdkVersion: string;
+ userAgent: string;
+ isOther: number;
count: number;
lastSeen: string;
};
@@ -129,6 +140,9 @@ const queryHourUsageRowsForService = async ({
WITH selected AS (
SELECT
JSONExtractString(log_comment, 'projectId') AS project_id,
+ JSONExtractString(log_comment, 'sdkName') AS sdk_name,
+ JSONExtractString(log_comment, 'sdkVersion') AS sdk_version,
+ JSONExtractString(log_comment, 'userAgent') AS user_agent,
event_time,
event_time_microseconds,
splitByChar('?', JSONExtractString(log_comment, 'route'))[1] AS route_path
@@ -146,6 +160,9 @@ WITH selected AS (
classified AS (
SELECT
project_id,
+ sdk_name,
+ sdk_version,
+ user_agent,
event_time,
event_time_microseconds,
multiIf(
@@ -197,18 +214,41 @@ classified AS (
NULL
) AS clickhouse_queries_per_api_call
FROM selected
+),
+caller_candidates AS (
+ SELECT
+ project_id,
+ legacy_route,
+ topK(${V4_LEGACY_API_MAX_QUERY_CALLERS_PER_ENDPOINT})(tuple(sdk_name, sdk_version, user_agent)) AS caller_keys
+ FROM classified
+ WHERE legacy_route IS NOT NULL
+ AND clickhouse_queries_per_api_call IS NOT NULL
+ GROUP BY project_id, legacy_route
+),
+bounded AS (
+ SELECT
+ classified.*,
+ has(caller_candidates.caller_keys, tuple(sdk_name, sdk_version, user_agent)) AS retain_caller
+ FROM classified
+ ANY INNER JOIN caller_candidates
+ ON classified.project_id = caller_candidates.project_id
+ AND classified.legacy_route = caller_candidates.legacy_route
+ WHERE classified.legacy_route IS NOT NULL
+ AND classified.clickhouse_queries_per_api_call IS NOT NULL
)
SELECT
formatDateTime(toStartOfHour(event_time, 'UTC'), '%Y-%m-%dT%H:%i:%SZ', 'UTC') AS hourStart,
project_id AS projectId,
legacy_route AS route,
+ if(retain_caller, sdk_name, '') AS sdkName,
+ if(retain_caller, sdk_version, '') AS sdkVersion,
+ if(retain_caller, user_agent, '') AS userAgent,
+ if(retain_caller, 0, 1) AS isOther,
sum(1.0 / clickhouse_queries_per_api_call) AS count,
formatDateTime(max(event_time_microseconds), '%Y-%m-%dT%H:%i:%S.%fZ', 'UTC') AS lastSeen
-FROM classified
-WHERE legacy_route IS NOT NULL
- AND clickhouse_queries_per_api_call IS NOT NULL
-GROUP BY hourStart, projectId, route
-ORDER BY hourStart ASC, projectId ASC, route ASC
+FROM bounded
+GROUP BY hourStart, projectId, route, sdkName, sdkVersion, userAgent, isOther
+ORDER BY hourStart ASC, projectId ASC, route ASC, isOther ASC, sdkName ASC, sdkVersion ASC, userAgent ASC
SETTINGS skip_unavailable_shards = 1
`,
params: {
@@ -242,8 +282,8 @@ SETTINGS skip_unavailable_shards = 1
/**
* Merges per-service results. Services pointing at overlapping replicas can
- * return identical result sets; those are deduplicated wholesale before
- * counts are summed, mirroring the request-path fallback behavior.
+ * return identical per-endpoint totals with different tied topK caller
+ * partitions. Deduplicate those service results before counts are summed.
*/
const mergeServiceRows = (
serviceRowSets: HourUsageRow[][],
@@ -254,15 +294,59 @@ const mergeServiceRows = (
(left, right) =>
left.hourStart.localeCompare(right.hourStart) ||
left.projectId.localeCompare(right.projectId) ||
- left.route.localeCompare(right.route),
+ left.route.localeCompare(right.route) ||
+ left.sdkName.localeCompare(right.sdkName) ||
+ left.sdkVersion.localeCompare(right.sdkVersion) ||
+ left.userAgent.localeCompare(right.userAgent) ||
+ left.isOther - right.isOther,
+ );
+ const endpointTotals = new Map<
+ string,
+ {
+ hourStart: string;
+ projectId: string;
+ route: string;
+ count: number;
+ lastSeen: string;
+ }
+ >();
+ for (const row of sortedRows) {
+ const key = [row.hourStart, row.projectId, row.route].join("\u0000");
+ const existing = endpointTotals.get(key);
+ endpointTotals.set(key, {
+ hourStart: row.hourStart,
+ projectId: row.projectId,
+ route: row.route,
+ count: (existing?.count ?? 0) + Number(row.count),
+ lastSeen:
+ existing && existing.lastSeen > row.lastSeen
+ ? existing.lastSeen
+ : row.lastSeen,
+ });
+ }
+ const resultSetKey = JSON.stringify(
+ Array.from(endpointTotals.values()).sort(
+ (left, right) =>
+ left.hourStart.localeCompare(right.hourStart) ||
+ left.projectId.localeCompare(right.projectId) ||
+ left.route.localeCompare(right.route),
+ ),
);
- uniqueServiceResultSets.set(JSON.stringify(sortedRows), sortedRows);
+ uniqueServiceResultSets.set(resultSetKey, sortedRows);
}
const merged = new Map<string, MergedHourUsageRow>();
for (const rows of uniqueServiceResultSets.values()) {
for (const row of rows) {
- const key = [row.hourStart, row.projectId, row.route].join("\u0000");
+ const key = [
+ row.hourStart,
+ row.projectId,
+ row.route,
+ row.sdkName,
+ row.sdkVersion,
+ row.userAgent,
+ row.isOther,
+ ].join("\u0000");
const existing = merged.get(key);
merged.set(
key,
@@ -279,6 +363,10 @@ const mergeServiceRows = (
hourStart: row.hourStart,
projectId: row.projectId,
route: row.route,
+ sdkName: row.sdkName,
+ sdkVersion: row.sdkVersion,
+ userAgent: row.userAgent,
+ isOther: row.isOther,
count: Number(row.count),
lastSeen: row.lastSeen,
},
@@ -351,14 +439,51 @@ const buildHourBuckets = ({
lastSeen: row.lastSeen,
});
} else {
- bucket.apiRows.push({
- projectId: row.projectId,
- entrypoint: `publicapi: ${row.route}`,
+ const entrypoint = `publicapi: ${row.route}`;
+ const existing = bucket.apiRows.find(
+ (apiRow) =>
+ apiRow.projectId === row.projectId &&
+ apiRow.entrypoint === entrypoint,
+ );
+ const caller: V4LegacyApiCaller = {
+ ...(row.isOther
+ ? { isOther: true as const }
+ : {
+ ...(row.sdkName === "python" || row.sdkName === "javascript"
+ ? { sdkName: row.sdkName }
+ : {}),
+ ...(row.sdkVersion ? { sdkVersion: row.sdkVersion } : {}),
+ ...(row.userAgent ? { userAgent: row.userAgent } : {}),
+ }),
count: row.count,
lastSeen: row.lastSeen,
- });
+ };
+ if (existing) {
+ existing.count += row.count;
+ existing.lastSeen =
+ existing.lastSeen > row.lastSeen ? existing.lastSeen : row.lastSeen;
+ existing.callers = mergeV4LegacyApiCallers(
+ [...(existing.callers ?? []), caller],
+ { maxCallers: null },
+ );
+ } else {
+ bucket.apiRows.push({
+ projectId: row.projectId,
+ entrypoint,
+ count: row.count,
+ lastSeen: row.lastSeen,
+ callers: [caller],
+ });
+ }
}
}
+ for (const bucket of buckets.values()) {
+ bucket.apiRows.sort(
+ (left, right) =>
+ left.projectId.localeCompare(right.projectId) ||
+ left.entrypoint.localeCompare(right.entrypoint),
+ );
+ }
return buckets;
};